From 9051ae4faf49bd23d5be52f9afa42030f3583db7 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 22:54:43 +0700 Subject: [PATCH 001/123] feat(sidebar): add a Table Details view option Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Settings/GeneralSettings.swift | 5 ++ .../TablePro/Resources/Localizable.xcstrings | 39 +++++----- ...abaseTreeOutlineCoordinator+Commands.swift | 2 +- .../DatabaseTreeOutlineCoordinator+Menu.swift | 1 + .../Menu/DatabaseTreeMenuContext.swift | 1 + .../Sidebar/Menu/SidebarMenuCommand.swift | 1 + .../Sidebar/Menu/SidebarViewOptionsMenu.swift | 10 +++ .../Models/GeneralSettingsTests.swift | 1 + ...tabaseTreeMenuSpecTests+TableDetails.swift | 71 +++++++++++++++++++ .../Sidebar/DatabaseTreeMenuSpecTests.swift | 2 + .../Sidebar/SidebarMenuBuilderTests.swift | 1 + 11 files changed, 115 insertions(+), 19 deletions(-) create mode 100644 apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 4babe30e3f..41fb8679f1 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -65,6 +65,7 @@ struct GeneralSettings: Codable, Equatable { var showObjectIcons: Bool var showSystemContainers: Bool var showPartitions: Bool + var showTableDetails: Bool var showWorkspaceRail: Bool var sidebarRowSize: SidebarRowSizePreference var connectionHealthCheck: ConnectionHealthCheck @@ -79,6 +80,7 @@ struct GeneralSettings: Codable, Equatable { showObjectIcons: true, showSystemContainers: false, showPartitions: true, + showTableDetails: false, showWorkspaceRail: true, sidebarRowSize: .matchSystem, connectionHealthCheck: .every30Seconds @@ -94,6 +96,7 @@ struct GeneralSettings: Codable, Equatable { showObjectIcons: Bool = true, showSystemContainers: Bool = false, showPartitions: Bool = true, + showTableDetails: Bool = false, showWorkspaceRail: Bool = true, sidebarRowSize: SidebarRowSizePreference = .matchSystem, connectionHealthCheck: ConnectionHealthCheck = .every30Seconds @@ -107,6 +110,7 @@ struct GeneralSettings: Codable, Equatable { self.showObjectIcons = showObjectIcons self.showSystemContainers = showSystemContainers self.showPartitions = showPartitions + self.showTableDetails = showTableDetails self.showWorkspaceRail = showWorkspaceRail self.sidebarRowSize = sidebarRowSize self.connectionHealthCheck = connectionHealthCheck @@ -124,6 +128,7 @@ struct GeneralSettings: Codable, Equatable { showObjectIcons = container.decodeSetting(.showObjectIcons, default: fallback.showObjectIcons) showSystemContainers = container.decodeSetting(.showSystemContainers, default: fallback.showSystemContainers) showPartitions = container.decodeSetting(.showPartitions, default: fallback.showPartitions) + showTableDetails = container.decodeSetting(.showTableDetails, default: fallback.showTableDetails) showWorkspaceRail = container.decodeSetting(.showWorkspaceRail, default: fallback.showWorkspaceRail) sidebarRowSize = container.decodeSetting(.sidebarRowSize, default: fallback.sidebarRowSize) connectionHealthCheck = container.decodeSetting(.connectionHealthCheck, default: fallback.connectionHealthCheck) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 8ecb808b3c..484159124a 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -16501,6 +16501,9 @@ } } } + }, + "A plan works on up to 3 devices at a time. Removing one signs TablePro out there." : { + }, "A point's id cannot change. Insert a new row with the new id instead." : { "extractionState" : "manual", @@ -16508,9 +16511,6 @@ }, "A publish to the team library is still running. Try again when it finishes." : { - }, - "A plan works on up to 3 devices at a time. Removing one signs TablePro out there." : { - }, "a query" : { "localizations" : { @@ -168745,15 +168745,15 @@ } } } - }, - "Signing in with credentials from this Mac was not approved." : { - }, "Signing in" : { }, "Signing in by email? Type the 6-digit code from the email in the sign-in sheet. The link in the email opens your browser instead." : { + }, + "Signing in with credentials from this Mac was not approved." : { + }, "Signing in…" : { "localizations" : { @@ -179419,6 +179419,9 @@ } } } + }, + "Table Details" : { + }, "Table Favorites" : { "localizations" : { @@ -194656,9 +194659,6 @@ } } } - }, - "The text at byte %lld is not valid UTF-8." : { - }, "The team library asked TablePro to download it again." : { @@ -194674,6 +194674,9 @@ }, "The team library refused the change. It may be too large or hold a field the library never stores." : { + }, + "The text at byte %lld is not valid UTF-8." : { + }, "The text could not be parsed as JSON." : { "localizations" : { @@ -217859,6 +217862,15 @@ } } } + }, + "You were signed out. Sign in again." : { + + }, + "You're on Free" : { + + }, + "You're signed in" : { + }, "You've used TablePro on %lld days" : { "localizations" : { @@ -217899,15 +217911,6 @@ } } } - }, - "You were signed out. Sign in again." : { - - }, - "You're on Free" : { - - }, - "You're signed in" : { - }, "Your account is not allowed to read the source of %@" : { "extractionState" : "manual", diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift index e406897762..ce7738617b 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift @@ -152,7 +152,7 @@ extension DatabaseTreeOutlineCoordinator { case .openRedisKey(let key, let keyType): mainCoordinator?.openRedisKey(key, keyType: keyType) case .toggleObjectIcons, .toggleObjectComments, .toggleSystemContainers, .togglePartitions, - .setRowSize: + .toggleTableDetails, .setRowSize: _ = SidebarViewOptionsMenu.apply(command) } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift index d48854232f..51e7267908 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift @@ -91,6 +91,7 @@ extension DatabaseTreeOutlineCoordinator: NSMenuDelegate { showObjectComments: settings.showObjectComments, showSystemContainers: settings.showSystemContainers, showPartitions: settings.showPartitions, + showTableDetails: settings.showTableDetails, rowSize: settings.sidebarRowSize, canFilterDatabases: PluginManager.shared.supportsDatabaseTree(for: databaseType) && sidebarState?.sidebarLayout == .tree, diff --git a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift index 0def1ddf99..b604a70942 100644 --- a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift +++ b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift @@ -46,6 +46,7 @@ internal struct DatabaseTreeMenuContext { internal let showObjectComments: Bool internal let showSystemContainers: Bool internal let showPartitions: Bool + internal var showTableDetails: Bool = false internal let rowSize: SidebarRowSizePreference internal var canFilterDatabases: Bool = false internal var hasDatabaseFilter: Bool = false diff --git a/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift b/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift index 0357e60911..4c9725b627 100644 --- a/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift +++ b/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift @@ -90,6 +90,7 @@ internal enum SidebarMenuCommand: Equatable { case toggleObjectComments case toggleSystemContainers case togglePartitions + case toggleTableDetails case setRowSize(SidebarRowSizePreference) } diff --git a/apple/TablePro/Views/Sidebar/Menu/SidebarViewOptionsMenu.swift b/apple/TablePro/Views/Sidebar/Menu/SidebarViewOptionsMenu.swift index 7de83d46eb..fc45df573b 100644 --- a/apple/TablePro/Views/Sidebar/Menu/SidebarViewOptionsMenu.swift +++ b/apple/TablePro/Views/Sidebar/Menu/SidebarViewOptionsMenu.swift @@ -26,6 +26,7 @@ internal enum SidebarViewOptionsMenu { showObjectComments: context.showObjectComments, showSystemContainers: context.showSystemContainers, showPartitions: context.showPartitions, + showTableDetails: context.showTableDetails, rowSize: context.rowSize ) } @@ -35,6 +36,7 @@ internal enum SidebarViewOptionsMenu { showObjectComments: Bool, showSystemContainers: Bool, showPartitions: Bool, + showTableDetails: Bool, rowSize: SidebarRowSizePreference ) -> [DatabaseTreeMenuSection] { [ @@ -58,6 +60,11 @@ internal enum SidebarViewOptionsMenu { title: String(localized: "Partitions"), command: .togglePartitions, isOn: showPartitions + )), + .command(SidebarMenuEntry( + title: String(localized: "Table Details"), + command: .toggleTableDetails, + isOn: showTableDetails )) ]), DatabaseTreeMenuSection(SidebarRowSizePreference.allCases.map { size in @@ -85,6 +92,8 @@ internal enum SidebarViewOptionsMenu { AppSettingsManager.shared.general.showSystemContainers.toggle() case .togglePartitions: AppSettingsManager.shared.general.showPartitions.toggle() + case .toggleTableDetails: + AppSettingsManager.shared.general.showTableDetails.toggle() case .setRowSize(let size): AppSettingsManager.shared.general.sidebarRowSize = size default: @@ -103,6 +112,7 @@ internal enum SidebarViewOptionsMenu { showObjectComments: settings.showObjectComments, showSystemContainers: settings.showSystemContainers, showPartitions: settings.showPartitions, + showTableDetails: settings.showTableDetails, rowSize: settings.sidebarRowSize ) } diff --git a/apple/TableProTests/Models/GeneralSettingsTests.swift b/apple/TableProTests/Models/GeneralSettingsTests.swift index 857025d5e5..991468ecbd 100644 --- a/apple/TableProTests/Models/GeneralSettingsTests.swift +++ b/apple/TableProTests/Models/GeneralSettingsTests.swift @@ -69,6 +69,7 @@ struct GeneralSettingsBoolSettingTests { BoolSetting(key: "showObjectIcons", defaultValue: true), BoolSetting(key: "showSystemContainers", defaultValue: false), BoolSetting(key: "showPartitions", defaultValue: true), + BoolSetting(key: "showTableDetails", defaultValue: false), BoolSetting(key: "showWorkspaceRail", defaultValue: true), ] diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift new file mode 100644 index 0000000000..3fdad4298f --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift @@ -0,0 +1,71 @@ +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +extension DatabaseTreeMenuSpecTests { + private func viewOptionEntries(_ sections: [DatabaseTreeMenuSection]) -> [SidebarMenuEntry] { + sections.flatMap { $0.items }.compactMap { item -> SidebarMenuEntry? in + guard case .command(let entry) = item else { return nil } + return entry + } + } + + @Test("View Options lists Table Details right after Partitions, with its own state") + func viewOptionsOfferTableDetails() { + let sections = SidebarViewOptionsMenu.sections( + showObjectIcons: true, + showObjectComments: true, + showSystemContainers: true, + showPartitions: true, + showTableDetails: false, + rowSize: .matchSystem + ) + let toggles = viewOptionEntries(Array(sections.prefix(1))) + let commands = toggles.map { $0.command } + let expected: [SidebarMenuCommand] = [ + .toggleObjectIcons, .toggleObjectComments, .toggleSystemContainers, .togglePartitions, .toggleTableDetails + ] + + #expect(commands == expected) + #expect(toggles.last?.title == String(localized: "Table Details")) + #expect(toggles.last?.isOn == false) + } + + @Test("The empty-area menu reads Table Details from its context") + func viewOptionsReadTableDetailsFromTheContext() { + var menuContext = context(clicked: nil) + menuContext.showTableDetails = true + let state = viewOptionEntries(SidebarViewOptionsMenu.sections(menuContext)) + .first { $0.command == .toggleTableDetails }? + .isOn + + #expect(state == true) + } +} + +extension GlobalStateSuites { + @MainActor + struct TableDetailsViewOptionsTests { + @Test( + "Table Details in View Options starts off and flips the setting", + .appSettings { $0.general.showTableDetails = false } + ) + func viewOptionsEntryWritesTheSetting() throws { + let found = SidebarViewOptionsMenu.currentSections() + .flatMap { $0.items } + .lazy + .compactMap { item -> SidebarMenuEntry? in + guard case .command(let entry) = item, entry.command == .toggleTableDetails else { return nil } + return entry + } + .first + let entry = try #require(found) + #expect(entry.isOn == false) + + #expect(SidebarViewOptionsMenu.apply(entry.command)) + + #expect(AppSettingsManager.shared.general.showTableDetails) + } + } +} diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift index 37660fb554..73dca888e4 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift @@ -366,6 +366,7 @@ struct DatabaseTreeMenuSpecTests { showObjectComments: true, showSystemContainers: true, showPartitions: true, + showTableDetails: false, rowSize: .matchSystem ) let items = sections.first?.items ?? [] @@ -387,6 +388,7 @@ struct DatabaseTreeMenuSpecTests { showObjectComments: true, showSystemContainers: true, showPartitions: false, + showTableDetails: false, rowSize: .matchSystem ) let states: [Bool?] = (sections.first?.items ?? []).compactMap { item in diff --git a/apple/TableProTests/Views/Sidebar/SidebarMenuBuilderTests.swift b/apple/TableProTests/Views/Sidebar/SidebarMenuBuilderTests.swift index 1793a25ed4..6e7a8aa26a 100644 --- a/apple/TableProTests/Views/Sidebar/SidebarMenuBuilderTests.swift +++ b/apple/TableProTests/Views/Sidebar/SidebarMenuBuilderTests.swift @@ -134,6 +134,7 @@ struct SidebarMenuBuilderTests { showObjectComments: settings.showObjectComments, showSystemContainers: settings.showSystemContainers, showPartitions: settings.showPartitions, + showTableDetails: settings.showTableDetails, rowSize: settings.sidebarRowSize ) From 5d4ddc1e83001c436c89fb1b82d305bf42e62a6e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:05:22 +0700 Subject: [PATCH 002/123] feat(sidebar): load a table's detail lists in the tree metadata service Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/DatabaseTreeMetadataService.swift | 68 ++++++++++ .../Models/Database/TableDetailList.swift | 41 ++++++ ...DatabaseTreeTableDetailsServiceTests.swift | 123 ++++++++++++++++++ .../SchemaRefreshCommitCostTests.swift | 46 +++++++ 4 files changed, 278 insertions(+) create mode 100644 apple/TablePro/Models/Database/TableDetailList.swift create mode 100644 apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift diff --git a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift index f7e894e09b..75e7625532 100644 --- a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift +++ b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift @@ -33,6 +33,14 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { let table: String } + struct TableDetailsKey: Hashable, Sendable { + let connectionId: UUID + let database: String + let schema: String? + let table: String + let kind: TableDetailKind + } + /// Carries the revision it started under, so a read after a change never joins a fetch that /// began before it. struct ListFetchKey: Hashable, Sendable { @@ -67,6 +75,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { @Published private(set) var triggersState: [ObjectsKey: MetadataLoadState<[TriggerInfo]>] = [:] @Published private(set) var typesState: [ObjectsKey: MetadataLoadState<[UserDefinedTypeInfo]>] = [:] @Published private(set) var partitionsState: [PartitionsKey: MetadataLoadState<[PartitionInfo]>] = [:] + @Published private(set) var tableDetailsState: [TableDetailsKey: MetadataLoadState] = [:] @Published private(set) var allSchemaTablesState: [DatabaseKey: MetadataLoadState] = [:] @Published private(set) var listsRevisions: [UUID: Int] = [:] @@ -77,6 +86,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { private let triggersDedup = OnceTask, [TriggerInfo]>() private let typesDedup = OnceTask, [UserDefinedTypeInfo]>() private let partitionsDedup = OnceTask, [PartitionInfo]>() + private let tableDetailsDedup = OnceTask, TableDetailList>() private let allSchemaTablesDedup = OnceTask() private var databaseListFence = CommitFence() @@ -86,6 +96,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { private var triggersCommit = ListCommitState() private var typesCommit = ListCommitState() private var partitionsCommit = ListCommitState() + private var tableDetailsCommit = ListCommitState() private var allSchemaTablesFence = CommitFence() private var allSchemaTablesFreshness = CatalogFreshness() private var allSchemaTablesRequested: [DatabaseKey: CatalogTableListing.SchemaSelection] = [:] @@ -121,6 +132,10 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { TreeList(state: \.partitionsState, commit: \.partitionsCommit, dedup: partitionsDedup, label: "partitions") } + private var tableDetailLists: TreeList { + TreeList(state: \.tableDetailsState, commit: \.tableDetailsCommit, dedup: tableDetailsDedup, label: "table details") + } + // MARK: - Reads func databaseListState(for connectionId: UUID) -> MetadataLoadState<[DatabaseMetadata]> { @@ -180,6 +195,13 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { return partitionsState[key] ?? .idle } + func tableDetailsLoadState( + connectionId: UUID, database: String, schema: String?, table: String, kind: TableDetailKind + ) -> MetadataLoadState { + let key = Self.tableDetailsKey(connectionId: connectionId, database: database, schema: schema, table: table, kind: kind) + return tableDetailsState[key] ?? .idle + } + func allSchemaTablesLoadState( connectionId: UUID, database: String ) -> MetadataLoadState { @@ -241,6 +263,14 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { ) } + func tableDetailsNeedFetch( + connectionId: UUID, database: String, schema: String?, table: String, kind: TableDetailKind + ) -> Bool { + isConnected(connectionId) && tableDetailsCommit.freshness.needsFetch( + Self.tableDetailsKey(connectionId: connectionId, database: database, schema: schema, table: table, kind: kind) + ) + } + func listsRevision(for connectionId: UUID) -> Int { listsRevisions[connectionId] ?? 0 } @@ -512,6 +542,14 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { await read(key, connectionId: connectionId, in: partitionLists, fetch: partitionListFetch(key)) } + /// One kind for one table: a group reads its own list and nothing beside it. + func loadTableDetails( + connectionId: UUID, database: String, schema: String?, table: String, kind: TableDetailKind + ) async { + let key = Self.tableDetailsKey(connectionId: connectionId, database: database, schema: schema, table: table, kind: kind) + await read(key, connectionId: connectionId, in: tableDetailLists, fetch: tableDetailFetch(key)) + } + /// Reads only the kinds that need it, so a container whose tables alone a change overtook reads /// its tables alone. func loadObjects(connectionId: UUID, database: String, schema: String?) async { @@ -776,6 +814,29 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { } } + private func tableDetailFetch(_ key: TableDetailsKey) -> @Sendable () async throws -> TableDetailList { + let table = key.table + let schema = key.schema + let kind = key.kind + return { [self] in + try await withDriver(connectionId: key.connectionId, database: key.database) { driver in + try await Self.fetchTableDetails(kind, table: table, schema: schema, from: driver) + } + } + } + + nonisolated private static func fetchTableDetails( + _ kind: TableDetailKind, table: String, schema: String?, from driver: DatabaseDriver + ) async throws -> TableDetailList { + switch kind { + case .columns: return .columns(try await driver.fetchColumns(table: table, schema: schema)) + case .indexes: return .indexes(try await driver.fetchIndexes(table: table, schema: schema)) + case .foreignKeys: return .foreignKeys(try await driver.fetchForeignKeys(table: table, schema: schema)) + case .checks: return .checks(try await driver.fetchCheckConstraints(table: table, schema: schema)) + case .triggers: return .triggers(try await driver.fetchTriggers(table: table, schema: schema)) + } + } + // MARK: - Lifecycle /// A fetch still running on the replaced driver answers for the old session, so every key is @@ -929,6 +990,13 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { return PartitionsKey(connectionId: connectionId, database: database, schema: normalized, table: table) } + private static func tableDetailsKey( + connectionId: UUID, database: String, schema: String?, table: String, kind: TableDetailKind + ) -> TableDetailsKey { + let normalized: String? = (schema?.isEmpty == true) ? nil : schema + return TableDetailsKey(connectionId: connectionId, database: database, schema: normalized, table: table, kind: kind) + } + private func partitionKeys(matching key: ObjectsKey) -> [PartitionsKey] { partitionsState.keys.filter { $0.connectionId == key.connectionId && $0.database == key.database && $0.schema == key.schema diff --git a/apple/TablePro/Models/Database/TableDetailList.swift b/apple/TablePro/Models/Database/TableDetailList.swift new file mode 100644 index 0000000000..3c7129afbe --- /dev/null +++ b/apple/TablePro/Models/Database/TableDetailList.swift @@ -0,0 +1,41 @@ +// +// TableDetailList.swift +// TablePro +// + +import Foundation + +/// The per-table lists a sidebar table row can show. Each loads on its own, so opening Columns +/// costs one read and leaves the other lists unread. +enum TableDetailKind: String, CaseIterable, Hashable, Sendable { + case columns + case indexes + case foreignKeys + case checks + case triggers +} + +/// The groups under a table row: one per detail list, plus the table's partitions. The raw value is +/// saved with a window's open groups, so a case is never renamed. +enum TableDetailGroupKind: String, CaseIterable, Hashable, Sendable { + case columns + case indexes + case foreignKeys + case checks + case triggers + case partitions + + /// Nil for partitions, which the tree reads through its partition lists. + var detailKind: TableDetailKind? { + TableDetailKind(rawValue: rawValue) + } +} + +/// One detail list as the driver answered it. +enum TableDetailList: Hashable, Sendable { + case columns([ColumnInfo]) + case indexes([IndexInfo]) + case foreignKeys([ForeignKeyInfo]) + case checks([CheckConstraintInfo]) + case triggers([TriggerInfo]) +} diff --git a/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift new file mode 100644 index 0000000000..563ae44e97 --- /dev/null +++ b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift @@ -0,0 +1,123 @@ +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProSQLGrammar +import Testing + +/// A table's detail lists load one kind at a time, the first time its group opens, and follow the +/// catalog the way partition lists do. PGlite keeps every read on the injected session driver. +@MainActor +struct DatabaseTreeTableDetailsServiceTests { + private struct ReadFailed: Error {} + + private let service = DatabaseTreeMetadataService.shared + + private func connect() -> (DatabaseConnection, CatalogReadCountingDriver) { + let connection = TestFixtures.makeConnection(type: .pglite) + let driver = CatalogReadCountingDriver(connection: connection) + driver.columnsByTable["orders"] = [ + TestFixtures.makeColumnInfo(name: "id", dataType: "integer"), + TestFixtures.makeColumnInfo(name: "total", dataType: "numeric", isPrimaryKey: false), + ] + driver.indexesByTable["orders"] = [ + IndexInfo(name: "orders_pkey", columns: ["id"], isUnique: true, isPrimary: true, type: "BTREE") + ] + driver.foreignKeysByTable["orders"] = [TestFixtures.makeForeignKeyInfo(name: "orders_user_fk")] + driver.checksByTable["orders"] = [CheckConstraintInfo(name: "total_positive", expression: "total > 0")] + driver.triggersByTable["orders"] = [ + TriggerInfo(name: "orders_audit", timing: "AFTER", event: "INSERT", statement: "") + ] + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + DatabaseManager.shared.injectSession(session, for: connection.id) + return (connection, driver) + } + + private func disconnect(_ connection: DatabaseConnection) async { + await service.handleDisconnect(connectionId: connection.id) + DatabaseManager.shared.removeSession(for: connection.id) + } + + private func load(_ connection: DatabaseConnection, _ kind: TableDetailKind) async { + await service.loadTableDetails( + connectionId: connection.id, database: connection.database, schema: "public", table: "orders", kind: kind + ) + } + + private func state(_ connection: DatabaseConnection, _ kind: TableDetailKind) -> MetadataLoadState { + service.tableDetailsLoadState( + connectionId: connection.id, database: connection.database, schema: "public", table: "orders", kind: kind + ) + } + + private func needsFetch(_ connection: DatabaseConnection, _ kind: TableDetailKind) -> Bool { + service.tableDetailsNeedFetch( + connectionId: connection.id, database: connection.database, schema: "public", table: "orders", kind: kind + ) + } + + private func columnNames(_ connection: DatabaseConnection) -> [String] { + guard case .loaded(.columns(let columns)) = state(connection, .columns) else { return [] } + return columns.map { $0.name } + } + + @Test("Each kind is read once, by its own call, with two callers asking at once") + func eachKindReadsOnce() async { + let (connection, driver) = connect() + + for kind in TableDetailKind.allCases { + async let first: Void = load(connection, kind) + async let second: Void = load(connection, kind) + _ = await (first, second) + } + + #expect(driver.detailReads == [ + "columns:orders", "indexes:orders", "foreignKeys:orders", "checks:orders", "triggers:orders" + ]) + #expect(columnNames(connection) == ["id", "total"]) + for kind in TableDetailKind.allCases { + #expect(!needsFetch(connection, kind), "\(kind)") + } + await disconnect(connection) + } + + @Test("Opening one group reads that kind alone and leaves the rest unread") + func oneKindReadsAlone() async { + let (connection, driver) = connect() + + await load(connection, .indexes) + + #expect(driver.detailReads == ["indexes:orders"]) + #expect(state(connection, .columns) == .idle) + #expect(needsFetch(connection, .columns)) + #expect(!needsFetch(connection, .indexes)) + await disconnect(connection) + } + + @Test("A failed first read shows its failure and is not asked for again until a change") + func failedFirstRead() async { + let (connection, driver) = connect() + driver.detailError = ReadFailed() + + await load(connection, .checks) + + #expect(state(connection, .checks).erased.failureMessage != nil) + #expect(!needsFetch(connection, .checks)) + await disconnect(connection) + } + + @Test("Nothing reads while the session is not connected") + func nothingReadsWhileNotConnected() async { + let (connection, driver) = connect() + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connecting + DatabaseManager.shared.injectSession(session, for: connection.id) + + #expect(!needsFetch(connection, .columns)) + await load(connection, .columns) + + #expect(state(connection, .columns) == .idle) + #expect(driver.detailReads.isEmpty) + await disconnect(connection) + } +} diff --git a/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift b/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift index 5fa76465ce..13894b95e5 100644 --- a/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift +++ b/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift @@ -19,9 +19,16 @@ final class CatalogReadCountingDriver: DatabaseDriver, @unchecked Sendable { var allSchemaTables: [TableInfo]? var answersTablesInSchemas = false var partitionsByTable: [String: [PartitionInfo]] = [:] + var columnsByTable: [String: [ColumnInfo]] = [:] + var indexesByTable: [String: [IndexInfo]] = [:] + var foreignKeysByTable: [String: [ForeignKeyInfo]] = [:] + var checksByTable: [String: [CheckConstraintInfo]] = [:] + var triggersByTable: [String: [TriggerInfo]] = [:] + var detailError: Error? private let lock = NSLock() private var readLog: [String] = [] + private var detailReadLog: [String] = [] private var pauseNextTableFetch = false private var tableFetchPausedHandler: (@Sendable () -> Void)? private var tableFetchGate: CheckedContinuation? @@ -34,6 +41,12 @@ final class CatalogReadCountingDriver: DatabaseDriver, @unchecked Sendable { lock.withLock { readLog } } + /// The per-table reads a sidebar table's detail groups send. Kept apart from `reads`, so a count + /// of catalog reads never picks up a column lookup another path makes on this driver. + var detailReads: [String] { + lock.withLock { detailReadLog } + } + var pausesNextTableFetch: Bool { get { lock.withLock { pauseNextTableFetch } } set { lock.withLock { pauseNextTableFetch = newValue } } @@ -144,6 +157,39 @@ final class CatalogReadCountingDriver: DatabaseDriver, @unchecked Sendable { return partitionsByTable[table] ?? [] } + func fetchColumns(table: String, schema: String?) async throws -> [ColumnInfo] { + try await answerDetail("columns", table: table, columnsByTable[table] ?? []) + } + + func fetchIndexes(table: String, schema: String?) async throws -> [IndexInfo] { + try await answerDetail("indexes", table: table, indexesByTable[table] ?? []) + } + + func fetchForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] { + try await answerDetail("foreignKeys", table: table, foreignKeysByTable[table] ?? []) + } + + func fetchCheckConstraints(table: String, schema: String?) async throws -> [CheckConstraintInfo] { + try await answerDetail("checks", table: table, checksByTable[table] ?? []) + } + + func fetchTriggers(table: String, schema: String?) async throws -> [TriggerInfo] { + try await answerDetail("triggers", table: table, triggersByTable[table] ?? []) + } + + /// Shares the table read's pause gate, so a test holds whichever read it starts next. + private func answerDetail(_ kind: String, table: String, _ value: Value) async throws -> Value { + lock.withLock { detailReadLog.append("\(kind):\(table)") } + if let detailError { throw detailError } + if takeTableFetchPause() { + await withCheckedContinuation { continuation in + park(continuation) + } + try Task.checkCancellation() + } + return value + } + func fetchRoutines(schema: String?) async throws -> [RoutineInfo] { record(schema.map { "routines:\($0)" } ?? "routines") return [] From 20fff316c5b8f2801f00e6150facd41f35ffc0f4 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:10:10 +0700 Subject: [PATCH 003/123] feat(sidebar): keep table detail lists in step with catalog changes and the connection Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- ...aseTreeMetadataService+CatalogChange.swift | 16 ++- .../Query/DatabaseTreeMetadataService.swift | 36 ++++++- .../DatabaseTreeCatalogRefreshPlanTests.swift | 55 ++++++++++ ...DatabaseTreeTableDetailsServiceTests.swift | 102 ++++++++++++++++++ 4 files changed, 205 insertions(+), 4 deletions(-) diff --git a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService+CatalogChange.swift b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService+CatalogChange.swift index 4e47982744..b1f7d6c063 100644 --- a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService+CatalogChange.swift +++ b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService+CatalogChange.swift @@ -15,6 +15,7 @@ struct CatalogTreeRefreshPlan: Equatable, Sendable { /// Planned from their own keys: a flat or hierarchical tree takes its tables from `SchemaService`, /// so a loaded partition list can have no table list beside it. var partitions: Set = [] + var tableDetails: Set = [] var routines: Set = [] var triggers: Set = [] var types: Set = [] @@ -22,7 +23,8 @@ struct CatalogTreeRefreshPlan: Equatable, Sendable { var isEmpty: Bool { !refreshesDatabaseList && schemaLists.isEmpty && tables.isEmpty && partitions.isEmpty - && routines.isEmpty && triggers.isEmpty && types.isEmpty && allSchemaTables.isEmpty + && tableDetails.isEmpty && routines.isEmpty && triggers.isEmpty && types.isEmpty + && allSchemaTables.isEmpty } } @@ -40,6 +42,7 @@ extension DatabaseTreeMetadataService { schemaListKeys: schemaList.keys, tableKeys: tablesState.keys, partitionKeys: partitionsState.keys, + tableDetailKeys: tableDetailsState.keys, routineKeys: routinesState.keys, triggerKeys: triggersState.keys, typeKeys: typesState.keys, @@ -62,6 +65,7 @@ extension DatabaseTreeMetadataService { schemaListKeys: schemaList.keys, tableKeys: tablesState.keys, partitionKeys: partitionsState.keys, + tableDetailKeys: tableDetailsState.keys, routineKeys: routinesState.keys, triggerKeys: triggersState.keys, typeKeys: typesState.keys, @@ -77,6 +81,7 @@ extension DatabaseTreeMetadataService { schemaListKeys: some Sequence, tableKeys: some Sequence, partitionKeys: some Sequence = EmptyCollection(), + tableDetailKeys: some Sequence = EmptyCollection(), routineKeys: some Sequence, triggerKeys: some Sequence, typeKeys: some Sequence, @@ -105,6 +110,15 @@ extension DatabaseTreeMetadataService { key.connectionId == change.connectionId && change.reaches(database: key.database) }) } + // By database alone, as partitions are: a key in another schema can point at the table a change dropped. + let reachesDetails = change.kinds.contains(.tables) + let reachesTriggerDetails = reachesDetails || change.kinds.contains(.triggers) + if reachesTriggerDetails { + plan.tableDetails = Set(tableDetailKeys.filter { key in + key.connectionId == change.connectionId && change.reaches(database: key.database) + && (reachesDetails || key.kind == .triggers) + }) + } plan.routines = objectKeys(routineKeys, for: .routines) plan.triggers = objectKeys(triggerKeys, for: .triggers) plan.types = objectKeys(typeKeys, for: .types) diff --git a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift index 75e7625532..e52ca3188d 100644 --- a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift +++ b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift @@ -290,6 +290,10 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { partitionsCommit.freshness.markChanged(key) marked = true } + for key in plan.tableDetails { + tableDetailsCommit.freshness.markChanged(key) + marked = true + } for key in plan.routines { routinesCommit.freshness.markChanged(key) marked = true @@ -614,13 +618,14 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { _ = await (tables, routines, triggers, types) } - /// A row refreshes only the fetch its kind comes from. Partitions ride with the tables, because - /// a partition row is drawn as a child of its table. + /// A row refreshes only the fetch its kind comes from. Partitions and a table's detail lists ride + /// with the tables, because their rows are drawn as children of a table. func refreshTableObjects(connectionId: UUID, database: String, schema: String?) async { let key = Self.objectsKey(connectionId: connectionId, database: database, schema: schema) async let tables: Void = rereadTables(key) async let partitions: Void = refreshPartitions(under: key) - _ = await (tables, partitions) + async let details: Void = refreshTableDetails(under: key) + _ = await (tables, partitions, details) } func refreshRoutineObjects(connectionId: UUID, database: String, schema: String?) async { @@ -661,6 +666,24 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { } } + /// The rule partitions follow: a loaded list reads again over its rows, and one that never + /// loaded is dropped for its next reader. + private func refreshTableDetails(under key: ObjectsKey) async { + let detailKeys = tableDetailsState.keys.filter { + $0.connectionId == key.connectionId && $0.database == key.database && $0.schema == key.schema + } + for detailKey in detailKeys { + guard case .loaded = tableDetailsState[detailKey] ?? .idle else { + tableDetailsCommit.fence.supersede(detailKey) + tableDetailsCommit.freshness.markChanged(detailKey) + tableDetailsState.removeValue(forKey: detailKey) + await tableDetailsDedup.cancel { $0.key == detailKey } + continue + } + await reread(detailKey, connectionId: detailKey.connectionId, in: tableDetailLists, fetch: tableDetailFetch(detailKey)) + } + } + /// A table's identity ignores its partition count, so the equality guard on a table list is blind /// to a count that moved; another client adding a partition is exactly that case. nonisolated internal static func partitionCountsChanged( @@ -862,6 +885,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { triggersCommit.freshness.removeAll { $0.connectionId == connectionId } typesCommit.freshness.removeAll { $0.connectionId == connectionId } partitionsCommit.freshness.removeAll { $0.connectionId == connectionId } + tableDetailsCommit.freshness.removeAll { $0.connectionId == connectionId } allSchemaTablesFreshness.removeAll { $0.connectionId == connectionId } allSchemaTablesRequested = allSchemaTablesRequested.filter { $0.key.connectionId != connectionId } allSchemaTablesCovered = allSchemaTablesCovered.filter { $0.key.connectionId != connectionId } @@ -874,6 +898,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { triggersState = triggersState.filter { $0.key.connectionId != connectionId } typesState = typesState.filter { $0.key.connectionId != connectionId } partitionsState = partitionsState.filter { $0.key.connectionId != connectionId } + tableDetailsState = tableDetailsState.filter { $0.key.connectionId != connectionId } } // MARK: - Private @@ -899,6 +924,9 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { for key in connectionPartitionKeys(connectionId) { partitionsCommit.fence.supersede(key) } + for key in tableDetailsState.keys where key.connectionId == connectionId { + tableDetailsCommit.fence.supersede(key) + } for key in allSchemaTablesState.keys where key.connectionId == connectionId { allSchemaTablesFence.supersede(key) } @@ -912,6 +940,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { await triggersDedup.cancel { $0.key.connectionId == connectionId } await typesDedup.cancel { $0.key.connectionId == connectionId } await partitionsDedup.cancel { $0.key.connectionId == connectionId } + await tableDetailsDedup.cancel { $0.key.connectionId == connectionId } await allSchemaTablesDedup.cancel { $0.database.connectionId == connectionId } } @@ -925,6 +954,7 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { idlePending(\.triggersState) { $0.connectionId == connectionId } idlePending(\.typesState) { $0.connectionId == connectionId } idlePending(\.partitionsState) { $0.connectionId == connectionId } + idlePending(\.tableDetailsState) { $0.connectionId == connectionId } idlePending(\.allSchemaTablesState) { $0.connectionId == connectionId } } diff --git a/apple/TableProTests/Core/Services/Query/DatabaseTreeCatalogRefreshPlanTests.swift b/apple/TableProTests/Core/Services/Query/DatabaseTreeCatalogRefreshPlanTests.swift index 4acaa2c342..73d7b0b544 100644 --- a/apple/TableProTests/Core/Services/Query/DatabaseTreeCatalogRefreshPlanTests.swift +++ b/apple/TableProTests/Core/Services/Query/DatabaseTreeCatalogRefreshPlanTests.swift @@ -200,4 +200,59 @@ struct DatabaseTreeCatalogRefreshPlanTests { #expect(result.allSchemaTables.isEmpty) #expect(result.isEmpty) } + + private typealias TableDetailsKey = DatabaseTreeMetadataService.TableDetailsKey + + private func detailKey( + _ kind: TableDetailKind, + database: String = "shop", + schema: String? = "public", + connection: UUID? = nil + ) -> TableDetailsKey { + TableDetailsKey(connectionId: connection ?? connectionId, database: database, schema: schema, table: "orders", kind: kind) + } + + private func detailPlan(_ change: CatalogChange, keys: [TableDetailsKey]) -> CatalogTreeRefreshPlan { + DatabaseTreeMetadataService.catalogRefreshPlan( + for: change, + hasDatabaseList: false, + schemaListKeys: [DatabaseKey](), + tableKeys: [ObjectsKey](), + tableDetailKeys: keys, + routineKeys: [ObjectsKey](), + triggerKeys: [ObjectsKey](), + typeKeys: [ObjectsKey]() + ) + } + + /// A foreign key in one schema can point at a table another schema's DDL just dropped, so a + /// table change reaches the whole database, the way partition lists are reached. + @Test("A table change reaches every detail list of its database, in any schema") + func tableChangeReachesDetailLists() { + let columns = detailKey(.columns) + let auditTriggers = detailKey(.triggers, schema: "audit") + let otherDatabase = detailKey(.columns, database: "warehouse") + let otherConnection = detailKey(.columns, connection: UUID()) + + let result = detailPlan( + CatalogChange(connectionId: connectionId, database: "shop", schema: "public", kinds: .tables), + keys: [columns, auditTriggers, otherDatabase, otherConnection] + ) + + #expect(result.tableDetails == [columns, auditTriggers]) + #expect(!result.isEmpty) + } + + @Test("A trigger change reaches trigger lists alone, and a routine change reaches none") + func triggerChangeReachesTriggerLists() { + let columns = detailKey(.columns) + let triggers = detailKey(.triggers) + + let triggerPlan = detailPlan(CatalogChange(connectionId: connectionId, kinds: .triggers), keys: [columns, triggers]) + let routinePlan = detailPlan(CatalogChange(connectionId: connectionId, kinds: .routines), keys: [columns, triggers]) + + #expect(triggerPlan.tableDetails == [triggers]) + #expect(routinePlan.tableDetails.isEmpty) + #expect(routinePlan.isEmpty) + } } diff --git a/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift index 563ae44e97..2c7324ee15 100644 --- a/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift +++ b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift @@ -120,4 +120,106 @@ struct DatabaseTreeTableDetailsServiceTests { #expect(driver.detailReads.isEmpty) await disconnect(connection) } + + private func change(_ connection: DatabaseConnection, _ kinds: SQLCatalogObjectKinds) async { + await service.refreshCatalog(for: CatalogChange(connectionId: connection.id, kinds: kinds)) + } + + @Test("A table change marks every loaded list stale, keeps its rows, and the next ask reads it once") + func tableChangeMarksListsStale() async { + let (connection, driver) = connect() + await load(connection, .columns) + await load(connection, .triggers) + driver.columnsByTable["orders"] = [TestFixtures.makeColumnInfo(name: "id", dataType: "bigint")] + + await change(connection, .tables) + + #expect(columnNames(connection) == ["id", "total"]) + #expect(needsFetch(connection, .columns)) + #expect(needsFetch(connection, .triggers)) + #expect(driver.detailReads == ["columns:orders", "triggers:orders"]) + + async let first: Void = load(connection, .columns) + async let second: Void = load(connection, .columns) + _ = await (first, second) + + #expect(columnNames(connection) == ["id"]) + #expect(driver.detailReads == ["columns:orders", "triggers:orders", "columns:orders"]) + await disconnect(connection) + } + + @Test("A trigger change marks trigger lists alone") + func triggerChangeMarksTriggersAlone() async { + let (connection, _) = connect() + await load(connection, .columns) + await load(connection, .triggers) + + await change(connection, .triggers) + + #expect(needsFetch(connection, .triggers)) + #expect(!needsFetch(connection, .columns)) + await disconnect(connection) + } + + @Test("A failed refetch keeps the rows already on screen") + func failedRefetchKeepsRows() async { + let (connection, driver) = connect() + await load(connection, .columns) + await change(connection, .tables) + driver.detailError = ReadFailed() + + await load(connection, .columns) + + #expect(columnNames(connection) == ["id", "total"]) + await disconnect(connection) + } + + @Test("A reconnect keeps the rows and marks them stale, and a disconnect clears them") + func reconnectKeepsAndDisconnectClears() async { + let (connection, _) = connect() + await load(connection, .columns) + + await service.handleReconnect(connectionId: connection.id) + #expect(columnNames(connection) == ["id", "total"]) + #expect(needsFetch(connection, .columns)) + + await service.handleDisconnect(connectionId: connection.id) + #expect(state(connection, .columns) == .idle) + DatabaseManager.shared.removeSession(for: connection.id) + } + + @Test("A read a disconnect overtakes commits nothing") + func readOvertakenByDisconnectCommitsNothing() async { + let (connection, driver) = connect() + driver.pausesNextTableFetch = true + var read: Task? + await withCheckedContinuation { (paused: CheckedContinuation) in + driver.onTableFetchPaused = { paused.resume() } + read = Task { await load(connection, .columns) } + } + + await service.handleDisconnect(connectionId: connection.id) + driver.resumeTableFetch() + await read?.value + + #expect(state(connection, .columns) == .idle) + DatabaseManager.shared.removeSession(for: connection.id) + } + + @Test("Refreshing a schema's tables reads a loaded list again and drops one that never loaded") + func refreshRidesWithTheTables() async { + let (connection, driver) = connect() + await load(connection, .columns) + driver.detailError = ReadFailed() + await load(connection, .indexes) + driver.detailError = nil + driver.columnsByTable["orders"] = [TestFixtures.makeColumnInfo(name: "id", dataType: "bigint")] + + await service.refreshTableObjects(connectionId: connection.id, database: connection.database, schema: "public") + + #expect(columnNames(connection) == ["id"]) + #expect(state(connection, .indexes) == .idle) + #expect(needsFetch(connection, .indexes)) + await disconnect(connection) + } } From e5e502d1d76a66bfa0d7d2ab2bb7c8612ab49c16 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:24:02 +0700 Subject: [PATCH 004/123] feat(sidebar): remember open table detail groups per window Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/UI/WindowSidebarState.swift | 55 ++++++++++++- .../ViewModels/WindowSidebarStateTests.swift | 78 +++++++++++++++++++ 2 files changed, 130 insertions(+), 3 deletions(-) diff --git a/apple/TablePro/Models/UI/WindowSidebarState.swift b/apple/TablePro/Models/UI/WindowSidebarState.swift index 5dc1aed215..7c44d561c7 100644 --- a/apple/TablePro/Models/UI/WindowSidebarState.swift +++ b/apple/TablePro/Models/UI/WindowSidebarState.swift @@ -18,6 +18,18 @@ struct DatabaseTableKey: Hashable, Sendable, Codable { let table: String } +extension DatabaseTableKey { + init(_ ref: DatabaseTreeTableRef) { + self.init(database: ref.database ?? "", schema: ref.schema, table: ref.table.name) + } +} + +/// One detail group under one table, as a window records it open. +struct DatabaseTableDetailGroupKey: Hashable, Sendable { + let table: DatabaseTableKey + let group: TableDetailGroupKind +} + @MainActor internal final class WindowSidebarState: ObservableObject { private let connectionId: UUID? @@ -59,6 +71,7 @@ internal final class WindowSidebarState: ObservableObject { @Published var expandedTreeDatabases: Set = [] { didSet { persistExpansion() } } @Published var expandedTreeDatabaseSchemas: Set = [] { didSet { persistExpansion() } } @Published var expandedTreeTables: Set = [] { didSet { persistExpansion() } } + @Published var expandedTreeTableDetailGroups: Set = [] { didSet { persistExpansion() } } /// Folders are open until the user closes one, so this records the closed ones: a table the /// open tab shows is only highlighted when its row is on screen. @Published var collapsedTableFolders: Set = [] { didSet { persistExpansion() } } @@ -120,6 +133,14 @@ internal final class WindowSidebarState: ObservableObject { let expanded: Bool } + /// The group rides as its raw string for the reason `PersistedObjectGroup` gives. + private struct PersistedTableDetailGroup: Codable { + let database: String + let schema: String? + let table: String + let group: String + } + private struct PersistedExpansion: Codable { var schemas: [String] var databases: [String] @@ -128,6 +149,7 @@ internal final class WindowSidebarState: ObservableObject { var objectGroups: [PersistedObjectGroup]? var seeded: Bool? var collapsedFolders: [UUID]? + var tableDetailGroups: [PersistedTableDetailGroup]? } private var storageKey: String? { @@ -144,6 +166,7 @@ internal final class WindowSidebarState: ObservableObject { expandedTreeTables = Set(decoded.tables ?? []) treeObjectGroupExpansion = Self.objectGroupExpansion(from: decoded.objectGroups ?? []) collapsedTableFolders = Set(decoded.collapsedFolders ?? []) + expandedTreeTableDetailGroups = Self.tableDetailGroups(from: decoded.tableDetailGroups ?? []) didSeedExpansion = decoded.seeded ?? true } @@ -152,8 +175,8 @@ internal final class WindowSidebarState: ObservableObject { if expandedTreeSchemas.isEmpty, expandedTreeDatabases.isEmpty, expandedTreeDatabaseSchemas.isEmpty, expandedTreeTables.isEmpty, - treeObjectGroupExpansion.isEmpty, collapsedTableFolders.isEmpty, - !didSeedExpansion { + expandedTreeTableDetailGroups.isEmpty, treeObjectGroupExpansion.isEmpty, + collapsedTableFolders.isEmpty, !didSeedExpansion { defaults.removeObject(forKey: storageKey) return } @@ -165,7 +188,8 @@ internal final class WindowSidebarState: ObservableObject { tables: Array(expandedTreeTables), objectGroups: Self.persistedObjectGroups(from: treeObjectGroupExpansion), seeded: didSeedExpansion, - collapsedFolders: Array(collapsedTableFolders) + collapsedFolders: Array(collapsedTableFolders), + tableDetailGroups: Self.persistedTableDetailGroups(from: expandedTreeTableDetailGroups) ) if let data = try? JSONEncoder().encode(snapshot) { defaults.set(data, forKey: storageKey) @@ -194,4 +218,29 @@ internal final class WindowSidebarState: ObservableObject { ) } } + + private static func tableDetailGroups( + from persisted: [PersistedTableDetailGroup] + ) -> Set { + Set(persisted.compactMap { entry in + guard let group = TableDetailGroupKind(rawValue: entry.group) else { return nil } + return DatabaseTableDetailGroupKey( + table: DatabaseTableKey(database: entry.database, schema: entry.schema, table: entry.table), + group: group + ) + }) + } + + private static func persistedTableDetailGroups( + from keys: Set + ) -> [PersistedTableDetailGroup] { + keys.map { key in + PersistedTableDetailGroup( + database: key.table.database, + schema: key.table.schema, + table: key.table.table, + group: key.group.rawValue + ) + } + } } diff --git a/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift b/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift index 131a852862..25bcb5f74a 100644 --- a/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift +++ b/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift @@ -221,4 +221,82 @@ struct WindowSidebarStateTests { state.expandedTreeDatabases.insert("x") #expect(state.expandedTreeDatabases == ["x"]) } + + @Test("Open detail groups persist and restore with the rest of the tree") + func persistsOpenDetailGroups() throws { + let defaults = try makeDefaults() + let connectionId = UUID() + let orders = DatabaseTableKey(database: "shop", schema: "public", table: "orders") + let columns = DatabaseTableDetailGroupKey(table: orders, group: .columns) + let partitions = DatabaseTableDetailGroupKey(table: orders, group: .partitions) + + let state = WindowSidebarState(connectionId: connectionId, defaults: defaults) + state.expandedTreeTables.insert(orders) + state.expandedTreeTableDetailGroups = [columns, partitions] + + let restored = WindowSidebarState(connectionId: connectionId, defaults: defaults) + #expect(restored.expandedTreeTables == [orders]) + #expect(restored.expandedTreeTableDetailGroups == [columns, partitions]) + } + + @Test("Expansion saved before table details shipped still decodes, with no group open") + func decodesExpansionWrittenBeforeTableDetails() throws { + let defaults = try makeDefaults() + let connectionId = UUID() + let stored = """ + {"schemas":[],"databases":["shop"],"databaseSchemas":[],\ + "tables":[{"database":"shop","schema":"public","table":"orders"}],"seeded":true} + """ + defaults.set(Data(stored.utf8), forKey: "com.TablePro.sidebar.treeExpansion.\(connectionId.uuidString)") + + let restored = WindowSidebarState(connectionId: connectionId, defaults: defaults) + + #expect(restored.expandedTreeDatabases == ["shop"]) + #expect(restored.expandedTreeTables == [DatabaseTableKey(database: "shop", schema: "public", table: "orders")]) + #expect(restored.expandedTreeTableDetailGroups.isEmpty) + } + + /// A later build may add a group this one has never heard of. Reading it must not throw away the + /// rest of the blob, the rule `unknownObjectKindKeepsOtherExpansion` pins for object kinds. + @Test("An unrecognized detail group does not discard the rest of the expansion") + func unknownDetailGroupKeepsOtherExpansion() throws { + let defaults = try makeDefaults() + let connectionId = UUID() + let stored = """ + {"schemas":[],"databases":["shop"],"databaseSchemas":[],"tables":[],"seeded":true,\ + "tableDetailGroups":[{"database":"shop","schema":"public","table":"orders","group":"policies"},\ + {"database":"shop","schema":"public","table":"orders","group":"indexes"}]} + """ + defaults.set(Data(stored.utf8), forKey: "com.TablePro.sidebar.treeExpansion.\(connectionId.uuidString)") + + let restored = WindowSidebarState(connectionId: connectionId, defaults: defaults) + + let orders = DatabaseTableKey(database: "shop", schema: "public", table: "orders") + #expect(restored.expandedTreeDatabases == ["shop"]) + #expect(restored.expandedTreeTableDetailGroups == [DatabaseTableDetailGroupKey(table: orders, group: .indexes)]) + } + + @Test("Closing the last open group clears storage along with the rest") + func closingTheLastGroupRemovesStorage() throws { + let defaults = try makeDefaults() + let connectionId = UUID() + let key = DatabaseTableDetailGroupKey( + table: DatabaseTableKey(database: "shop", schema: "public", table: "orders"), group: .columns + ) + + let state = WindowSidebarState(connectionId: connectionId, defaults: defaults) + state.expandedTreeTableDetailGroups.insert(key) + state.expandedTreeTableDetailGroups.remove(key) + + #expect(defaults.data(forKey: "com.TablePro.sidebar.treeExpansion.\(connectionId.uuidString)") == nil) + } + + @Test("A table row's key is the one its expansion is recorded under") + func tableKeyFromATreeRow() { + let ref = DatabaseTreeTableRef( + database: nil, schema: "public", table: TableInfo(name: "orders", type: .table, rowCount: nil) + ) + + #expect(DatabaseTableKey(ref) == DatabaseTableKey(database: "", schema: "public", table: "orders")) + } } From cc30c0bf33028e98efe5d7b66a9e1e848b66cd9a Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:35:51 +0700 Subject: [PATCH 005/123] feat(sidebar): resolve the detail groups and rows a table lists Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Database/DatabaseTreeTableDetailRef.swift | 41 +++++ .../Views/Sidebar/DatabaseTreeView.swift | 3 + .../Views/Sidebar/TableDetailTree.swift | 145 +++++++++++++++ .../Views/Sidebar/TableDetailTreeTests.swift | 167 ++++++++++++++++++ 4 files changed, 356 insertions(+) create mode 100644 apple/TablePro/Models/Database/DatabaseTreeTableDetailRef.swift create mode 100644 apple/TablePro/Views/Sidebar/TableDetailTree.swift create mode 100644 apple/TableProTests/Views/Sidebar/TableDetailTreeTests.swift diff --git a/apple/TablePro/Models/Database/DatabaseTreeTableDetailRef.swift b/apple/TablePro/Models/Database/DatabaseTreeTableDetailRef.swift new file mode 100644 index 0000000000..ab7ca3f9e3 --- /dev/null +++ b/apple/TablePro/Models/Database/DatabaseTreeTableDetailRef.swift @@ -0,0 +1,41 @@ +// +// DatabaseTreeTableDetailRef.swift +// TablePro +// + +import Foundation + +/// One detail of a table as the sidebar lists it. A foreign key is one row per constraint, so a key +/// over two columns reads as one key rather than two. +enum TableDetailItem: Hashable, Sendable { + case column(ColumnInfo) + case index(IndexInfo) + case foreignKey(EditableForeignKeyDefinition) + case check(CheckConstraintInfo) + + var name: String { + switch self { + case .column(let column): column.name + case .index(let index): index.name + case .foreignKey(let key): key.name + case .check(let check): check.name + } + } +} + +/// One detail group under one table row. +struct DatabaseTreeTableDetailGroupRef: Hashable, Sendable { + let table: DatabaseTreeTableRef + let kind: TableDetailGroupKind + + var expansionKey: DatabaseTableDetailGroupKey { + DatabaseTableDetailGroupKey(table: DatabaseTableKey(table), group: kind) + } +} + +/// One column, index, foreign key or check, with the table it belongs to, which is what its menu +/// and its double-click open. +struct DatabaseTreeTableDetailRef: Hashable, Sendable { + let table: DatabaseTreeTableRef + let item: TableDetailItem +} diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift index e1aaf317a4..ccf914b04d 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift @@ -24,6 +24,9 @@ struct DatabaseTreeTriggerRef: Identifiable, Equatable { let database: String? let schema: String? let trigger: TriggerInfo + /// Set for a trigger listed under its own table, where the row captions when it fires rather + /// than the table name the row above already shows. + var listedUnderTable = false var id: String { IdentityPath.joined([database ?? "", schema ?? "", trigger.id], separator: "|") diff --git a/apple/TablePro/Views/Sidebar/TableDetailTree.swift b/apple/TablePro/Views/Sidebar/TableDetailTree.swift new file mode 100644 index 0000000000..7e8f4553f8 --- /dev/null +++ b/apple/TablePro/Views/Sidebar/TableDetailTree.swift @@ -0,0 +1,145 @@ +// +// TableDetailTree.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +/// Which detail lists an engine can answer. A group it cannot fill is not listed: an empty +/// Triggers group would claim the table has none. +internal struct TableDetailCapabilities: Equatable, Sendable { + let foreignKeys: Bool + let checks: Bool + let triggers: Bool + + init(foreignKeys: Bool, checks: Bool, triggers: Bool) { + self.foreignKeys = foreignKeys + self.checks = checks + self.triggers = triggers + } + + init(databaseType: DatabaseType) { + self.init( + foreignKeys: databaseType.supportsForeignKeys, + checks: databaseType.supportsCheckConstraints, + triggers: databaseType.supportsTriggers + ) + } +} + +internal enum TableDetailGroupResolver { + /// A sequence holds no columns, indexes or constraints, and a triangle that opens on nothing is + /// the bug the outline's expandability gate exists to prevent. + static func listsDetails(of type: TableInfo.TableType) -> Bool { + type != .sequence + } + + static func groups( + for type: TableInfo.TableType, + capabilities: TableDetailCapabilities, + showsPartitions: Bool + ) -> [TableDetailGroupKind] { + guard listsDetails(of: type) else { return [] } + let isTable = type == .table || type == .partitionedTable + var groups: [TableDetailGroupKind] = [.columns] + if isTable || type == .materializedView { groups.append(.indexes) } + if isTable, capabilities.foreignKeys { groups.append(.foreignKeys) } + if isTable, capabilities.checks { groups.append(.checks) } + if isTable, capabilities.triggers { groups.append(.triggers) } + if type == .partitionedTable, showsPartitions { groups.append(.partitions) } + return groups + } + + /// A failed read is not asked for again until the next change, so the user's own reopening is + /// the retry. A restore pass never retries, or every reload would repeat a read the server refuses. + static func readsOnDisclosure( + needsFetch: Bool, + phase: MetadataLoadPhase, + origin: DatabaseTreeFilter.DisclosureOrigin + ) -> Bool { + needsFetch || (origin == .user && phase.failureMessage != nil) + } +} + +internal enum TableDetailRows { + enum Row: Equatable { + case detail(DatabaseTreeTableDetailRef) + case trigger(DatabaseTreeTriggerRef) + } + + struct Entry: Equatable { + let key: String + let row: Row + } + + static func entries(for list: TableDetailList, table: DatabaseTreeTableRef) -> [Entry] { + switch list { + case .triggers(let triggers): + let keys = uniqueKeys(for: triggers.map { $0.name }) + return zip(keys, triggers).map { key, trigger in + Entry(key: key, row: .trigger(DatabaseTreeTriggerRef( + database: table.database, + schema: table.schema, + trigger: owned(trigger, by: table), + listedUnderTable: true + ))) + } + case .columns, .indexes, .foreignKeys, .checks: + let items = items(in: list) + let keys = uniqueKeys(for: items.map { $0.name }) + return zip(keys, items).map { key, item in + Entry(key: key, row: .detail(DatabaseTreeTableDetailRef(table: table, item: item))) + } + } + } + + static func items(in list: TableDetailList) -> [TableDetailItem] { + switch list { + case .columns(let columns): columns.map(TableDetailItem.column) + case .indexes(let indexes): indexes.map(TableDetailItem.index) + case .foreignKeys(let keys): EditableForeignKeyDefinition.grouping(keys).map(TableDetailItem.foreignKey) + case .checks(let checks): checks.map(TableDetailItem.check) + case .triggers: [] + } + } + + /// A row's node id ends in this key, and `NSOutlineView` must get each node once. Unnamed checks + /// and same-named triggers are real, so a repeat gets its position after the name. + static func uniqueKeys(for names: [String]) -> [String] { + var seen: [String: Int] = [:] + return names.map { name in + let occurrence = seen[name, default: 0] + 1 + seen[name] = occurrence + return occurrence == 1 ? name : "\(name)\u{1}\(occurrence)" + } + } + + /// Show DDL and Copy Table Name read the trigger's own table and schema, and a per-table read + /// may leave them out because the caller already named the table. + static func owned(_ trigger: TriggerInfo, by table: DatabaseTreeTableRef) -> TriggerInfo { + let tableName = trigger.table?.nilIfEmpty ?? table.table.name + let schema = trigger.schema?.nilIfEmpty ?? table.qualifyingSchema + guard tableName != trigger.table || schema != trigger.schema else { return trigger } + return TriggerInfo( + name: trigger.name, + timing: trigger.timing, + event: trigger.event, + statement: trigger.statement, + enabled: trigger.enabled, + table: tableName, + schema: schema, + orientation: trigger.orientation, + definition: trigger.definition, + attributes: trigger.attributes + ) + } +} + +extension TableDetailList { + /// What a group's caption counts: rows as listed, so a two-column key counts once. + var count: Int { + if case .triggers(let triggers) = self { return triggers.count } + return TableDetailRows.items(in: self).count + } +} diff --git a/apple/TableProTests/Views/Sidebar/TableDetailTreeTests.swift b/apple/TableProTests/Views/Sidebar/TableDetailTreeTests.swift new file mode 100644 index 0000000000..4540984eaf --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/TableDetailTreeTests.swift @@ -0,0 +1,167 @@ +import Foundation +@testable import TablePro +import Testing + +struct TableDetailTreeTests { + private let everything = TableDetailCapabilities(foreignKeys: true, checks: true, triggers: true) + + private func orders(_ type: TableInfo.TableType = .table) -> DatabaseTreeTableRef { + DatabaseTreeTableRef( + database: "shop", schema: "public", table: TableInfo(name: "orders", type: type, rowCount: nil, schema: "public") + ) + } + + private func groups( + _ type: TableInfo.TableType, + capabilities: TableDetailCapabilities? = nil, + showsPartitions: Bool = true + ) -> [TableDetailGroupKind] { + TableDetailGroupResolver.groups( + for: type, capabilities: capabilities ?? everything, showsPartitions: showsPartitions + ) + } + + @Test("A table lists every group its engine can read, in a fixed order") + func tableGroups() { + #expect(groups(.table) == [.columns, .indexes, .foreignKeys, .checks, .triggers]) + } + + @Test("A group the engine cannot read is not listed") + func capabilitiesGateGroups() { + let keysOnly = TableDetailCapabilities(foreignKeys: true, checks: false, triggers: false) + let none = TableDetailCapabilities(foreignKeys: false, checks: false, triggers: false) + + #expect(groups(.table, capabilities: keysOnly) == [.columns, .indexes, .foreignKeys]) + #expect(groups(.table, capabilities: none) == [.columns, .indexes]) + } + + @Test("A view lists columns, a materialized view adds indexes, and a sequence lists nothing") + func relationTypesGateGroups() { + #expect(groups(.view) == [.columns]) + #expect(groups(.foreignTable) == [.columns]) + #expect(groups(.materializedView) == [.columns, .indexes]) + #expect(groups(.sequence).isEmpty) + #expect(!TableDetailGroupResolver.listsDetails(of: .sequence)) + #expect(TableDetailGroupResolver.listsDetails(of: .view)) + } + + @Test("A partitioned table's partitions come last, and only while Partitions is on") + func partitionsGroupFollowsItsOption() { + #expect(groups(.partitionedTable) == [.columns, .indexes, .foreignKeys, .checks, .triggers, .partitions]) + #expect(groups(.partitionedTable, showsPartitions: false) == [.columns, .indexes, .foreignKeys, .checks, .triggers]) + #expect(!groups(.table).contains(.partitions)) + } + + @Test("A list reads when stale, and again when the user opens a group whose read failed") + func readsOnDisclosureFollowsStalenessAndTheUser() { + #expect(TableDetailGroupResolver.readsOnDisclosure(needsFetch: true, phase: .idle, origin: .restore)) + #expect(!TableDetailGroupResolver.readsOnDisclosure(needsFetch: false, phase: .loaded, origin: .user)) + #expect(TableDetailGroupResolver.readsOnDisclosure(needsFetch: false, phase: .failed("denied"), origin: .user)) + #expect(!TableDetailGroupResolver.readsOnDisclosure(needsFetch: false, phase: .failed("denied"), origin: .restore)) + #expect(!TableDetailGroupResolver.readsOnDisclosure(needsFetch: false, phase: .failed("denied"), origin: .search)) + } + + @Test("A two-column foreign key is one row, with both column pairs in key order") + func foreignKeysGroupByConstraint() { + let list = TableDetailList.foreignKeys([ + TestFixtures.makeForeignKeyInfo( + name: "orders_customer_fk", column: "customer_id", referencedTable: "customers", referencedColumn: "id" + ), + TestFixtures.makeForeignKeyInfo( + name: "orders_customer_fk", column: "customer_region", referencedTable: "customers", referencedColumn: "region" + ), + TestFixtures.makeForeignKeyInfo( + name: "orders_coupon_fk", column: "coupon_id", referencedTable: "coupons", referencedColumn: "id" + ), + ]) + + let items = TableDetailRows.items(in: list) + let names = items.map { $0.name } + + #expect(names == ["orders_customer_fk", "orders_coupon_fk"]) + #expect(list.count == 2) + guard case .foreignKey(let key) = items.first else { + Issue.record("The first row is not a foreign key") + return + } + #expect(key.columns == ["customer_id", "customer_region"]) + #expect(key.referencedColumns == ["id", "region"]) + } + + @Test("Items that share a name get keys of their own, and the first keeps its name") + func sameNamedItemsGetTheirOwnKeys() { + let keys = TableDetailRows.uniqueKeys(for: ["", "", "total_positive", ""]) + + #expect(Set(keys).count == 4) + #expect(keys[2] == "total_positive") + + let entries = TableDetailRows.entries( + for: .checks([ + CheckConstraintInfo(name: "", expression: "total > 0"), + CheckConstraintInfo(name: "", expression: "total < 1000"), + ]), + table: orders() + ) + let entryKeys = entries.map { $0.key } + #expect(Set(entryKeys).count == 2) + } + + @Test("A detail row carries the table it belongs to") + func detailRowsCarryTheirTable() { + let entries = TableDetailRows.entries( + for: .columns([TestFixtures.makeColumnInfo(name: "id", dataType: "integer")]), table: orders() + ) + + guard case .detail(let detail) = entries.first?.row else { + Issue.record("A column is not a detail row") + return + } + #expect(detail.table == orders()) + #expect(detail.item.name == "id") + #expect(TableDetailRows.entries(for: .columns([]), table: orders()).isEmpty) + } + + @Test("A trigger listed under its table names that table, even when the driver left it out") + func triggersBelongToTheirTable() { + let bare = TriggerInfo(name: "orders_audit", timing: "AFTER", event: "INSERT", statement: "") + + let entries = TableDetailRows.entries(for: .triggers([bare]), table: orders()) + + guard case .trigger(let ref) = entries.first?.row else { + Issue.record("A trigger is not a trigger row") + return + } + #expect(ref.listedUnderTable) + #expect(ref.database == "shop") + #expect(ref.trigger.table == "orders") + #expect(ref.trigger.schema == "public") + #expect(ref.objectRef.table == "orders") + #expect(sameFiring(ref.trigger, bare)) + } + + @Test("A trigger the driver placed keeps its own table and schema") + func placedTriggersKeepTheirPlace() { + let placed = TriggerInfo( + name: "audit", timing: "BEFORE", event: "UPDATE", statement: "", table: "orders_log", schema: "audit" + ) + + let owned = TableDetailRows.owned(placed, by: orders()) + + #expect(owned == placed) + } + + @Test("A group's expansion key is its table's key and its kind") + func groupExpansionKey() { + let group = DatabaseTreeTableDetailGroupRef(table: orders(), kind: .checks) + + #expect(group.expansionKey == DatabaseTableDetailGroupKey( + table: DatabaseTableKey(database: "shop", schema: "public", table: "orders"), group: .checks + )) + #expect(TableDetailGroupKind.partitions.detailKind == nil) + #expect(TableDetailGroupKind.checks.detailKind == .checks) + } + + private func sameFiring(_ lhs: TriggerInfo, _ rhs: TriggerInfo) -> Bool { + [lhs.name, lhs.timing, lhs.event, lhs.statement] == [rhs.name, rhs.timing, rhs.event, rhs.statement] + } +} From 22b0979542c20519cbc90a33ee3f32020cd48b6d Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:47:14 +0700 Subject: [PATCH 006/123] feat(sidebar): draw table detail groups and rows Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../TablePro/Resources/Localizable.xcstrings | 6 + .../Views/Sidebar/DatabaseTreeRowView.swift | 2 +- .../Views/Sidebar/TableDetailRowView.swift | 146 ++++++++++++++++++ .../Views/Sidebar/TriggerRowView.swift | 18 ++- .../Sidebar/TableDetailRowLogicTests.swift | 91 +++++++++++ 5 files changed, 259 insertions(+), 4 deletions(-) create mode 100644 apple/TablePro/Views/Sidebar/TableDetailRowView.swift create mode 100644 apple/TableProTests/Views/Sidebar/TableDetailRowLogicTests.swift diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 484159124a..00e9b04c64 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -2464,6 +2464,9 @@ "%@ (specification)" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%@ (unique)" : { + }, "%@ (You)" : { "localizations" : { @@ -207495,6 +207498,9 @@ } } } + }, + "unique" : { + }, "Unique" : { "localizations" : { diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift index ea0b5d864a..9e3b536eb3 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift @@ -122,7 +122,7 @@ struct DatabaseTreeRowView: View { case .routine(let ref): RoutineRowView(routine: ref.routine, displayLabel: context.routineDisplayLabel(ref)) case .trigger(let ref): - TriggerRowView(trigger: ref.trigger) + TriggerRowView(trigger: ref.trigger, listedUnderTable: ref.listedUnderTable) case .userType(let ref): UserTypeRowView(type: ref.type) case .status(let status): diff --git a/apple/TablePro/Views/Sidebar/TableDetailRowView.swift b/apple/TablePro/Views/Sidebar/TableDetailRowView.swift new file mode 100644 index 0000000000..fdc16311c1 --- /dev/null +++ b/apple/TablePro/Views/Sidebar/TableDetailRowView.swift @@ -0,0 +1,146 @@ +// +// TableDetailRowView.swift +// TablePro +// + +import SwiftUI +import TableProPluginKit + +/// What a detail group and a detail row say, kept out of the views so the rows, their accessibility +/// labels and the tests read one rule. +internal enum TableDetailRowLogic { + static func title(for kind: TableDetailGroupKind) -> String { + switch kind { + case .columns: String(localized: "Columns") + case .indexes: String(localized: "Indexes") + case .foreignKeys: String(localized: "Foreign Keys") + case .checks: String(localized: "Checks") + case .triggers: String(localized: "Triggers") + case .partitions: String(localized: "Partitions") + } + } + + static func iconName(for kind: TableDetailGroupKind) -> String { + switch kind { + case .columns: "tablecells" + case .indexes: "list.bullet" + case .foreignKeys: "link" + case .checks: "checkmark.shield" + case .triggers: SidebarObjectKind.trigger.iconName + case .partitions: SidebarPartitionRow.iconName + } + } + + static func iconName(for item: TableDetailItem) -> String { + switch item { + case .column(let column): column.isPrimaryKey ? "key" : "rectangle.portrait" + case .index(let index): index.isPrimary ? "key" : iconName(for: .indexes) + case .foreignKey: iconName(for: .foreignKeys) + case .check: iconName(for: .checks) + } + } + + static func caption(for item: TableDetailItem) -> String? { + switch item { + case .column(let column): + return column.dataType.nilIfEmpty + case .index(let index): + let columns = index.columns.joined(separator: ", ") + guard index.isUnique else { return columns.nilIfEmpty } + return columns.isEmpty + ? String(localized: "unique") + : String(format: String(localized: "%@ (unique)"), columns) + case .foreignKey(let key): + return "\u{2192} \(key.referencedTable)(\(key.referencedColumns.joined(separator: ", ")))" + case .check(let check): + return singleLine(check.expression).nilIfEmpty + } + } + + /// A check expression can span lines in the catalog, and the row has one. + static func singleLine(_ text: String) -> String { + text.split(whereSeparator: \.isWhitespace).joined(separator: " ") + } + + static func accessibilityLabel(for item: TableDetailItem) -> String { + let base = String(format: String(localized: "%@: %@"), kindLabel(for: item), item.name) + guard let caption = caption(for: item) else { return base } + return base + ", " + caption + } + + static func groupAccessibilityLabel(kind: TableDetailGroupKind, count: Int?) -> String { + let title = title(for: kind) + guard let count else { return title } + let items = count == 1 + ? String(localized: "1 item") + : String(format: String(localized: "%lld items"), count) + return title + ", " + items + } + + private static func kindLabel(for item: TableDetailItem) -> String { + switch item { + case .column: String(localized: "Column") + case .index: String(localized: "Index") + case .foreignKey: String(localized: "Foreign Key") + case .check: String(localized: "Check") + } + } +} + +/// A group under a table: its title, and its count once the list has loaded. +struct TableDetailGroupRowView: View { + @ObservedObject private var settingsManager = AppSettingsManager.shared + let kind: TableDetailGroupKind + let count: Int? + + var body: some View { + Label { + HStack(spacing: 6) { + Text(TableDetailRowLogic.title(for: kind)) + .lineLimit(1) + if let count { + Text(verbatim: "\(count)") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } icon: { + Image(systemName: TableDetailRowLogic.iconName(for: kind)) + } + .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .accessibilityElement(children: .combine) + .accessibilityLabel(TableDetailRowLogic.groupAccessibilityLabel(kind: kind, count: count)) + } +} + +/// One column, index, foreign key or check: its name, and what it is in the caption slot. +struct TableDetailRowView: View { + @ObservedObject private var settingsManager = AppSettingsManager.shared + let item: TableDetailItem + + var body: some View { + let caption = TableDetailRowLogic.caption(for: item) + Label { + HStack(spacing: 6) { + Text(item.name) + .lineLimit(1) + .truncationMode(.tail) + .layoutPriority(1) + if let caption { + Text(caption) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + .help(caption) + } + } + } icon: { + Image(systemName: TableDetailRowLogic.iconName(for: item)) + .frame(width: 16) + } + .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .accessibilityElement(children: .combine) + .accessibilityLabel(TableDetailRowLogic.accessibilityLabel(for: item)) + } +} diff --git a/apple/TablePro/Views/Sidebar/TriggerRowView.swift b/apple/TablePro/Views/Sidebar/TriggerRowView.swift index 660fff5af4..7ad2f0b335 100644 --- a/apple/TablePro/Views/Sidebar/TriggerRowView.swift +++ b/apple/TablePro/Views/Sidebar/TriggerRowView.swift @@ -12,6 +12,17 @@ enum TriggerRowLogic { return String(format: String(localized: "%1$@ on %2$@"), base, table) } + /// Under a schema's Triggers group the table tells two same-named triggers apart. Under the table + /// itself that name is the row above, so the caption says when the trigger fires instead. + static func caption(for trigger: TriggerInfo, listedUnderTable: Bool) -> String? { + guard listedUnderTable else { + guard let table = trigger.table, !table.isEmpty else { return nil } + return table + } + let firing = [trigger.timing, trigger.event].filter { !$0.isEmpty }.joined(separator: " ") + return firing.isEmpty ? nil : firing + } + /// 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. static func tooltip(for trigger: TriggerInfo) -> String { @@ -31,6 +42,7 @@ enum TriggerRowLogic { struct TriggerRowView: View { @ObservedObject private var settingsManager = AppSettingsManager.shared let trigger: TriggerInfo + var listedUnderTable = false var body: some View { Label { @@ -38,12 +50,12 @@ struct TriggerRowView: View { Text(trigger.name) .lineLimit(1) .truncationMode(.tail) - if let table = trigger.table, !table.isEmpty { - Text(table) + if let caption = TriggerRowLogic.caption(for: trigger, listedUnderTable: listedUnderTable) { + Text(caption) .font(.caption) .foregroundStyle(.secondary) .lineLimit(1) - .truncationMode(.head) + .truncationMode(listedUnderTable ? .tail : .head) } } } icon: { diff --git a/apple/TableProTests/Views/Sidebar/TableDetailRowLogicTests.swift b/apple/TableProTests/Views/Sidebar/TableDetailRowLogicTests.swift new file mode 100644 index 0000000000..5ba02f3130 --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/TableDetailRowLogicTests.swift @@ -0,0 +1,91 @@ +import Foundation +@testable import TablePro +import Testing + +struct TableDetailRowLogicTests { + private func index(_ columns: [String], unique: Bool = false, primary: Bool = false) -> TableDetailItem { + .index(IndexInfo(name: "orders_idx", columns: columns, isUnique: unique, isPrimary: primary, type: "BTREE")) + } + + @Test("Every group has its own title, and the Structure tab's glyph where it has one") + func groupTitlesAndIcons() { + let titles = TableDetailGroupKind.allCases.map { TableDetailRowLogic.title(for: $0) } + + #expect(Set(titles).count == titles.count) + #expect(TableDetailRowLogic.title(for: .columns) == String(localized: "Columns")) + #expect(TableDetailRowLogic.title(for: .checks) == String(localized: "Checks")) + #expect(TableDetailRowLogic.iconName(for: .indexes) == "list.bullet") + #expect(TableDetailRowLogic.iconName(for: .foreignKeys) == "link") + #expect(TableDetailRowLogic.iconName(for: .checks) == "checkmark.shield") + #expect(TableDetailRowLogic.iconName(for: .triggers) == SidebarObjectKind.trigger.iconName) + #expect(TableDetailRowLogic.iconName(for: .partitions) == SidebarPartitionRow.iconName) + } + + @Test("A primary key column and the primary index wear the key glyph") + func primaryKeysWearTheKey() { + let key = TableDetailItem.column(TestFixtures.makeColumnInfo(name: "id", isPrimaryKey: true)) + let plain = TableDetailItem.column(TestFixtures.makeColumnInfo(name: "total", isPrimaryKey: false)) + + #expect(TableDetailRowLogic.iconName(for: key) == "key") + #expect(TableDetailRowLogic.iconName(for: plain) != "key") + #expect(TableDetailRowLogic.iconName(for: index(["id"], unique: true, primary: true)) == "key") + #expect(TableDetailRowLogic.iconName(for: index(["total"])) == "list.bullet") + } + + @Test("A column's caption is its type as the driver reports it") + func columnCaption() { + let column = TableDetailItem.column(TestFixtures.makeColumnInfo(name: "total", dataType: "numeric(10,2)")) + + #expect(TableDetailRowLogic.caption(for: column) == "numeric(10,2)") + } + + @Test("An index's caption lists its columns and says when it is unique") + func indexCaption() { + #expect(TableDetailRowLogic.caption(for: index(["customer_id", "created_at"])) == "customer_id, created_at") + #expect( + TableDetailRowLogic.caption(for: index(["email"], unique: true)) + == String(format: String(localized: "%@ (unique)"), "email") + ) + } + + @Test("A foreign key's caption names the table and columns it points at") + func foreignKeyCaption() { + var key = EditableForeignKeyDefinition.from(TestFixtures.makeForeignKeyInfo(referencedTable: "customers")) + key.referencedColumns = ["id", "region"] + + #expect(TableDetailRowLogic.caption(for: .foreignKey(key)) == "\u{2192} customers(id, region)") + } + + @Test("A check's caption is its expression on one line") + func checkCaption() { + let check = TableDetailItem.check(CheckConstraintInfo(name: "total_range", expression: "total > 0\n AND\ttotal < 1000")) + + #expect(TableDetailRowLogic.caption(for: check) == "total > 0 AND total < 1000") + } + + @Test("VoiceOver reads the kind, the name and the caption") + func accessibilityLabels() { + let column = TableDetailItem.column(TestFixtures.makeColumnInfo(name: "total", dataType: "numeric")) + let label = TableDetailRowLogic.accessibilityLabel(for: column) + + #expect(label.contains("total")) + #expect(label.contains("numeric")) + #expect(label.contains(String(localized: "Column"))) + #expect(TableDetailRowLogic.groupAccessibilityLabel(kind: .columns, count: nil) == String(localized: "Columns")) + #expect( + TableDetailRowLogic.groupAccessibilityLabel(kind: .columns, count: 1) + != TableDetailRowLogic.groupAccessibilityLabel(kind: .columns, count: 2) + ) + } + + @Test("A trigger under its table captions when it fires; under a schema, its table") + func triggerCaption() { + let trigger = TriggerInfo(name: "audit", timing: "AFTER", event: "INSERT", statement: "", table: "orders") + let bare = TriggerInfo(name: "audit", timing: "", event: "", statement: "") + + #expect(TriggerRowLogic.caption(for: trigger, listedUnderTable: true) == "AFTER INSERT") + #expect(TriggerRowLogic.caption(for: trigger, listedUnderTable: false) == "orders") + #expect(TriggerRowLogic.caption(for: bare, listedUnderTable: true) == nil) + #expect(TriggerRowLogic.caption(for: bare, listedUnderTable: false) == nil) + } +} From 9bd8458d4ce7e40a415cc439d9f9d9ffa13cc3cd Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:57:59 +0700 Subject: [PATCH 007/123] feat(sidebar): add detail group and detail row kinds to the object tree Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Views/Sidebar/DatabaseTreeCellView.swift | 3 +- .../DatabaseTreeDoubleClickIntent.swift | 4 + .../Views/Sidebar/DatabaseTreeNode.swift | 43 +++++++++-- ...baseTreeOutlineCoordinator+Expansion.swift | 6 +- ...DatabaseTreeOutlineCoordinator+Nodes.swift | 2 +- .../DatabaseTreeOutlineCoordinator.swift | 2 + .../Views/Sidebar/DatabaseTreeRowView.swift | 6 ++ .../Views/Sidebar/DatabaseTreeSelection.swift | 3 +- .../Sidebar/DatabaseTreeTypeSelect.swift | 4 + .../Sidebar/Menu/DatabaseTreeMenuSpec.swift | 14 +++- .../DatabaseTreeDoubleClickIntentTests.swift | 23 ++++++ ...tabaseTreeMenuSpecTests+TableDetails.swift | 43 +++++++++++ .../Views/Sidebar/DatabaseTreeNodeTests.swift | 76 +++++++++++++++++++ 13 files changed, 217 insertions(+), 12 deletions(-) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift index e30599e652..7c53376369 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift @@ -41,7 +41,8 @@ final class DatabaseTreeCellView: RenamableSidebarCellView case .schema, .tableFolder: return "folder" case .routine, .trigger, .userType, .status, .recentSection, .temporarySection, .foldersSection, - .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: + .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, + .tableDetailGroup, .tableDetail: return "tablecells" } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift index b1808d59ad..85756ee4fa 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift @@ -17,6 +17,8 @@ internal enum DatabaseTreeDoubleClickIntent: Equatable { /// Open a routine's, trigger's or type's source. Selection alone does not open one, because /// fetching a definition is a round trip, and arrowing through a section would fire one per row. case openObjectSource(DatabaseObjectRef) + /// A column, index, foreign key or check is read in its table's Structure tab. + case showStructure(DatabaseTreeTableRef) /// Expand or collapse a container row. case toggleDisclosure case ignore @@ -37,6 +39,8 @@ internal enum DatabaseTreeDoubleClickResolver { return .openObjectSource(ref.objectRef) case .userType(let ref): return .openObjectSource(ref.objectRef) + case .tableDetail(let ref): + return .showStructure(ref.table) default: return node.isExpandable ? .toggleDisclosure : .ignore } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift index 0a8aaa293c..61bd738a14 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift @@ -91,6 +91,12 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { /// A partition of a partitioned table. Separate from `.table` because on MySQL and Oracle a /// partition is not a relation and cannot be opened, dropped or renamed on its own. case partition(DatabaseTreePartitionRef) + /// A heading under a table for one kind of detail. An ordinary row, not a source list group, + /// so it indents under its table the way an object group indents under its schema. + case tableDetailGroup(DatabaseTreeTableDetailGroupRef) + /// A column, index, foreign key or check. A trigger under a table stays `.trigger`, so it + /// opens and offers its menu the way it does under a schema. + case tableDetail(DatabaseTreeTableDetailRef) case routine(DatabaseTreeRoutineRef) case trigger(DatabaseTreeTriggerRef) case userType(DatabaseTreeUserTypeRef) @@ -118,7 +124,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { var isExpandable: Bool { switch kind { case .recentSection, .temporarySection, .foldersSection, .tableFolder, .database, .schema, - .objectKindSection, .containerObjectKindSection, + .objectKindSection, .containerObjectKindSection, .tableDetailGroup, .hierarchicalSchemaSection, .redisKeysSection: return true case .table(let ref): @@ -128,11 +134,26 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { case .redisNode(let node): guard case .namespace = node else { return false } return true - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status: + case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetail: return false } } + /// The disclosure a row offers under the sidebar's options, the one rule every expandability gate + /// reads. `isExpandable` answers for the kind alone, as the outline drew it before Table Details: + /// partitions shown, details hidden. + func isExpandable(showsPartitions: Bool, showsTableDetails: Bool) -> Bool { + switch kind { + case .table(let ref): + if showsTableDetails, TableDetailGroupResolver.listsDetails(of: ref.table.type) { return true } + return showsPartitions && ref.table.type == .partitionedTable + case .partition: + return showsPartitions && isExpandable + default: + return isExpandable + } + } + var tableRef: DatabaseTreeTableRef? { switch kind { case .table(let ref): return ref @@ -168,7 +189,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return true case .database, .schema, .containerObjectKindSection, .tableFolder, .hierarchicalSchemaSection, .recentTable, .temporaryTable, .table, .partition, - .routine, .trigger, .userType, .status, .redisNode: + .routine, .trigger, .userType, .status, .redisNode, .tableDetailGroup, .tableDetail: return false } } @@ -179,7 +200,8 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return true case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, - .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: + .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, + .tableDetailGroup, .tableDetail: return false } } @@ -192,7 +214,8 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return .schema(database: database, schema: schema, isSystem: systemSchemas.contains(schema)) case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, - .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: + .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, + .tableDetailGroup, .tableDetail: return nil } } @@ -250,6 +273,16 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { } static func partitionId(_ ref: DatabaseTreePartitionRef) -> String { "partition\u{1}\(ref.id)" } + /// Under the table's own id, so a trigger listed under its table and under its schema's Triggers + /// group is two rows: `NSOutlineView` holds each item once. + static func tableDetailGroupId(_ group: DatabaseTreeTableDetailGroupRef) -> String { + "\(tableId(group.table))\u{1}detailgroup\u{1}\(group.kind.rawValue)" + } + + static func tableDetailId(groupId: String, key: String) -> String { + "\(groupId)\u{1}detail\u{1}\(key)" + } + static func recentTableId(_ ref: DatabaseTreeTableRef) -> String { "recent\u{1}table\u{1}\(ref.id)" } static let temporarySectionId = "temporary-section" static func temporaryTableId(_ ref: DatabaseTreeTableRef) -> String { "temporary\u{1}table\u{1}\(ref.id)" } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift index c161f342db..7cd99e5302 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift @@ -199,7 +199,7 @@ extension DatabaseTreeOutlineCoordinator { case .objectKindSection, .containerObjectKindSection, .tableFolder, .table, .partition: restorePartitionExpansion(under: node) case .recentSection, .recentTable, .temporarySection, .temporaryTable, .database, .routine, .trigger, - .userType, .status, .redisKeysSection, .redisNode: + .userType, .status, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: break } } @@ -257,7 +257,7 @@ extension DatabaseTreeOutlineCoordinator { case .partition(let ref): guard let tableRef = ref.tableRef else { break } recordTableExpansion(tableRef, expanded: expanded) - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .redisNode: + case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .redisNode, .tableDetailGroup, .tableDetail: break } } @@ -289,7 +289,7 @@ extension DatabaseTreeOutlineCoordinator { loadHierarchicalSchemaObjects(schema) case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, - .redisKeysSection, .redisNode: + .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: break } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift index 665e162416..987ef448f2 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift @@ -78,7 +78,7 @@ extension DatabaseTreeOutlineCoordinator { return redisChildren(of: nil) case .redisNode(let redisNode): return redisChildren(of: redisNode) - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status: + case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetailGroup, .tableDetail: return [] } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index af9b8bcbac..1a14f9b90b 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -745,6 +745,8 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { open(ref, activateGridFocus: true, forceNonPreview: true) case .openObjectSource(let objectRef): mainCoordinator?.showObjectSource(objectRef) + case .showStructure(let ref): + perform(SidebarMenuCommand.showStructure(ref)) case .toggleDisclosure: if outlineView.isItemExpanded(node) { outlineView.collapseItem(node) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift index 9e3b536eb3..d013dc19ed 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift @@ -55,6 +55,8 @@ struct DatabaseTreeRowContext { var showsPartitions: Bool = true /// The engine's schema rows are databases attached beside the opened file, never one to switch to. var listsAttachedSchemas: Bool = false + /// A group's count comes from the list its table read, which only the coordinator holds. + var tableDetailCount: @MainActor (DatabaseTreeTableDetailGroupRef) -> Int? = { _ in nil } } struct DatabaseTreeRowView: View { @@ -119,6 +121,10 @@ struct DatabaseTreeRowView: View { tableRow(ref) case .partition(let ref): partitionRow(ref) + case .tableDetailGroup(let group): + TableDetailGroupRowView(kind: group.kind, count: context.tableDetailCount(group)) + case .tableDetail(let ref): + TableDetailRowView(item: ref.item) case .routine(let ref): RoutineRowView(routine: ref.routine, displayLabel: context.routineDisplayLabel(ref)) case .trigger(let ref): diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift index 85fa896b1f..2bdda6a750 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift @@ -18,7 +18,8 @@ internal enum DatabaseTreeSelection { case .status, .recentSection, .temporarySection, .foldersSection, .objectKindSection, .redisKeysSection: return false case .database, .schema, .hierarchicalSchemaSection, .table, .partition, .routine, .trigger, .userType, - .recentTable, .temporaryTable, .containerObjectKindSection, .tableFolder, .redisNode: + .recentTable, .temporaryTable, .containerObjectKindSection, .tableFolder, .redisNode, + .tableDetailGroup, .tableDetail: return true } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift index 55f3ed21e8..2c786e0304 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift @@ -62,6 +62,10 @@ internal enum DatabaseTreeTypeSelect { return ref.table.name case .partition(let ref): return ref.partition.name + case .tableDetailGroup(let group): + return TableDetailRowLogic.title(for: group.kind) + case .tableDetail(let ref): + return ref.item.name case .database(let metadata): return metadata.name case .schema(_, let schema): diff --git a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift index 39d1569256..5b4649571c 100644 --- a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift @@ -33,6 +33,8 @@ internal enum DatabaseTreeMenuSpec { return folderSections(ref.folder) case .partition(let ref): return partitionSections(ref, context: context) + case .tableDetail(let ref): + return tableDetailSections(ref) case .database(let metadata): return containerSections(.database(metadata.name, isSystem: metadata.isSystemDatabase), context: context) case .schema(let database, let schema): @@ -64,7 +66,9 @@ internal enum DatabaseTreeMenuSpec { return redisSections(node) case .redisKeysSection: return [DatabaseTreeMenuSection([.command(String(localized: "Refresh"), .refreshRedisKeys)])] - case .status, .recentSection, .temporarySection: + // A group stands for no object. An empty menu still opens as an empty frame, so it gets the + // sidebar's own menu, as a status row does. + case .status, .recentSection, .temporarySection, .tableDetailGroup: return backgroundSections(context) } } @@ -336,6 +340,14 @@ internal enum DatabaseTreeMenuSpec { ] } + /// Editing a column or a key from the tree is out of reach on purpose: the Structure tab does it. + private static func tableDetailSections(_ ref: DatabaseTreeTableDetailRef) -> [DatabaseTreeMenuSection] { + [ + DatabaseTreeMenuSection([.command(String(localized: "Copy Name"), .copyText(ref.item.name))]), + DatabaseTreeMenuSection([.command(String(localized: "Show Structure"), .showStructure(ref.table))]) + ] + } + private static func userTypeSections( _ ref: DatabaseTreeUserTypeRef, context: DatabaseTreeMenuContext diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeDoubleClickIntentTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeDoubleClickIntentTests.swift index 15e9dc1c19..4ceb398aed 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeDoubleClickIntentTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeDoubleClickIntentTests.swift @@ -72,4 +72,27 @@ struct DatabaseTreeDoubleClickIntentTests { func placeholderRowIsIgnored() { #expect(DatabaseTreeDoubleClickResolver.resolve(node: node(.status(.loading))) == .ignore) } + + @Test("A column, index, key or check opens its table's Structure tab") + func detailRowShowsStructure() { + let ref = tableRef("orders") + let detail = DatabaseTreeTableDetailRef(table: ref, item: .column(TestFixtures.makeColumnInfo(name: "total"))) + + #expect(DatabaseTreeDoubleClickResolver.resolve(node: node(.tableDetail(detail))) == .showStructure(ref)) + } + + @Test("A detail group toggles its disclosure, and a trigger under its table opens its source") + func detailGroupAndTriggerRows() { + let ref = tableRef("orders") + let group = DatabaseTreeTableDetailGroupRef(table: ref, kind: .indexes) + let trigger = DatabaseTreeTriggerRef( + database: "app", + schema: "public", + trigger: TriggerInfo(name: "audit", timing: "AFTER", event: "INSERT", statement: "", table: "orders"), + listedUnderTable: true + ) + + #expect(DatabaseTreeDoubleClickResolver.resolve(node: node(.tableDetailGroup(group))) == .toggleDisclosure) + #expect(DatabaseTreeDoubleClickResolver.resolve(node: node(.trigger(trigger))) == .openObjectSource(trigger.objectRef)) + } } diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift index 3fdad4298f..9d089447c0 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests+TableDetails.swift @@ -42,6 +42,49 @@ extension DatabaseTreeMenuSpecTests { #expect(state == true) } + + @Test("A column, index, key or check offers Copy Name, then Show Structure for its table") + func detailRowMenu() { + let orders = tableRef("orders") + let items: [TableDetailItem] = [ + .column(TestFixtures.makeColumnInfo(name: "total")), + .index(IndexInfo(name: "orders_total_idx", columns: ["total"], isUnique: false, isPrimary: false, type: "BTREE")), + .foreignKey(EditableForeignKeyDefinition.from(TestFixtures.makeForeignKeyInfo(name: "orders_user_fk"))), + .check(CheckConstraintInfo(name: "total_positive", expression: "total > 0")), + ] + + for item in items { + let clicked = DatabaseTreeNode.Kind.tableDetail(DatabaseTreeTableDetailRef(table: orders, item: item)) + let sections = DatabaseTreeMenuSpec.sections(for: context(clicked: clicked)) + + #expect(sections.count == 2, "\(item.name)") + #expect(commands(sections) == [.copyText(item.name), .showStructure(orders)], "\(item.name)") + } + } + + @Test("A detail group row offers the sidebar's own menu, as a status row does") + func detailGroupMenuIsTheBackgroundMenu() { + let group = DatabaseTreeTableDetailGroupRef(table: tableRef("orders"), kind: .columns) + + let clicked = commands(DatabaseTreeMenuSpec.sections(for: context(clicked: .tableDetailGroup(group)))) + let background = commands(DatabaseTreeMenuSpec.sections(for: context(clicked: nil))) + + #expect(clicked == background) + } + + @Test("A trigger under its table keeps the trigger menu, naming the table the driver left out") + func triggerUnderTableMenu() { + let bare = TriggerInfo(name: "orders_audit", timing: "AFTER", event: "INSERT", statement: "") + let entries = TableDetailRows.entries(for: .triggers([bare]), table: tableRef("orders")) + guard case .trigger(let ref) = entries.first?.row else { + Issue.record("A trigger is not a trigger row") + return + } + + let menu = commands(DatabaseTreeMenuSpec.sections(for: context(clicked: .trigger(ref)))) + + #expect(menu == [.copyText("orders_audit"), .copyText("orders"), .showObjectSource(ref.objectRef)]) + } } extension GlobalStateSuites { diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift index bd0cb34067..d5d911b194 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift @@ -333,4 +333,80 @@ struct DatabaseTreeNodeTests { #expect(groups.map(\.kind) == [.procedure]) #expect(groups.allSatisfy { $0.schema == "HR" }) } + + @Test("A detail group and its rows sit under their table's id, apart from the same trigger under a schema") + func tableDetailIdsAreScopedToTheirTable() { + let orders = tableRef("orders") + let dotted = DatabaseTreeTableRef( + database: "shop", schema: nil, table: TableInfo(name: "b.c", type: .table, rowCount: 0, schema: "a") + ) + let otherDotted = DatabaseTreeTableRef( + database: "shop", schema: nil, table: TableInfo(name: "c", type: .table, rowCount: 0, schema: "a.b") + ) + let columns = DatabaseTreeTableDetailGroupRef(table: orders, kind: .columns) + let columnsId = DatabaseTreeNode.tableDetailGroupId(columns) + let ids = [ + columnsId, + DatabaseTreeNode.tableDetailGroupId(DatabaseTreeTableDetailGroupRef(table: orders, kind: .indexes)), + DatabaseTreeNode.tableDetailGroupId(DatabaseTreeTableDetailGroupRef(table: tableRef("invoices"), kind: .columns)), + DatabaseTreeNode.tableDetailGroupId(DatabaseTreeTableDetailGroupRef(table: dotted, kind: .columns)), + DatabaseTreeNode.tableDetailGroupId(DatabaseTreeTableDetailGroupRef(table: otherDotted, kind: .columns)), + DatabaseTreeNode.tableId(orders), + ] + + #expect(Set(ids).count == ids.count) + #expect(columnsId.hasPrefix(DatabaseTreeNode.tableId(orders))) + + let trigger = TriggerInfo(name: "audit", timing: "AFTER", event: "INSERT", statement: "", table: "orders") + let schemaRow = DatabaseTreeNode.triggerId(DatabaseTreeTriggerRef(database: "shop", schema: "public", trigger: trigger)) + let triggersId = DatabaseTreeNode.tableDetailGroupId(DatabaseTreeTableDetailGroupRef(table: orders, kind: .triggers)) + #expect(DatabaseTreeNode.tableDetailId(groupId: triggersId, key: "audit") != schemaRow) + #expect( + DatabaseTreeNode.tableDetailId(groupId: columnsId, key: "status.loading") + != DatabaseTreeNode.statusId(parentId: columnsId, status: .loading) + ) + } + + @Test("Table Details opens every table but a sequence; partitions still follow their own option") + func expandabilityFollowsTheOptions() { + let plain = DatabaseTreeNode(id: "t", kind: .table(tableRef("users"))) + let partitioned = DatabaseTreeNode(id: "p", kind: .table(partitionedRef("orders"))) + let sequence = DatabaseTreeNode(id: "s", kind: .table(DatabaseTreeTableRef( + database: "shop", schema: "public", table: TableInfo(name: "order_ids", type: .sequence, rowCount: nil) + ))) + let subpartitioned = DatabaseTreeNode(id: "sp", kind: .partition(partitionRef("p1", isSubpartitioned: true))) + + #expect(!plain.isExpandable(showsPartitions: true, showsTableDetails: false)) + #expect(plain.isExpandable(showsPartitions: false, showsTableDetails: true)) + #expect(partitioned.isExpandable(showsPartitions: true, showsTableDetails: false)) + #expect(!partitioned.isExpandable(showsPartitions: false, showsTableDetails: false)) + #expect(partitioned.isExpandable(showsPartitions: false, showsTableDetails: true)) + #expect(!sequence.isExpandable(showsPartitions: true, showsTableDetails: true)) + #expect(subpartitioned.isExpandable(showsPartitions: true, showsTableDetails: true)) + #expect(!subpartitioned.isExpandable(showsPartitions: false, showsTableDetails: true)) + } + + @Test("A detail group expands like an object group, a detail row is a leaf, and a click opens neither") + func detailRowShapes() { + let orders = tableRef("orders") + let groupKind = DatabaseTreeNode.Kind.tableDetailGroup(DatabaseTreeTableDetailGroupRef(table: orders, kind: .indexes)) + let detailKind = DatabaseTreeNode.Kind.tableDetail( + DatabaseTreeTableDetailRef(table: orders, item: .column(TestFixtures.makeColumnInfo(name: "total"))) + ) + let group = DatabaseTreeNode(id: "g", kind: groupKind) + let detail = DatabaseTreeNode(id: "d", kind: detailKind) + + #expect(group.isExpandable) + #expect(!detail.isExpandable) + #expect(!group.isGroupRow) + #expect(!detail.isGroupRow) + #expect(!group.isContainer) + #expect(group.containerRef(systemSchemas: []) == nil) + #expect(group.tableRef == nil) + #expect(detail.tableRef == nil) + #expect(DatabaseTreeSelection.isSelectable(groupKind)) + #expect(DatabaseTreeSelection.isSelectable(detailKind)) + #expect(DatabaseTreeTypeSelect.matchString(for: groupKind) == String(localized: "Indexes")) + #expect(DatabaseTreeTypeSelect.matchString(for: detailKind) == "total") + } } From 544edec81adb1c5f396f7e6825ec96f405b8d0d3 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:10:19 +0700 Subject: [PATCH 008/123] feat(sidebar): list, load and record a table's detail groups Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- ...baseTreeOutlineCoordinator+Expansion.swift | 40 ++- ...DatabaseTreeOutlineCoordinator+Nodes.swift | 13 +- ...eTreeOutlineCoordinator+TableDetails.swift | 56 ++++ .../DatabaseTreeOutlineCoordinator.swift | 3 +- .../DatabaseTreeTableDetailOutlineTests.swift | 264 ++++++++++++++++++ 5 files changed, 365 insertions(+), 11 deletions(-) create mode 100644 apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift create mode 100644 apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift index 7cd99e5302..34aef033af 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift @@ -196,10 +196,10 @@ extension DatabaseTreeOutlineCoordinator { restoreObjectGroupExpansion(under: node) case .foldersSection: restoreFolderExpansion(under: node) - case .objectKindSection, .containerObjectKindSection, .tableFolder, .table, .partition: + case .objectKindSection, .containerObjectKindSection, .tableFolder, .table, .partition, .tableDetailGroup: restorePartitionExpansion(under: node) case .recentSection, .recentTable, .temporarySection, .temporaryTable, .database, .routine, .trigger, - .userType, .status, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: + .userType, .status, .redisKeysSection, .redisNode, .tableDetail: break } } @@ -257,7 +257,13 @@ extension DatabaseTreeOutlineCoordinator { case .partition(let ref): guard let tableRef = ref.tableRef else { break } recordTableExpansion(tableRef, expanded: expanded) - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .redisNode, .tableDetailGroup, .tableDetail: + case .tableDetailGroup(let group): + if expanded { + windowState?.expandedTreeTableDetailGroups.insert(group.expansionKey) + } else { + windowState?.expandedTreeTableDetailGroups.remove(group.expansionKey) + } + case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .redisNode, .tableDetail: break } } @@ -282,6 +288,8 @@ extension DatabaseTreeOutlineCoordinator { loadPartitions(ref) case .partition(let ref): loadPartitions(ref.tableRef ?? ref.parent) + case .tableDetailGroup(let group): + loadTableDetailGroup(group) case .hierarchicalSchemaSection(let schema): guard DatabaseTreeFilter.readsOnDisclosure(origin: disclosureOrigin) || !hierarchicalSearchSkipsRead(schema) @@ -289,7 +297,7 @@ extension DatabaseTreeOutlineCoordinator { loadHierarchicalSchemaObjects(schema) case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, - .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: + .redisKeysSection, .redisNode, .tableDetail: break } } @@ -393,6 +401,30 @@ extension DatabaseTreeOutlineCoordinator { } } + /// A group reads its own list alone. Partitions keep their own list and the rule it already follows. + private func loadTableDetailGroup(_ group: DatabaseTreeTableDetailGroupRef) { + let ref = group.table + guard let kind = group.kind.detailKind else { + loadPartitions(ref) + return + } + let connectionId = connectionId + let database = ref.database ?? "" + let phase = service.tableDetailsLoadState( + connectionId: connectionId, database: database, schema: ref.schema, table: ref.table.name, kind: kind + ).erased + let needsFetch = service.tableDetailsNeedFetch( + connectionId: connectionId, database: database, schema: ref.schema, table: ref.table.name, kind: kind + ) + guard TableDetailGroupResolver.readsOnDisclosure(needsFetch: needsFetch, phase: phase, origin: disclosureOrigin) + else { return } + Task { + await service.loadTableDetails( + connectionId: connectionId, database: database, schema: ref.schema, table: ref.table.name, kind: kind + ) + } + } + /// An expanded container whose lists a change overtook reads them again on the next pass; a /// collapsed one waits until it is opened. private func loadObjects(database: String, schema: String?) { diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift index 987ef448f2..f2decd7602 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift @@ -64,7 +64,7 @@ extension DatabaseTreeOutlineCoordinator { return objectNodes(database: database, schema: schema) case .table(let ref): guard showsPartitions, ref.table.type == .partitionedTable else { return [] } - return partitionNodes(of: ref) + return partitionNodes(of: ref, parentId: DatabaseTreeNode.tableId(ref)) case .partition(let ref): guard showsPartitions, ref.partition.isSubpartitioned else { return [] } return subpartitionNodes(of: ref) @@ -78,15 +78,16 @@ extension DatabaseTreeOutlineCoordinator { return redisChildren(of: nil) case .redisNode(let redisNode): return redisChildren(of: redisNode) - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetailGroup, .tableDetail: + case .tableDetailGroup(let group): + return tableDetailNodes(in: group) + case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetail: return [] } } /// Only the top-level partitions. A subpartition names the partition it subdivides and is /// nested under that row instead, because an engine that has them reports both in one list. - private func partitionNodes(of ref: DatabaseTreeTableRef) -> [DatabaseTreeNode] { - let parentId = DatabaseTreeNode.tableId(ref) + internal func partitionNodes(of ref: DatabaseTreeTableRef, parentId: String) -> [DatabaseTreeNode] { let state = service.partitionsLoadState( connectionId: connectionId, database: ref.database ?? "", schema: ref.schema, table: ref.table.name ) @@ -108,7 +109,7 @@ extension DatabaseTreeOutlineCoordinator { /// own list carrying its name. private func subpartitionNodes(of ref: DatabaseTreePartitionRef) -> [DatabaseTreeNode] { if let relation = ref.tableRef { - return partitionNodes(of: relation) + return partitionNodes(of: relation, parentId: DatabaseTreeNode.tableId(relation)) } let parent = ref.parent let state = service.partitionsLoadState( @@ -802,7 +803,7 @@ extension DatabaseTreeOutlineCoordinator { } } - private func statusNode(parentId: String, status: DatabaseTreeNode.Status) -> DatabaseTreeNode { + internal func statusNode(parentId: String, status: DatabaseTreeNode.Status) -> DatabaseTreeNode { node(id: DatabaseTreeNode.statusId(parentId: parentId, status: status), kind: .status(status)) } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift new file mode 100644 index 0000000000..03e1fe404a --- /dev/null +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift @@ -0,0 +1,56 @@ +// +// DatabaseTreeOutlineCoordinator+TableDetails.swift +// TablePro +// + +import Foundation + +/// The rows under a table while Table Details is on: one group per kind of detail, and under each +/// group the list its engine read for that table. +extension DatabaseTreeOutlineCoordinator { + internal func tableDetailNodes(in group: DatabaseTreeTableDetailGroupRef) -> [DatabaseTreeNode] { + let groupId = DatabaseTreeNode.tableDetailGroupId(group) + let ref = group.table + guard let kind = group.kind.detailKind else { + return partitionNodes(of: ref, parentId: groupId) + } + switch tableDetailsLoadState(ref, kind: kind) { + case .idle, .loading: + return [statusNode(parentId: groupId, status: .loading)] + case .failed(let message): + return [statusNode(parentId: groupId, status: .error(message))] + case .loaded(let list): + let entries = TableDetailRows.entries(for: list, table: ref) + guard !entries.isEmpty else { return [statusNode(parentId: groupId, status: .empty)] } + return entries.map { entry in + let id = DatabaseTreeNode.tableDetailId(groupId: groupId, key: entry.key) + switch entry.row { + case .detail(let detail): return node(id: id, kind: .tableDetail(detail)) + case .trigger(let trigger): return node(id: id, kind: .trigger(trigger)) + } + } + } + } + + /// Nil until the group's list has loaded, so the row shows no number rather than a zero it does not know. + internal func tableDetailCount(_ group: DatabaseTreeTableDetailGroupRef) -> Int? { + let ref = group.table + guard let kind = group.kind.detailKind else { + return service.partitionsLoadState( + connectionId: connectionId, database: ref.database ?? "", schema: ref.schema, table: ref.table.name + ) + .value? + .filter { $0.parentPartitionName == nil } + .count + } + return tableDetailsLoadState(ref, kind: kind).value?.count + } + + private func tableDetailsLoadState( + _ ref: DatabaseTreeTableRef, kind: TableDetailKind + ) -> MetadataLoadState { + service.tableDetailsLoadState( + connectionId: connectionId, database: ref.database ?? "", schema: ref.schema, table: ref.table.name, kind: kind + ) + } +} diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 1a14f9b90b..26f173afc5 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -625,7 +625,8 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { self?.routineDisplayLabels[ref.id] ?? ref.routine.name }, showsPartitions: showsPartitions, - listsAttachedSchemas: listsAttachedSchemas + listsAttachedSchemas: listsAttachedSchemas, + tableDetailCount: { [weak self] group in self?.tableDetailCount(group) } ) } diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift new file mode 100644 index 0000000000..9823a47c10 --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift @@ -0,0 +1,264 @@ +import AppKit +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import Testing + +/// A table's detail groups in a real outline: what each group lists, when it reads, and what the +/// window remembers. PGlite keeps every read on the injected session driver. +@MainActor +struct DatabaseTreeTableDetailOutlineTests { + private struct ReadFailed: Error {} + + private struct Fixture { + let connection: DatabaseConnection + let driver: CatalogReadCountingDriver + let coordinator: DatabaseTreeOutlineCoordinator + let windowState: WindowSidebarState + let outlineView: NSOutlineView + let scrollView: NSScrollView + } + + private let service = DatabaseTreeMetadataService.shared + + private func makeFixture() throws -> Fixture { + let connection = TestFixtures.makeConnection(type: .pglite) + let driver = CatalogReadCountingDriver(connection: connection) + driver.columnsByTable["orders"] = [ + TestFixtures.makeColumnInfo(name: "id", dataType: "integer"), + TestFixtures.makeColumnInfo(name: "total", dataType: "numeric", isPrimaryKey: false), + ] + driver.foreignKeysByTable["orders"] = [ + TestFixtures.makeForeignKeyInfo( + name: "orders_customer_fk", column: "customer_id", referencedTable: "customers", referencedColumn: "id" + ), + TestFixtures.makeForeignKeyInfo( + name: "orders_customer_fk", column: "customer_region", referencedTable: "customers", referencedColumn: "region" + ), + ] + driver.triggersByTable["orders"] = [ + TriggerInfo(name: "orders_audit", timing: "AFTER", event: "INSERT", statement: "") + ] + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + DatabaseManager.shared.injectSession(session, for: connection.id) + + let scrollView = SidebarOutlineScaffold.makeScrollView( + outlineView: NSOutlineView(), + configuration: SidebarOutlineScaffold.Configuration( + columnIdentifier: "TableDetailColumn", + allowsMultipleSelection: true, + rowSizePreference: .medium + ) + ) + let outlineView = try #require(scrollView.documentView as? NSOutlineView) + let windowState = WindowSidebarState() + let coordinator = DatabaseTreeOutlineCoordinator() + coordinator.connectionId = connection.id + coordinator.databaseType = .pglite + coordinator.windowState = windowState + outlineView.dataSource = coordinator + outlineView.delegate = coordinator + coordinator.attach(outlineView: outlineView) + return Fixture( + connection: connection, + driver: driver, + coordinator: coordinator, + windowState: windowState, + outlineView: outlineView, + scrollView: scrollView + ) + } + + private func tearDown(_ fixture: Fixture) async { + await service.handleDisconnect(connectionId: fixture.connection.id) + DatabaseManager.shared.removeSession(for: fixture.connection.id) + _ = fixture.scrollView + } + + private func orders(_ fixture: Fixture, type: TableInfo.TableType = .table) -> DatabaseTreeTableRef { + DatabaseTreeTableRef( + database: fixture.connection.database, + schema: "public", + table: TableInfo(name: "orders", type: type, rowCount: nil, schema: "public") + ) + } + + private func group( + _ fixture: Fixture, _ kind: TableDetailGroupKind, type: TableInfo.TableType = .table + ) -> DatabaseTreeTableDetailGroupRef { + DatabaseTreeTableDetailGroupRef(table: orders(fixture, type: type), kind: kind) + } + + private func node(_ fixture: Fixture, _ group: DatabaseTreeTableDetailGroupRef) -> DatabaseTreeNode { + fixture.coordinator.node(id: DatabaseTreeNode.tableDetailGroupId(group), kind: .tableDetailGroup(group)) + } + + private func load(_ fixture: Fixture, _ kind: TableDetailKind) async { + await service.loadTableDetails( + connectionId: fixture.connection.id, database: fixture.connection.database, + schema: "public", table: "orders", kind: kind + ) + } + + private func detailState(_ fixture: Fixture, _ kind: TableDetailKind) -> MetadataLoadState { + service.tableDetailsLoadState( + connectionId: fixture.connection.id, database: fixture.connection.database, + schema: "public", table: "orders", kind: kind + ) + } + + /// What a reload after a landed list builds. + private func rebuiltChildren(_ fixture: Fixture, of node: DatabaseTreeNode) -> [DatabaseTreeNode] { + fixture.coordinator.childrenCache.removeValue(forKey: node.id) + return fixture.coordinator.resolvedChildren(of: node) + } + + private func showAtRoot(_ fixture: Fixture, _ nodes: [DatabaseTreeNode]) { + fixture.coordinator.childrenCache = ["": nodes] + fixture.outlineView.reloadData() + } + + @Test("A Columns group shows a loading row, then one row per column and its count") + func columnsGroupListsColumns() async throws { + let fixture = try makeFixture() + let columns = group(fixture, .columns) + let groupNode = node(fixture, columns) + let groupId = DatabaseTreeNode.tableDetailGroupId(columns) + let loadingIds = fixture.coordinator.resolvedChildren(of: groupNode).map { $0.id } + + #expect(loadingIds == [DatabaseTreeNode.statusId(parentId: groupId, status: .loading)]) + #expect(fixture.coordinator.tableDetailCount(columns) == nil) + + await load(fixture, .columns) + + let names = rebuiltChildren(fixture, of: groupNode).compactMap { row -> String? in + guard case .tableDetail(let detail) = row.kind else { return nil } + return detail.item.name + } + #expect(names == ["id", "total"]) + #expect(fixture.coordinator.tableDetailCount(columns) == 2) + await tearDown(fixture) + } + + @Test("A two-column foreign key is one row, and the group counts it once") + func foreignKeyGroupCountsConstraints() async throws { + let fixture = try makeFixture() + let keys = group(fixture, .foreignKeys) + + await load(fixture, .foreignKeys) + + #expect(rebuiltChildren(fixture, of: node(fixture, keys)).count == 1) + #expect(fixture.coordinator.tableDetailCount(keys) == 1) + await tearDown(fixture) + } + + @Test("A trigger under its table is a trigger row, with an id apart from its schema's listing") + func triggerRowsUnderTheirTable() async throws { + let fixture = try makeFixture() + + await load(fixture, .triggers) + + let row = try #require(rebuiltChildren(fixture, of: node(fixture, group(fixture, .triggers))).first) + guard case .trigger(let ref) = row.kind else { + Issue.record("A trigger under its table is not a trigger row") + return + } + #expect(ref.listedUnderTable) + #expect(ref.trigger.table == "orders") + #expect(row.id != DatabaseTreeNode.triggerId(ref)) + await tearDown(fixture) + } + + @Test("Two checks that share a name are two rows") + func sameNamedChecksAreTwoRows() async throws { + let fixture = try makeFixture() + fixture.driver.checksByTable["orders"] = [ + CheckConstraintInfo(name: "", expression: "total > 0"), + CheckConstraintInfo(name: "", expression: "total < 1000"), + ] + + await load(fixture, .checks) + + let rows = rebuiltChildren(fixture, of: node(fixture, group(fixture, .checks))) + let ids = Set(rows.map { $0.id }) + #expect(rows.count == 2) + #expect(ids.count == 2) + #expect(rows.first !== rows.last) + await tearDown(fixture) + } + + @Test("A Partitions group lists the table's partitions, under a loading row of its own") + func partitionsGroupListsPartitions() async throws { + let fixture = try makeFixture() + let partitions = group(fixture, .partitions, type: .partitionedTable) + let groupId = DatabaseTreeNode.tableDetailGroupId(partitions) + + let ids = fixture.coordinator.resolvedChildren(of: node(fixture, partitions)).map { $0.id } + + #expect(ids == [DatabaseTreeNode.statusId(parentId: groupId, status: .loading)]) + await tearDown(fixture) + } + + @Test("An empty list shows the empty row, and a failed read its error under its own group") + func emptyAndFailedListsShowTheirStatus() async throws { + let fixture = try makeFixture() + let indexes = group(fixture, .indexes) + let checks = group(fixture, .checks) + + await load(fixture, .indexes) + fixture.driver.detailError = ReadFailed() + await load(fixture, .checks) + + let indexIds = rebuiltChildren(fixture, of: node(fixture, indexes)).map { $0.id } + let checkRows = rebuiltChildren(fixture, of: node(fixture, checks)) + let indexesId = DatabaseTreeNode.tableDetailGroupId(indexes) + #expect(indexIds == [DatabaseTreeNode.statusId(parentId: indexesId, status: .empty)]) + #expect(fixture.coordinator.tableDetailCount(indexes) == 0) + guard checkRows.count == 1, case .status(.error) = checkRows[0].kind else { + Issue.record("A failed read does not show its error row") + await tearDown(fixture) + return + } + #expect(fixture.coordinator.resolvedChildren(of: node(fixture, group(fixture, .columns))).count == 1) + await tearDown(fixture) + } + + @Test("Opening a group reads its own kind alone, and the window records it open and closed") + func openingAGroupReadsItsKind() async throws { + let fixture = try makeFixture() + let indexes = group(fixture, .indexes) + let groupNode = node(fixture, indexes) + showAtRoot(fixture, [groupNode]) + + fixture.outlineView.expandItem(groupNode) + try await waitUntil { detailState(fixture, .indexes).value != nil } + + #expect(fixture.driver.detailReads == ["indexes:orders"]) + #expect(fixture.windowState.expandedTreeTableDetailGroups == [indexes.expansionKey]) + + fixture.outlineView.collapseItem(groupNode) + #expect(fixture.windowState.expandedTreeTableDetailGroups.isEmpty) + await tearDown(fixture) + } + + @Test("A group whose read failed reads again when the user opens it again") + func reopeningAFailedGroupRetries() async throws { + let fixture = try makeFixture() + let groupNode = node(fixture, group(fixture, .columns)) + showAtRoot(fixture, [groupNode]) + fixture.driver.detailError = ReadFailed() + + fixture.outlineView.expandItem(groupNode) + try await waitUntil { detailState(fixture, .columns).erased.failureMessage != nil } + + fixture.driver.detailError = nil + fixture.outlineView.collapseItem(groupNode) + fixture.outlineView.expandItem(groupNode) + try await waitUntil { detailState(fixture, .columns).value != nil } + + #expect(fixture.driver.detailReads == ["columns:orders", "columns:orders"]) + await tearDown(fixture) + } +} From ad8cc2bfbc49c190ce734479cb3fe31e3d9c355e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:17:28 +0700 Subject: [PATCH 009/123] feat(sidebar): expand tables to their detail groups when Table Details is on Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- ...baseTreeOutlineCoordinator+Expansion.swift | 45 +++--- ...DatabaseTreeOutlineCoordinator+Nodes.swift | 1 + ...eTreeOutlineCoordinator+TableDetails.swift | 13 ++ .../DatabaseTreeOutlineCoordinator.swift | 19 +-- .../Sidebar/DatabaseTreeOutlineView.swift | 1 + .../Sidebar/DatabaseTreeRenderInputs.swift | 2 + .../Views/Sidebar/DatabaseTreeView.swift | 1 + .../Views/Sidebar/SidebarTreeView.swift | 1 + .../TablePro/Views/Sidebar/SidebarView.swift | 1 + .../DatabaseTreeTableDetailOutlineTests.swift | 144 +++++++++++++++++- 10 files changed, 198 insertions(+), 30 deletions(-) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift index 34aef033af..04eb52ee44 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift @@ -30,7 +30,7 @@ extension DatabaseTreeOutlineCoordinator { case .objectKindSection(let kind): let hasMatches = flatItemCount(for: kind) > 0 setExpanded(sectionNode, viewModel?.effectiveExpanded(kind: kind, hasMatches: hasMatches) ?? true) - if outlineView.isItemExpanded(sectionNode) { restorePartitionExpansion(under: sectionNode) } + if outlineView.isItemExpanded(sectionNode) { restoreTableExpansion(under: sectionNode) } case .foldersSection: setExpanded(sectionNode, searching || (viewModel?.isFoldersExpanded ?? true)) if outlineView.isItemExpanded(sectionNode) { restoreFolderExpansion(under: sectionNode) } @@ -116,27 +116,35 @@ extension DatabaseTreeOutlineCoordinator { ) } - /// Both a partitioned table and a subpartitioned partition of one are restored here. On - /// PostgreSQL a subpartitioned partition is a relation of its own and loads its own children, so - /// it is recorded and re-expanded under the same key a table uses. - private func restorePartitionExpansion(under parent: DatabaseTreeNode) { - guard showsPartitions, searchText.isEmpty, let outlineView = self.outlineView, let windowState - else { return } + /// A table, its detail groups and a subpartitioned partition are restored here. On PostgreSQL a + /// subpartitioned partition is a relation of its own and loads its own children, so it is + /// recorded and re-expanded under the same key a table uses. A section can hold 17,000 tables, + /// so the names the window recorded are checked before any key is built. + private func restoreTableExpansion(under parent: DatabaseTreeNode) { + guard showsPartitions || showsTableDetails, searchText.isEmpty, + let outlineView = self.outlineView, let windowState else { return } + let expandedNames = Set(windowState.expandedTreeTables.map { $0.table }) + guard !expandedNames.isEmpty else { return } for node in resolvedChildren(of: parent) { - guard node.isExpandable, let ref = expandableTableRef(of: node) else { continue } - let key = DatabaseTableKey(database: ref.database ?? "", schema: ref.schema, table: ref.table.name) - guard windowState.expandedTreeTables.contains(key) else { continue } + if case .tableDetailGroup(let group) = node.kind { + guard windowState.expandedTreeTableDetailGroups.contains(group.expansionKey) else { continue } + } else { + guard let ref = expandableTableRef(of: node), expandedNames.contains(ref.table.name), + node.isExpandable(showsPartitions: showsPartitions, showsTableDetails: showsTableDetails), + windowState.expandedTreeTables.contains(DatabaseTableKey(ref)) + else { continue } + } setExpanded(node, true) guard outlineView.isItemExpanded(node) else { continue } triggerLoad(for: node) - restorePartitionExpansion(under: node) + restoreTableExpansion(under: node) } } private func expandableTableRef(of node: DatabaseTreeNode) -> DatabaseTreeTableRef? { switch node.kind { case .table(let ref): - return ref.table.type == .partitionedTable ? ref : nil + return ref case .partition(let ref): return ref.tableRef default: @@ -145,11 +153,10 @@ extension DatabaseTreeOutlineCoordinator { } private func recordTableExpansion(_ ref: DatabaseTreeTableRef, expanded: Bool) { - let key = DatabaseTableKey(database: ref.database ?? "", schema: ref.schema, table: ref.table.name) if expanded { - windowState?.expandedTreeTables.insert(key) + windowState?.expandedTreeTables.insert(DatabaseTableKey(ref)) } else { - windowState?.expandedTreeTables.remove(key) + windowState?.expandedTreeTables.remove(DatabaseTableKey(ref)) } } @@ -162,7 +169,7 @@ extension DatabaseTreeOutlineCoordinator { guard let ref = folderNode.folderRef else { continue } let collapsed = windowState?.collapsedTableFolders.contains(ref.folder.id) ?? false setExpanded(folderNode, searching || !collapsed) - if outlineView.isItemExpanded(folderNode) { restorePartitionExpansion(under: folderNode) } + if outlineView.isItemExpanded(folderNode) { restoreTableExpansion(under: folderNode) } } } @@ -178,7 +185,7 @@ extension DatabaseTreeOutlineCoordinator { stored: windowState?.isTreeObjectGroupExpanded(group) ?? group.kind.isExpandedByDefault ) setExpanded(groupNode, expanded) - if outlineView.isItemExpanded(groupNode) { restorePartitionExpansion(under: groupNode) } + if outlineView.isItemExpanded(groupNode) { restoreTableExpansion(under: groupNode) } } } @@ -197,7 +204,7 @@ extension DatabaseTreeOutlineCoordinator { case .foldersSection: restoreFolderExpansion(under: node) case .objectKindSection, .containerObjectKindSection, .tableFolder, .table, .partition, .tableDetailGroup: - restorePartitionExpansion(under: node) + restoreTableExpansion(under: node) case .recentSection, .recentTable, .temporarySection, .temporaryTable, .database, .routine, .trigger, .userType, .status, .redisKeysSection, .redisNode, .tableDetail: break @@ -285,6 +292,8 @@ extension DatabaseTreeOutlineCoordinator { else { return } loadObjects(database: database, schema: schema) case .table(let ref): + // With Table Details on, partitions load with their own group rather than with the table. + guard !showsTableDetails else { return } loadPartitions(ref) case .partition(let ref): loadPartitions(ref.tableRef ?? ref.parent) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift index f2decd7602..9cd545f5a8 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift @@ -63,6 +63,7 @@ extension DatabaseTreeOutlineCoordinator { case .schema(let database, let schema): return objectNodes(database: database, schema: schema) case .table(let ref): + if showsTableDetails { return tableDetailGroupNodes(of: ref) } guard showsPartitions, ref.table.type == .partitionedTable else { return [] } return partitionNodes(of: ref, parentId: DatabaseTreeNode.tableId(ref)) case .partition(let ref): diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift index 03e1fe404a..0b37486583 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+TableDetails.swift @@ -8,6 +8,19 @@ import Foundation /// The rows under a table while Table Details is on: one group per kind of detail, and under each /// group the list its engine read for that table. extension DatabaseTreeOutlineCoordinator { + /// What a table lists follows its relation type and what its engine can read. + internal func tableDetailGroupNodes(of ref: DatabaseTreeTableRef) -> [DatabaseTreeNode] { + TableDetailGroupResolver.groups( + for: ref.table.type, + capabilities: TableDetailCapabilities(databaseType: databaseType), + showsPartitions: showsPartitions + ) + .map { kind in + let group = DatabaseTreeTableDetailGroupRef(table: ref, kind: kind) + return node(id: DatabaseTreeNode.tableDetailGroupId(group), kind: .tableDetailGroup(group)) + } + } + internal func tableDetailNodes(in group: DatabaseTreeTableDetailGroupRef) -> [DatabaseTreeNode] { let groupId = DatabaseTreeNode.tableDetailGroupId(group) let ref = group.table diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 26f173afc5..003b7e4850 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -38,6 +38,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { internal var showRecentTables = true internal var showSystemContainers = false internal var showsPartitions = true + internal var showsTableDetails = false private var rowSize: SidebarRowSize = .medium internal var nodeCache: [String: DatabaseTreeNode] = [:] @@ -218,6 +219,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { || showRecentTables != view.showRecentTables || showSystemContainers != view.showSystemContainers || showsPartitions != view.showsPartitions + || showsTableDetails != view.showsTableDetails || rowSize != view.resolvedRowSize searchText = view.searchText @@ -229,6 +231,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { showRecentTables = view.showRecentTables showSystemContainers = view.showSystemContainers showsPartitions = view.showsPartitions + showsTableDetails = view.showsTableDetails rowSize = view.resolvedRowSize if !hasRenderedOnce || activeChanged { @@ -779,18 +782,12 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDataSource { } /// `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. + /// read. Whether a table or a partition discloses also follows the Partitions and Table Details + /// options, so the gate reads the node's options rule. Without it a hidden set of children left + /// a disclosure triangle that opened on nothing. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { - guard let node = item as? DatabaseTreeNode, node.isExpandable else { return false } - switch node.kind { - case .table(let ref) where ref.table.type == .partitionedTable: - return showsPartitions - case .partition: - return showsPartitions - default: - return true - } + guard let node = item as? DatabaseTreeNode else { return false } + return node.isExpandable(showsPartitions: showsPartitions, showsTableDetails: showsTableDetails) } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift index 178b7a3d1c..09f18f6633 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift @@ -31,6 +31,7 @@ struct DatabaseTreeOutlineView: NSViewRepresentable { let showRecentTables: Bool let showSystemContainers: Bool let showsPartitions: Bool + let showsTableDetails: Bool let rowSizePreference: SidebarRowSizePreference /// The size the rows are actually drawn at, which is the system's unless the user overrode it. diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRenderInputs.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRenderInputs.swift index 6dbbfc1048..e47629284b 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRenderInputs.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRenderInputs.swift @@ -79,6 +79,7 @@ struct DatabaseTreeRenderInputs: Equatable { let types: [ObjectsKey: Rows] let currency: [ObjectsKey: Currency] let partitions: [DatabaseTreeMetadataService.PartitionsKey: Rows] + let tableDetails: [DatabaseTreeMetadataService.TableDetailsKey: MetadataLoadState] let listings: [DatabaseKey: Listing] let listsRevision: Int let catalogGeneration: Int @@ -133,6 +134,7 @@ struct DatabaseTreeRenderInputs: Equatable { self.types = types self.currency = currency self.partitions = Self.slice(treeMetadata.partitionsState, where: { $0.connectionId == connectionId }) { Rows($0) } + self.tableDetails = Self.slice(treeMetadata.tableDetailsState, where: { $0.connectionId == connectionId }) { $0 } self.listings = listings self.listsRevision = treeMetadata.listsRevision(for: connectionId) self.catalogGeneration = schemaService.generationToken(for: connectionId) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift index ccf914b04d..a0906ab5b4 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift @@ -191,6 +191,7 @@ struct DatabaseTreeView: View { showRecentTables: settingsManager.general.showRecentTables, showSystemContainers: showsSystemContainers, showsPartitions: settingsManager.general.showPartitions, + showsTableDetails: settingsManager.general.showTableDetails, rowSizePreference: settingsManager.general.sidebarRowSize ) } diff --git a/apple/TablePro/Views/Sidebar/SidebarTreeView.swift b/apple/TablePro/Views/Sidebar/SidebarTreeView.swift index eda2191cae..aef81b2b5b 100644 --- a/apple/TablePro/Views/Sidebar/SidebarTreeView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarTreeView.swift @@ -111,6 +111,7 @@ struct SidebarTreeView: View { showRecentTables: settingsManager.general.showRecentTables, showSystemContainers: settingsManager.general.showSystemContainers, showsPartitions: settingsManager.general.showPartitions, + showsTableDetails: settingsManager.general.showTableDetails, rowSizePreference: settingsManager.general.sidebarRowSize ) } diff --git a/apple/TablePro/Views/Sidebar/SidebarView.swift b/apple/TablePro/Views/Sidebar/SidebarView.swift index ec55eab1ab..ab75b0127a 100644 --- a/apple/TablePro/Views/Sidebar/SidebarView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarView.swift @@ -483,6 +483,7 @@ struct SidebarView: View { showRecentTables: settingsManager.general.showRecentTables, showSystemContainers: settingsManager.general.showSystemContainers, showsPartitions: settingsManager.general.showPartitions, + showsTableDetails: settingsManager.general.showTableDetails, rowSizePreference: settingsManager.general.sidebarRowSize ) } diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift index 9823a47c10..846abe2458 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift @@ -22,7 +22,7 @@ struct DatabaseTreeTableDetailOutlineTests { private let service = DatabaseTreeMetadataService.shared - private func makeFixture() throws -> Fixture { + private func makeFixture(showsTableDetails: Bool = true, showsPartitions: Bool = true) throws -> Fixture { let connection = TestFixtures.makeConnection(type: .pglite) let driver = CatalogReadCountingDriver(connection: connection) driver.columnsByTable["orders"] = [ @@ -58,6 +58,8 @@ struct DatabaseTreeTableDetailOutlineTests { coordinator.connectionId = connection.id coordinator.databaseType = .pglite coordinator.windowState = windowState + coordinator.showsTableDetails = showsTableDetails + coordinator.showsPartitions = showsPartitions outlineView.dataSource = coordinator outlineView.delegate = coordinator coordinator.attach(outlineView: outlineView) @@ -261,4 +263,144 @@ struct DatabaseTreeTableDetailOutlineTests { #expect(fixture.driver.detailReads == ["columns:orders", "columns:orders"]) await tearDown(fixture) } + + private func tableNode(_ fixture: Fixture, type: TableInfo.TableType = .table) -> DatabaseTreeNode { + let ref = orders(fixture, type: type) + return fixture.coordinator.node(id: DatabaseTreeNode.tableId(ref), kind: .table(ref)) + } + + private func groupKinds(_ fixture: Fixture, of node: DatabaseTreeNode) -> [TableDetailGroupKind] { + fixture.coordinator.resolvedChildren(of: node).compactMap { child in + guard case .tableDetailGroup(let group) = child.kind else { return nil } + return group.kind + } + } + + private func isExpandable(_ fixture: Fixture, _ node: DatabaseTreeNode) -> Bool { + fixture.coordinator.outlineView(fixture.outlineView, isItemExpandable: node) + } + + /// What `refresh()` does for these rows: drop every built child, reload, and put the saved + /// disclosure back. The root is the flat shape's Tables section with one table under it. + private func reloadFlat(_ fixture: Fixture, table: DatabaseTreeNode) { + let section = fixture.coordinator.node( + id: DatabaseTreeNode.objectKindSectionId(.table), kind: .objectKindSection(.table) + ) + fixture.coordinator.childrenCache = ["": [section], section.id: [table]] + fixture.outlineView.reloadData() + fixture.coordinator.applyDesiredExpansion() + } + + @Test("With Table Details off, a plain table has no triangle and a partitioned one lists partitions as before") + func detailsOffKeepsTodaysTree() async throws { + let fixture = try makeFixture(showsTableDetails: false) + let partitionedId = DatabaseTreeNode.tableId(orders(fixture, type: .partitionedTable)) + let partitioned = tableNode(fixture, type: .partitionedTable) + let childIds = fixture.coordinator.resolvedChildren(of: partitioned).map { $0.id } + + #expect(!isExpandable(fixture, tableNode(fixture))) + #expect(isExpandable(fixture, partitioned)) + #expect(childIds == [DatabaseTreeNode.statusId(parentId: partitionedId, status: .loading)]) + await tearDown(fixture) + } + + @Test("With Table Details on, a table lists the groups its engine and relation type support") + func detailsOnListsGroups() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture) + + #expect(isExpandable(fixture, table)) + #expect(groupKinds(fixture, of: table) == [.columns, .indexes, .foreignKeys, .checks, .triggers]) + #expect(groupKinds(fixture, of: tableNode(fixture, type: .view)) == [.columns]) + #expect(groupKinds(fixture, of: tableNode(fixture, type: .materializedView)) == [.columns, .indexes]) + #expect(!isExpandable(fixture, tableNode(fixture, type: .sequence))) + await tearDown(fixture) + } + + @Test("A partitioned table's partitions move into a last Partitions group, shown only while Partitions is on") + func partitionsGroupFollowsItsOption() async throws { + let shown = try makeFixture() + let hidden = try makeFixture(showsPartitions: false) + let hiddenTable = tableNode(hidden, type: .partitionedTable) + + #expect(groupKinds(shown, of: tableNode(shown, type: .partitionedTable)).last == .partitions) + #expect(isExpandable(hidden, hiddenTable)) + #expect(!groupKinds(hidden, of: hiddenTable).contains(.partitions)) + await tearDown(shown) + await tearDown(hidden) + } + + @Test("Opening a table reads nothing until one of its groups opens") + func openingATableReadsNothing() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture, type: .partitionedTable) + showAtRoot(fixture, [table]) + + fixture.outlineView.expandItem(table) + let columns = try #require(fixture.coordinator.resolvedChildren(of: table).first) + fixture.outlineView.expandItem(columns) + try await waitUntil { detailState(fixture, .columns).value != nil } + + let partitions = service.partitionsLoadState( + connectionId: fixture.connection.id, database: fixture.connection.database, schema: "public", table: "orders" + ) + #expect(fixture.driver.detailReads == ["columns:orders"]) + #expect(partitions.erased == .idle) + await tearDown(fixture) + } + + @Test("An open table and group come back after a reload, and the group reads its list") + func openGroupsAreRestored() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture) + let columns = group(fixture, .columns) + fixture.windowState.expandedTreeTables = [DatabaseTableKey(orders(fixture))] + fixture.windowState.expandedTreeTableDetailGroups = [columns.expansionKey] + + reloadFlat(fixture, table: table) + + #expect(fixture.outlineView.isItemExpanded(table)) + #expect(fixture.outlineView.isItemExpanded(node(fixture, columns))) + try await waitUntil { detailState(fixture, .columns).value != nil } + #expect(fixture.driver.detailReads == ["columns:orders"]) + await tearDown(fixture) + } + + @Test("A detail list landing changes what the outline draws, and another connection's does not") + func landingListMovesTheRenderInputs() async throws { + let fixture = try makeFixture() + let other = try makeFixture() + let before = fixture.coordinator.currentRenderInputs() + + await load(other, .columns) + #expect(fixture.coordinator.currentRenderInputs() == before) + + await load(fixture, .columns) + #expect(fixture.coordinator.currentRenderInputs() != before) + await tearDown(fixture) + await tearDown(other) + } + + @Test("Turning Table Details off shows the partitions again, and turning it on brings the open group back") + func togglingKeepsTheOpenGroup() async throws { + let fixture = try makeFixture() + let ref = orders(fixture, type: .partitionedTable) + let table = tableNode(fixture, type: .partitionedTable) + let columns = group(fixture, .columns, type: .partitionedTable) + fixture.windowState.expandedTreeTables = [DatabaseTableKey(ref)] + fixture.windowState.expandedTreeTableDetailGroups = [columns.expansionKey] + reloadFlat(fixture, table: table) + #expect(fixture.outlineView.isItemExpanded(node(fixture, columns))) + + fixture.coordinator.showsTableDetails = false + reloadFlat(fixture, table: table) + let plainIds = fixture.coordinator.resolvedChildren(of: table).map { $0.id } + #expect(plainIds == [DatabaseTreeNode.statusId(parentId: DatabaseTreeNode.tableId(ref), status: .loading)]) + #expect(fixture.windowState.expandedTreeTableDetailGroups == [columns.expansionKey]) + + fixture.coordinator.showsTableDetails = true + reloadFlat(fixture, table: table) + #expect(fixture.outlineView.isItemExpanded(node(fixture, columns))) + await tearDown(fixture) + } } From 03ddf33a8217764987c3f30ceadbee9ac7491504 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:02:02 +0700 Subject: [PATCH 010/123] fix(sidebar): keep an Option-click from opening every table's detail groups With Table Details on, an Option-click on a schema or Tables group made the outline open every table and every detail group below it. A schema of 2,000 tables queued about 10,000 detail reads and saved about 12,000 expansions, which a relaunch or catalog change then read again. The outline now notes an expand-children walk, and the delegate refuses tables and detail groups AppKit reaches only through it. A row expanded on its own still opens, and with Table Details off a partitioned table keeps opening with its schema as before. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Views/Sidebar/DatabaseTreeNode.swift | 18 +++++ .../DatabaseTreeOutlineCoordinator.swift | 9 +++ .../Sidebar/DatabaseTreeOutlineView.swift | 23 ++++++ .../Views/Sidebar/DatabaseTreeNodeTests.swift | 16 +++++ .../DatabaseTreeTableDetailOutlineTests.swift | 72 ++++++++++++++++++- 5 files changed, 137 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift index 61bd738a14..bc858db308 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift @@ -154,6 +154,24 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { } } + /// Whether an Option-click on a row above this one opens it too. With Table Details on, every + /// table holds groups that each read a list as they open, so a schema of 2,000 tables queued + /// about 10,000 reads and saved every row it opened. A table and its groups then open only by + /// their own click; a partitioned table keeps opening with its schema while the option is off. + func opensWithAncestor(showsTableDetails: Bool) -> Bool { + switch kind { + case .table: + return !showsTableDetails + case .tableDetailGroup: + return false + case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + .database, .schema, .partition, .tableDetail, .routine, .trigger, .userType, .status, + .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, + .redisNode: + return true + } + } + var tableRef: DatabaseTreeTableRef? { switch kind { case .table(let ref): return ref diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 003b7e4850..0043b5cc15 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -846,6 +846,15 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { return DatabaseTreeSelection.isSelectable(node.kind) } + /// Refusing a row here keeps it closed, so it posts no expansion: nothing records it and + /// nothing reads its list. A row expanded on its own is never refused. + func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool { + guard let node = item as? DatabaseTreeNode, + (outlineView as? DatabaseTreeNSOutlineView)?.isExpandingAsDescendant(node) == true + else { return true } + return node.opensWithAncestor(showsTableDetails: showsTableDetails) + } + /// 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 diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift index 09f18f6633..80452a3a23 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift @@ -110,6 +110,29 @@ final class DatabaseTreeNSOutlineView: SidebarOutlineView { override func insertNewline(_ sender: Any?) { primaryActionTarget?.performPrimaryAction() } + + /// An Option-click on a triangle and Option-Right Arrow both arrive here with `expandChildren` + /// set, and AppKit then asks `outlineView(_:shouldExpandItem:)` about each descendant without + /// saying why. The notifications carry only the row, so the walk is noted here for the delegate. + /// A single disclosure started inside the walk, such as a restore, clears it for its own span. + private var descendantWalk: DescendantWalk? + + private struct DescendantWalk { + let root: AnyObject? + } + + override func expandItem(_ item: Any?, expandChildren: Bool) { + let outer = descendantWalk + descendantWalk = expandChildren ? DescendantWalk(root: item as AnyObject?) : nil + defer { descendantWalk = outer } + super.expandItem(item, expandChildren: expandChildren) + } + + /// True for a row AppKit opens only because a row above it was expanded with its children. + func isExpandingAsDescendant(_ item: Any) -> Bool { + guard let walk = descendantWalk else { return false } + return walk.root !== item as AnyObject + } } @MainActor diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift index d5d911b194..ce6961f1e1 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeNodeTests.swift @@ -386,6 +386,22 @@ struct DatabaseTreeNodeTests { #expect(!subpartitioned.isExpandable(showsPartitions: false, showsTableDetails: true)) } + @Test("An Option-click above a table opens it only while Table Details is off, and never a detail group") + func optionClickReachesTablesOnlyWithoutDetails() { + let partitioned = DatabaseTreeNode(id: "p", kind: .table(partitionedRef("orders"))) + let group = DatabaseTreeNode( + id: "g", kind: .tableDetailGroup(DatabaseTreeTableDetailGroupRef(table: tableRef("orders"), kind: .columns)) + ) + let subpartitioned = DatabaseTreeNode(id: "sp", kind: .partition(partitionRef("p1", isSubpartitioned: true))) + let tablesGroup = DatabaseTreeNode(id: "o", kind: .containerObjectKindSection(objectGroup())) + + #expect(partitioned.opensWithAncestor(showsTableDetails: false)) + #expect(!partitioned.opensWithAncestor(showsTableDetails: true)) + #expect(!group.opensWithAncestor(showsTableDetails: true)) + #expect(subpartitioned.opensWithAncestor(showsTableDetails: false)) + #expect(tablesGroup.opensWithAncestor(showsTableDetails: true)) + } + @Test("A detail group expands like an object group, a detail row is a leaf, and a click opens neither") func detailRowShapes() { let orders = tableRef("orders") diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift index 846abe2458..c4da31c4e9 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift @@ -45,7 +45,7 @@ struct DatabaseTreeTableDetailOutlineTests { DatabaseManager.shared.injectSession(session, for: connection.id) let scrollView = SidebarOutlineScaffold.makeScrollView( - outlineView: NSOutlineView(), + outlineView: DatabaseTreeNSOutlineView(), configuration: SidebarOutlineScaffold.Configuration( columnIdentifier: "TableDetailColumn", allowsMultipleSelection: true, @@ -349,6 +349,76 @@ struct DatabaseTreeTableDetailOutlineTests { await tearDown(fixture) } + /// The flat shape's Tables section with one table under it, before any restore pass runs. + private func showFlat(_ fixture: Fixture, table: DatabaseTreeNode) -> DatabaseTreeNode { + let section = fixture.coordinator.node( + id: DatabaseTreeNode.objectKindSectionId(.table), kind: .objectKindSection(.table) + ) + fixture.coordinator.childrenCache = ["": [section], section.id: [table]] + fixture.outlineView.reloadData() + return section + } + + /// `expandItem(_:expandChildren:)` is what an Option-click on a disclosure triangle calls. + @Test("An Option-click on the Tables section opens no table, so no group reads or is saved") + func optionClickOpensNoTable() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture) + let section = showFlat(fixture, table: table) + + fixture.outlineView.expandItem(section, expandChildren: true) + let openGroups = fixture.coordinator.resolvedChildren(of: table).filter { group in + fixture.outlineView.isItemExpanded(group) + } + + #expect(fixture.outlineView.isItemExpanded(section)) + #expect(!fixture.outlineView.isItemExpanded(table)) + #expect(openGroups.isEmpty) + #expect(fixture.windowState.expandedTreeTables.isEmpty) + #expect(fixture.windowState.expandedTreeTableDetailGroups.isEmpty) + #expect(fixture.driver.detailReads.isEmpty) + await tearDown(fixture) + } + + @Test("An Option-click on a table opens that table alone, and a group still opens by its own click") + func optionClickOnATableOpensItAlone() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture) + showAtRoot(fixture, [table]) + + fixture.outlineView.expandItem(table, expandChildren: true) + let groups = fixture.coordinator.resolvedChildren(of: table) + let openGroups = groups.filter { group in fixture.outlineView.isItemExpanded(group) } + + #expect(fixture.outlineView.isItemExpanded(table)) + #expect(openGroups.isEmpty) + #expect(fixture.windowState.expandedTreeTables == [DatabaseTableKey(orders(fixture))]) + #expect(fixture.windowState.expandedTreeTableDetailGroups.isEmpty) + + let columns = try #require(groups.first) + fixture.outlineView.expandItem(columns) + try await waitUntil { detailState(fixture, .columns).value != nil } + + #expect(fixture.outlineView.isItemExpanded(columns)) + #expect(fixture.driver.detailReads == ["columns:orders"]) + await tearDown(fixture) + } + + @Test("With Table Details off, an Option-click still opens a partitioned table and reads its partitions") + func optionClickKeepsPartitionsWhenDetailsAreOff() async throws { + let fixture = try makeFixture(showsTableDetails: false) + let ref = orders(fixture, type: .partitionedTable) + let table = tableNode(fixture, type: .partitionedTable) + let section = showFlat(fixture, table: table) + + fixture.outlineView.expandItem(section, expandChildren: true) + try await waitUntil { fixture.driver.reads.contains("partitions:orders") } + + #expect(fixture.outlineView.isItemExpanded(table)) + #expect(fixture.windowState.expandedTreeTables == [DatabaseTableKey(ref)]) + await tearDown(fixture) + } + @Test("An open table and group come back after a reload, and the group reads its list") func openGroupsAreRestored() async throws { let fixture = try makeFixture() From abec2897096b5e809246eade78fd6a87ace928c9 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:07:48 +0700 Subject: [PATCH 011/123] fix(sidebar): drop table detail lists when Table Details turns off A Refresh on a Tables group read every loaded detail list again whatever the option said, so lists no row draws kept costing a read each after the option was off. Turning the option off now drops every detail list, so the tree matches the one without Table Details. Each key is superseded first, so a read still running commits nothing, and only reads started before the drop are cancelled. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/DatabaseTreeMetadataService.swift | 20 +++++++++++++++++ .../DatabaseTreeOutlineCoordinator.swift | 9 +++++++- ...DatabaseTreeTableDetailsServiceTests.swift | 22 +++++++++++++++++++ .../DatabaseTreeTableDetailOutlineTests.swift | 17 ++++++++++++++ 4 files changed, 67 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift index e52ca3188d..8485303bc5 100644 --- a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift +++ b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift @@ -684,6 +684,26 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { } } + /// Table Details is one option for every window, so turning it off drops every detail list: no + /// row draws one, and a refresh would read each of them again. Each key is superseded before any + /// suspension, so a read still running commits nothing, and only reads started before the drop + /// are cancelled, never one a group opened after the option came back on. + func dropTableDetails() { + guard !tableDetailsState.isEmpty else { return } + var dropped: [TableDetailsKey: Int] = [:] + for key in tableDetailsState.keys { + tableDetailsCommit.fence.supersede(key) + tableDetailsCommit.freshness.markChanged(key) + dropped[key] = tableDetailsCommit.freshness.revision(for: key) + } + tableDetailsState.removeAll() + Task { [dropped] in + await tableDetailsDedup.cancel { fetch in + dropped[fetch.key].map { fetch.revision < $0 } ?? false + } + } + } + /// A table's identity ignores its partition count, so the equality guard on a table list is blind /// to a count that moved; another client adding a partition is exactly that case. nonisolated internal static func partitionCountsChanged( diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 0043b5cc15..871529138a 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -38,7 +38,14 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { internal var showRecentTables = true internal var showSystemContainers = false internal var showsPartitions = true - internal var showsTableDetails = false + /// Off, no row draws a detail list, so the loaded ones go and nothing reads them again: the + /// tree is the one it was before Table Details existed. + internal var showsTableDetails = false { + didSet { + guard oldValue, !showsTableDetails else { return } + service.dropTableDetails() + } + } private var rowSize: SidebarRowSize = .medium internal var nodeCache: [String: DatabaseTreeNode] = [:] diff --git a/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift index 2c7324ee15..a41127f6e1 100644 --- a/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift +++ b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift @@ -206,6 +206,28 @@ struct DatabaseTreeTableDetailsServiceTests { DatabaseManager.shared.removeSession(for: connection.id) } + @Test("Dropping the lists clears every one, and a read the drop overtakes commits nothing") + func dropClearsListsAndOvertakesARead() async { + let (connection, driver) = connect() + await load(connection, .indexes) + driver.pausesNextTableFetch = true + var read: Task? + await withCheckedContinuation { (paused: CheckedContinuation) in + driver.onTableFetchPaused = { paused.resume() } + read = Task { await load(connection, .columns) } + } + + service.dropTableDetails() + driver.resumeTableFetch() + await read?.value + + #expect(state(connection, .columns) == .idle) + #expect(state(connection, .indexes) == .idle) + #expect(needsFetch(connection, .columns)) + #expect(needsFetch(connection, .indexes)) + await disconnect(connection) + } + @Test("Refreshing a schema's tables reads a loaded list again and drops one that never loaded") func refreshRidesWithTheTables() async { let (connection, driver) = connect() diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift index c4da31c4e9..ceb049e2d4 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift @@ -451,6 +451,23 @@ struct DatabaseTreeTableDetailOutlineTests { await tearDown(other) } + @Test("Turning Table Details off drops the lists it loaded, so a refresh reads none of them") + func turningDetailsOffDropsTheLists() async throws { + let fixture = try makeFixture() + await load(fixture, .columns) + await load(fixture, .triggers) + + fixture.coordinator.showsTableDetails = false + await service.refreshTableObjects( + connectionId: fixture.connection.id, database: fixture.connection.database, schema: "public" + ) + + #expect(fixture.driver.detailReads == ["columns:orders", "triggers:orders"]) + #expect(detailState(fixture, .columns) == .idle) + #expect(detailState(fixture, .triggers) == .idle) + await tearDown(fixture) + } + @Test("Turning Table Details off shows the partitions again, and turning it on brings the open group back") func togglingKeepsTheOpenGroup() async throws { let fixture = try makeFixture() From d9ea2b4fdf12a4e5019ccc431f2c4cda773afade Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:15:40 +0700 Subject: [PATCH 012/123] fix(sidebar): refresh table detail lists from a schema's Triggers and the hierarchical layout Refresh on a schema's Triggers group left each table's Triggers list stale, and Refresh in the hierarchical layout, which reloads through SchemaService, never touched a detail list. The Triggers refresh now reads the container's per-table trigger lists again, and the hierarchical refresh reads the schema's detail lists beside its objects, by the rule the Tables refresh follows. A schema refresh keeps one read per detail list, since two rereads of one key at once cancel the first. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/DatabaseTreeMetadataService.swift | 29 ++++++++++++++++--- .../DatabaseTreeOutlineCoordinator.swift | 12 +++++++- ...DatabaseTreeTableDetailsServiceTests.swift | 21 ++++++++++++++ .../DatabaseTreeTableDetailOutlineTests.swift | 18 ++++++++++++ 4 files changed, 75 insertions(+), 5 deletions(-) diff --git a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift index 8485303bc5..2bfd60af3c 100644 --- a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift +++ b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift @@ -608,10 +608,14 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { await reread(key, connectionId: connectionId, in: schemaLists, fetch: schemaListFetch(key)) } + /// The schema's trigger list alone beside the tables: the table refresh already reads every detail + /// list, the per-table Triggers among them, and reading one twice at once cancels the first read. func refreshObjects(connectionId: UUID, database: String, schema: String?) async { async let tables: Void = refreshTableObjects(connectionId: connectionId, database: database, schema: schema) async let routines: Void = refreshRoutineObjects(connectionId: connectionId, database: database, schema: schema) - async let triggers: Void = refreshTriggerObjects(connectionId: connectionId, database: database, schema: schema) + async let triggers: Void = rereadTriggers( + Self.objectsKey(connectionId: connectionId, database: database, schema: schema) + ) async let types: Void = refreshUserDefinedTypeObjects( connectionId: connectionId, database: database, schema: schema ) @@ -633,10 +637,19 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { await reread(key, connectionId: connectionId, in: routineLists, fetch: routineListFetch(key)) } + /// A table's Triggers group lists the same triggers one table at a time, so it reads again with + /// the schema's list rather than staying stale beside it. func refreshTriggerObjects(connectionId: UUID, database: String, schema: String?) async { - guard browsesTriggers(connectionId) else { return } let key = Self.objectsKey(connectionId: connectionId, database: database, schema: schema) - await reread(key, connectionId: connectionId, in: triggerLists, fetch: triggerListFetch(key)) + async let triggers: Void = rereadTriggers(key) + async let details: Void = refreshTableDetails(under: key, kinds: [.triggers]) + _ = await (triggers, details) + } + + /// The hierarchical layout reloads a schema through `SchemaService`, which holds no detail list, + /// so its Refresh reads the schema's detail lists here. + func refreshTableDetails(connectionId: UUID, database: String, schema: String?) async { + await refreshTableDetails(under: Self.objectsKey(connectionId: connectionId, database: database, schema: schema)) } func refreshUserDefinedTypeObjects(connectionId: UUID, database: String, schema: String?) async { @@ -649,6 +662,11 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { await reread(key, connectionId: key.connectionId, in: tableLists, fetch: tableListFetch(key)) } + private func rereadTriggers(_ key: ObjectsKey) async { + guard browsesTriggers(key.connectionId) else { return } + await reread(key, connectionId: key.connectionId, in: triggerLists, fetch: triggerListFetch(key)) + } + /// A list that is not loaded is dropped and read by its next reader rather than now. private func refreshPartitions(under key: ObjectsKey) async { for partitionKey in partitionKeys(matching: key) { @@ -668,9 +686,12 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { /// The rule partitions follow: a loaded list reads again over its rows, and one that never /// loaded is dropped for its next reader. - private func refreshTableDetails(under key: ObjectsKey) async { + private func refreshTableDetails( + under key: ObjectsKey, kinds: Set = Set(TableDetailKind.allCases) + ) async { let detailKeys = tableDetailsState.keys.filter { $0.connectionId == key.connectionId && $0.database == key.database && $0.schema == key.schema + && kinds.contains($0.kind) } for detailKey in detailKeys { guard case .loaded = tableDetailsState[detailKey] ?? .idle else { diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 871529138a..89584a37d4 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -711,11 +711,21 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { } } + /// `SchemaService` holds no table's detail lists, so they read again beside the schema's objects, + /// under the database a hierarchical table row names. internal func reloadHierarchicalSchemaObjects(_ schema: String) { let connectionId = connectionId let database = browsingDatabase + let service = service + let schemaService = schemaService Task { - await schemaService.reloadSchemaObjects(connectionId: connectionId, schema: schema, database: database) + async let objects: Void = schemaService.reloadSchemaObjects( + connectionId: connectionId, schema: schema, database: database + ) + async let details: Void = service.refreshTableDetails( + connectionId: connectionId, database: database ?? "", schema: schema + ) + _ = await (objects, details) } } diff --git a/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift index a41127f6e1..5daa3b455b 100644 --- a/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift +++ b/apple/TableProTests/Core/Services/Query/DatabaseTreeTableDetailsServiceTests.swift @@ -206,6 +206,27 @@ struct DatabaseTreeTableDetailsServiceTests { DatabaseManager.shared.removeSession(for: connection.id) } + @Test("Refreshing a schema's triggers reads its tables' loaded trigger lists again, and no other kind") + func triggerRefreshRereadsTableTriggers() async { + let (connection, driver) = connect() + await load(connection, .columns) + await load(connection, .triggers) + driver.triggersByTable["orders"] = [ + TriggerInfo(name: "orders_stamp", timing: "BEFORE", event: "UPDATE", statement: "") + ] + + await service.refreshTriggerObjects(connectionId: connection.id, database: connection.database, schema: "public") + + guard case .loaded(.triggers(let triggers)) = state(connection, .triggers) else { + Issue.record("The trigger list is not loaded after the refresh") + await disconnect(connection) + return + } + #expect(triggers.map { $0.name } == ["orders_stamp"]) + #expect(driver.detailReads == ["columns:orders", "triggers:orders", "triggers:orders"]) + await disconnect(connection) + } + @Test("Dropping the lists clears every one, and a read the drop overtakes commits nothing") func dropClearsListsAndOvertakesARead() async { let (connection, driver) = connect() diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift index ceb049e2d4..b19078ccb9 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift @@ -451,6 +451,24 @@ struct DatabaseTreeTableDetailOutlineTests { await tearDown(other) } + @Test("Refreshing a schema in the hierarchical layout reads its tables' loaded detail lists again") + func hierarchicalRefreshRereadsDetailLists() async throws { + let fixture = try makeFixture() + fixture.coordinator.activeDatabase = fixture.connection.database + await load(fixture, .columns) + fixture.driver.columnsByTable["orders"] = [TestFixtures.makeColumnInfo(name: "id", dataType: "bigint")] + + fixture.coordinator.reloadHierarchicalSchemaObjects("public") + try await waitUntil { fixture.driver.detailReads.count == 2 } + try await waitUntil { + guard case .loaded(.columns(let columns)) = detailState(fixture, .columns) else { return false } + return columns.map { $0.name } == ["id"] + } + + #expect(fixture.driver.detailReads == ["columns:orders", "columns:orders"]) + await tearDown(fixture) + } + @Test("Turning Table Details off drops the lists it loaded, so a refresh reads none of them") func turningDetailsOffDropsTheLists() async throws { let fixture = try makeFixture() From f5599c403961e2cc0fd36a15794904d9d68afee8 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:21:54 +0700 Subject: [PATCH 013/123] fix(sidebar): read open detail groups again while a search runs The restore pass returned early while the search field had text, and it was the only path that read an open group's list again. After a reconnect or a catalog change, an open group kept its spinner or its stale rows until the search was cleared. While a search runs, the pass still opens no table, but each table, partition and detail group already open on screen reads its list if a change overtook it. The rows a search shows are unchanged. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- ...baseTreeOutlineCoordinator+Expansion.swift | 25 +++++++++++- .../DatabaseTreeTableDetailOutlineTests.swift | 38 +++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift index 04eb52ee44..ffa7cc450b 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift @@ -121,8 +121,11 @@ extension DatabaseTreeOutlineCoordinator { /// recorded and re-expanded under the same key a table uses. A section can hold 17,000 tables, /// so the names the window recorded are checked before any key is built. private func restoreTableExpansion(under parent: DatabaseTreeNode) { - guard showsPartitions || showsTableDetails, searchText.isEmpty, - let outlineView = self.outlineView, let windowState else { return } + guard showsPartitions || showsTableDetails, let outlineView = self.outlineView, let windowState else { return } + guard searchText.isEmpty else { + readOpenDetailRows(under: parent) + return + } let expandedNames = Set(windowState.expandedTreeTables.map { $0.table }) guard !expandedNames.isEmpty else { return } for node in resolvedChildren(of: parent) { @@ -141,6 +144,24 @@ extension DatabaseTreeOutlineCoordinator { } } + /// A search decides what is open and opens no table, yet a group already open on screen still + /// reads a list a change or a reconnect overtook. The restore pass was its only reader, so its + /// spinner stayed until the search was cleared. + private func readOpenDetailRows(under parent: DatabaseTreeNode) { + guard showsTableDetails, let outlineView = self.outlineView else { return } + for node in resolvedChildren(of: parent) where outlineView.isItemExpanded(node) { + switch node.kind { + case .table, .partition, .tableDetailGroup: + triggerLoad(for: node) + readOpenDetailRows(under: node) + case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + .database, .schema, .tableDetail, .routine, .trigger, .userType, .status, .objectKindSection, + .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: + continue + } + } + } + private func expandableTableRef(of node: DatabaseTreeNode) -> DatabaseTreeTableRef? { switch node.kind { case .table(let ref): diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift index b19078ccb9..ba43165ae1 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift @@ -436,6 +436,44 @@ struct DatabaseTreeTableDetailOutlineTests { await tearDown(fixture) } + @Test("While a search runs, an open group still reads a list a reconnect overtook") + func openGroupRereadsDuringSearch() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture) + let columns = group(fixture, .columns) + fixture.windowState.expandedTreeTables = [DatabaseTableKey(orders(fixture))] + fixture.windowState.expandedTreeTableDetailGroups = [columns.expansionKey] + reloadFlat(fixture, table: table) + try await waitUntil { detailState(fixture, .columns).value != nil } + + fixture.coordinator.searchText = "orders" + await service.handleReconnect(connectionId: fixture.connection.id) + reloadFlat(fixture, table: table) + try await waitUntil { fixture.driver.detailReads.count == 2 } + + #expect(fixture.outlineView.isItemExpanded(table)) + #expect(fixture.outlineView.isItemExpanded(node(fixture, columns))) + #expect(fixture.driver.detailReads == ["columns:orders", "columns:orders"]) + await tearDown(fixture) + } + + @Test("A search opens no table the window recorded open, so it reads no group") + func searchOpensNoRecordedTable() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture) + let columns = group(fixture, .columns) + fixture.windowState.expandedTreeTables = [DatabaseTableKey(orders(fixture))] + fixture.windowState.expandedTreeTableDetailGroups = [columns.expansionKey] + fixture.coordinator.searchText = "orders" + + reloadFlat(fixture, table: table) + + #expect(!fixture.outlineView.isItemExpanded(table)) + #expect(!fixture.outlineView.isItemExpanded(node(fixture, columns))) + #expect(detailState(fixture, .columns) == .idle) + await tearDown(fixture) + } + @Test("A detail list landing changes what the outline draws, and another connection's does not") func landingListMovesTheRenderInputs() async throws { let fixture = try makeFixture() From 40bdd3351277511f902e02665700bf274fdbe9c3 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:36:27 +0700 Subject: [PATCH 014/123] test(sidebar): pin the restore re-read of an open group and the older build's read of expansion Two gaps the branch's tests left open. In a real outline, a catalog change now has to read an open detail group again through the restore pass, and the group keeps its rows while that read runs. The wait is bounded, so a pass that stops reading fails the test rather than hanging it. A copy of the previous build's PersistedExpansion, which has no tableDetailGroups field, decodes the blob this build writes with open groups in it, so the previous stable still reads the format. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ViewModels/WindowSidebarStateTests.swift | 39 +++++++++++++++++++ .../DatabaseTreeTableDetailOutlineTests.swift | 37 ++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift b/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift index 25bcb5f74a..d8a7e25548 100644 --- a/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift +++ b/apple/TableProTests/ViewModels/WindowSidebarStateTests.swift @@ -258,6 +258,45 @@ struct WindowSidebarStateTests { /// A later build may add a group this one has never heard of. Reading it must not throw away the /// rest of the blob, the rule `unknownObjectKindKeepsOtherExpansion` pins for object kinds. + /// `PersistedExpansion` as the build before Table Details declares it, copied from that build. + private struct PreviousPersistedExpansion: Decodable { + struct ObjectGroup: Decodable { + let database: String + let schema: String? + let kind: String + let expanded: Bool + } + + var schemas: [String] + var databases: [String] + var databaseSchemas: [DatabaseSchemaKey] + var tables: [DatabaseTableKey]? + var objectGroups: [ObjectGroup]? + var seeded: Bool? + var collapsedFolders: [UUID]? + } + + /// Sparkle never downgrades, but a beta user can turn betas off, so the previous stable reads + /// what this build writes. + @Test("The build before table details still reads expansion that holds open groups") + func previousBuildReadsExpansionWithDetailGroups() throws { + let defaults = try makeDefaults() + let connectionId = UUID() + let orders = DatabaseTableKey(database: "shop", schema: "public", table: "orders") + let state = WindowSidebarState(connectionId: connectionId, defaults: defaults) + state.expandedTreeDatabases.insert("shop") + state.expandedTreeTables.insert(orders) + state.expandedTreeTableDetailGroups = [DatabaseTableDetailGroupKey(table: orders, group: .columns)] + + let data = try #require(defaults.data(forKey: "com.TablePro.sidebar.treeExpansion.\(connectionId.uuidString)")) + let written = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + let previous = try JSONDecoder().decode(PreviousPersistedExpansion.self, from: data) + + #expect(written["tableDetailGroups"] != nil) + #expect(previous.databases == ["shop"]) + #expect(previous.tables == [orders]) + } + @Test("An unrecognized detail group does not discard the rest of the expansion") func unknownDetailGroupKeepsOtherExpansion() throws { let defaults = try makeDefaults() diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift index ba43165ae1..3288454f50 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeTableDetailOutlineTests.swift @@ -1,7 +1,9 @@ import AppKit import Foundation +import os @testable import TablePro import TableProPluginKit +import TableProSQLGrammar import TableProTestSupport import Testing @@ -436,6 +438,41 @@ struct DatabaseTreeTableDetailOutlineTests { await tearDown(fixture) } + private func detailNames(_ rows: [DatabaseTreeNode]) -> [String] { + rows.compactMap { row -> String? in + guard case .tableDetail(let detail) = row.kind else { return nil } + return detail.item.name + } + } + + @Test("A catalog change reads an open group again on the restore pass, and its rows stay until the read lands") + func catalogChangeRereadsAnOpenGroupKeepingItsRows() async throws { + let fixture = try makeFixture() + let table = tableNode(fixture) + let columns = group(fixture, .columns) + let groupNode = node(fixture, columns) + fixture.windowState.expandedTreeTables = [DatabaseTableKey(orders(fixture))] + fixture.windowState.expandedTreeTableDetailGroups = [columns.expansionKey] + reloadFlat(fixture, table: table) + try await waitUntil { detailState(fixture, .columns).value != nil } + fixture.driver.columnsByTable["orders"] = [TestFixtures.makeColumnInfo(name: "id", dataType: "bigint")] + + await service.refreshCatalog(for: CatalogChange(connectionId: fixture.connection.id, kinds: .tables)) + let paused = OSAllocatedUnfairLock(initialState: false) + fixture.driver.onTableFetchPaused = { paused.withLock { $0 = true } } + fixture.driver.pausesNextTableFetch = true + reloadFlat(fixture, table: table) + try await waitUntil { paused.withLock { $0 } } + + #expect(detailNames(rebuiltChildren(fixture, of: groupNode)) == ["id", "total"]) + + fixture.driver.resumeTableFetch() + try await waitUntil { detailNames(rebuiltChildren(fixture, of: groupNode)) == ["id"] } + #expect(fixture.outlineView.isItemExpanded(groupNode)) + #expect(fixture.driver.detailReads == ["columns:orders", "columns:orders"]) + await tearDown(fixture) + } + @Test("While a search runs, an open group still reads a list a reconnect overtook") func openGroupRereadsDuringSearch() async throws { let fixture = try makeFixture() From a32cd0f009c57346a989b164c58506b9ef41bda0 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:26:03 +0700 Subject: [PATCH 015/123] feat(navigator): add the connection navigator setting and its visibility rule Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionWindowPaneResolver.swift | 20 ++++++++ .../Core/Storage/AppSettingsManager.swift | 3 +- .../Models/Settings/GeneralSettings.swift | 8 +++ .../Views/Settings/GeneralSettingsView.swift | 3 ++ .../ConnectionWindowPaneResolverTests.swift | 51 +++++++++++++++++++ .../ConnectionNavigatorSettingTests.swift | 42 +++++++++++++++ 6 files changed, 126 insertions(+), 1 deletion(-) create mode 100644 apple/TableProTests/Models/ConnectionNavigatorSettingTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift index c8123947c2..786e01ff21 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift @@ -127,4 +127,24 @@ internal enum ConnectionWindowPaneResolver { guard workspaceCount > 1, !isClosing else { return false } return preferenceEnabled || !pane.hasContent } + + /// Whether the column stands when it holds the navigator instead of the strip. + /// + /// The navigator lists every saved connection, not the ones the window has open, so it has + /// something to offer with one workspace or none, and the workspace count plays no part. The + /// preference still does: it is what View > Show Connections writes, and that command keeps + /// hiding and showing the column whichever list is in it. + internal static func showsConnectionNavigator( + preferenceEnabled: Bool, + navigatorEnabled: Bool, + isClosing: Bool + ) -> Bool { + navigatorEnabled && preferenceEnabled && !isClosing + } + + /// Show Connections only means something where the column can stand: always with the navigator, + /// and with the strip only once there is a second workspace to switch to. + internal static func canToggleConnectionsColumn(navigatorEnabled: Bool, workspaceCount: Int) -> Bool { + navigatorEnabled || workspaceCount > 1 + } } diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 47b3a24e27..d02610e76b 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -12,7 +12,8 @@ final class AppSettingsManager: ObservableObject { didSet { general.language.apply() storage.saveGeneral(general) - if oldValue.showWorkspaceRail != general.showWorkspaceRail { + if oldValue.showWorkspaceRail != general.showWorkspaceRail + || oldValue.showsConnectionNavigator != general.showsConnectionNavigator { appEvents.workspaceRailVisibilityChanged.send(()) } if oldValue.connectionHealthCheck != general.connectionHealthCheck { diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 41fb8679f1..0182a79ee7 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -68,6 +68,7 @@ struct GeneralSettings: Codable, Equatable { var showTableDetails: Bool var showWorkspaceRail: Bool var sidebarRowSize: SidebarRowSizePreference + var showsConnectionNavigator: Bool var connectionHealthCheck: ConnectionHealthCheck static let `default` = GeneralSettings( @@ -83,6 +84,7 @@ struct GeneralSettings: Codable, Equatable { showTableDetails: false, showWorkspaceRail: true, sidebarRowSize: .matchSystem, + showsConnectionNavigator: false, connectionHealthCheck: .every30Seconds ) @@ -99,6 +101,7 @@ struct GeneralSettings: Codable, Equatable { showTableDetails: Bool = false, showWorkspaceRail: Bool = true, sidebarRowSize: SidebarRowSizePreference = .matchSystem, + showsConnectionNavigator: Bool = false, connectionHealthCheck: ConnectionHealthCheck = .every30Seconds ) { self.startupBehavior = startupBehavior @@ -113,6 +116,7 @@ struct GeneralSettings: Codable, Equatable { self.showTableDetails = showTableDetails self.showWorkspaceRail = showWorkspaceRail self.sidebarRowSize = sidebarRowSize + self.showsConnectionNavigator = showsConnectionNavigator self.connectionHealthCheck = connectionHealthCheck } @@ -131,6 +135,10 @@ struct GeneralSettings: Codable, Equatable { showTableDetails = container.decodeSetting(.showTableDetails, default: fallback.showTableDetails) showWorkspaceRail = container.decodeSetting(.showWorkspaceRail, default: fallback.showWorkspaceRail) sidebarRowSize = container.decodeSetting(.sidebarRowSize, default: fallback.sidebarRowSize) + showsConnectionNavigator = container.decodeSetting( + .showsConnectionNavigator, + default: fallback.showsConnectionNavigator + ) connectionHealthCheck = container.decodeSetting(.connectionHealthCheck, default: fallback.connectionHealthCheck) } } diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index d66319fbf1..3da21219a9 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -64,6 +64,9 @@ struct GeneralSettingsView: View { 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("List every saved connection beside the database tree", isOn: $settings.showsConnectionNavigator) + .help("Turns the connections column into a list of every saved connection, in its groups. Double-click one to open 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.") diff --git a/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift index 705262e897..7afde59950 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift @@ -134,6 +134,57 @@ struct ConnectionWindowPaneResolverTests { } } + // MARK: - Navigator + + /// The navigator lists saved connections, not open ones, so a window with one connection still + /// has the others to offer. + @Test("The navigator stands with any workspace count") + func navigatorStandsWithAnyWorkspaceCount() { + #expect(ConnectionWindowPaneResolver.showsConnectionNavigator( + preferenceEnabled: true, + navigatorEnabled: true, + isClosing: false + )) + } + + @Test("A closing window is given no navigator") + func navigatorHidesWhileClosing() { + #expect(!ConnectionWindowPaneResolver.showsConnectionNavigator( + preferenceEnabled: true, + navigatorEnabled: true, + isClosing: true + )) + } + + @Test("Hide Connections hides the navigator") + func showConnectionsHidesTheNavigator() { + #expect(!ConnectionWindowPaneResolver.showsConnectionNavigator( + preferenceEnabled: false, + navigatorEnabled: true, + isClosing: false + )) + } + + @Test("With the setting off the navigator never stands") + func navigatorOffNeverStands() { + for preference in [true, false] { + for closing in [true, false] { + #expect(!ConnectionWindowPaneResolver.showsConnectionNavigator( + preferenceEnabled: preference, + navigatorEnabled: false, + isClosing: closing + )) + } + } + } + + @Test("The navigator lets Show Connections act on a window with one workspace") + func navigatorOpensTheToggleToOneWorkspace() { + #expect(ConnectionWindowPaneResolver.canToggleConnectionsColumn(navigatorEnabled: true, workspaceCount: 1)) + #expect(!ConnectionWindowPaneResolver.canToggleConnectionsColumn(navigatorEnabled: false, workspaceCount: 1)) + #expect(ConnectionWindowPaneResolver.canToggleConnectionsColumn(navigatorEnabled: false, workspaceCount: 2)) + } + // MARK: - Dialling /// There is no timer in here any more. A connect reports itself from the moment it starts, and diff --git a/apple/TableProTests/Models/ConnectionNavigatorSettingTests.swift b/apple/TableProTests/Models/ConnectionNavigatorSettingTests.swift new file mode 100644 index 0000000000..5b0ebf34c4 --- /dev/null +++ b/apple/TableProTests/Models/ConnectionNavigatorSettingTests.swift @@ -0,0 +1,42 @@ +// +// ConnectionNavigatorSettingTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct ConnectionNavigatorSettingTests { + private static func encoded(_ settings: GeneralSettings) throws -> [String: Any] { + let data = try JSONEncoder().encode(settings) + return try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private static func decoded(_ object: [String: Any]) throws -> GeneralSettings { + try JSONDecoder().decode(GeneralSettings.self, from: JSONSerialization.data(withJSONObject: object)) + } + + @Test("The navigator starts off") + func startsOff() { + #expect(GeneralSettings.default.showsConnectionNavigator == false) + #expect(GeneralSettings().showsConnectionNavigator == false) + } + + @Test("Settings saved before the navigator existed decode with it off") + func missingKeyDecodesOff() throws { + let decoded = try Self.decoded(["startupBehavior": "showWelcome"]) + #expect(decoded.showsConnectionNavigator == false) + } + + @Test("Turning the navigator on survives a round trip and leaves the strip setting alone") + func roundTripsOn() throws { + var object = try Self.encoded(.default) + object["showsConnectionNavigator"] = true + + let decoded = try Self.decoded(object) + + #expect(decoded.showsConnectionNavigator) + #expect(decoded.showWorkspaceRail) + } +} From 7a1bc3c7d724f0819a34b47fdcc0d4f8c8323bf4 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:50:53 +0700 Subject: [PATCH 016/123] feat(navigator): remember which navigator groups are expanded Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 1 + .../ConnectionNavigatorExpansionStore.swift | 30 +++++++++++ ...nnectionNavigatorExpansionStoreTests.swift | 50 +++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 apple/TablePro/Core/Storage/ConnectionNavigatorExpansionStore.swift create mode 100644 apple/TableProTests/Core/Storage/ConnectionNavigatorExpansionStoreTests.swift diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index abd611cd4e..71e2e33109 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -167,6 +167,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Favorite tables (iCloud-synced) | UserDefaults | `FavoriteTablesStorage` | | Team library, per team: pull cursor, items, unpushed edits, conflicts (synced with tablepro-cloud's `/v2`, never iCloud) | JSON, one file per team | `TeamLibraryStateStore` through `TeamLibrarySync` | | Sidebar database and schema filters, recent tables | UserDefaults, device-local | `DatabaseTreeFilterStorage`, `RecentTablesStore` | +| Connection navigator group expansion | UserDefaults `com.TablePro.navigator.groupExpansion`, device-local, never synced | `ConnectionNavigatorExpansionStore` | | History drawer state | UserDefaults, device-local | `HistoryPanelPreferencesStorage` | | Server Dashboard tiles, per connection | UserDefaults, device-local | `ServerDashboardTileStorage` | | Module on/off (Settings > Extensions) | UserDefaults, device-local, never synced | `AppModuleSettings` | diff --git a/apple/TablePro/Core/Storage/ConnectionNavigatorExpansionStore.swift b/apple/TablePro/Core/Storage/ConnectionNavigatorExpansionStore.swift new file mode 100644 index 0000000000..f4b42aac2b --- /dev/null +++ b/apple/TablePro/Core/Storage/ConnectionNavigatorExpansionStore.swift @@ -0,0 +1,30 @@ +// +// ConnectionNavigatorExpansionStore.swift +// TablePro +// + +import Foundation + +/// Which navigator groups are open, kept apart from the Welcome window's set: the two lists are +/// opened and closed for different reasons, and a narrow column wants fewer groups open. +/// Device-local and never synced, like every other piece of list chrome. +internal struct ConnectionNavigatorExpansionStore { + internal static let key = "com.TablePro.navigator.groupExpansion" + + private let defaults: UserDefaults + + internal init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { + self.defaults = defaults + } + + /// A group deleted here or on another Mac leaves its id behind, and nothing could ever reopen + /// it, so it is dropped on the way in. + internal func load(keeping groupIds: Set) -> Set { + let stored = defaults.stringArray(forKey: Self.key) ?? [] + return Set(stored.compactMap(UUID.init(uuidString:))).intersection(groupIds) + } + + internal func save(_ ids: Set) { + defaults.set(ids.map(\.uuidString), forKey: Self.key) + } +} diff --git a/apple/TableProTests/Core/Storage/ConnectionNavigatorExpansionStoreTests.swift b/apple/TableProTests/Core/Storage/ConnectionNavigatorExpansionStoreTests.swift new file mode 100644 index 0000000000..2baed65937 --- /dev/null +++ b/apple/TableProTests/Core/Storage/ConnectionNavigatorExpansionStoreTests.swift @@ -0,0 +1,50 @@ +// +// ConnectionNavigatorExpansionStoreTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct ConnectionNavigatorExpansionStoreTests { + private let suite: EphemeralDefaults + private let store: ConnectionNavigatorExpansionStore + + init() throws { + suite = try EphemeralDefaults() + store = ConnectionNavigatorExpansionStore(defaults: suite.defaults) + } + + @Test("Expanded groups come back as they were saved") + func roundTrips() { + let first = UUID() + let second = UUID() + store.save([first, second]) + + #expect(store.load(keeping: [first, second, UUID()]) == [first, second]) + } + + @Test("A group that no longer exists is dropped on load") + func dropsUnknownGroups() { + let kept = UUID() + store.save([kept, UUID()]) + + #expect(store.load(keeping: [kept]) == [kept]) + } + + @Test("Nothing saved reads as every group collapsed") + func missingKeyReadsEmpty() { + #expect(store.load(keeping: [UUID()]).isEmpty) + } + + @Test("The set is stored under the navigator's own key") + func writesItsOwnKey() throws { + let first = UUID() + let second = UUID() + store.save([first, second]) + + let stored = try #require(suite.defaults.stringArray(forKey: "com.TablePro.navigator.groupExpansion")) + #expect(Set(stored) == [first.uuidString, second.uuidString]) + } +} From f415bc37875125361d8288474809ebcd3487cc50 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:50:53 +0700 Subject: [PATCH 017/123] feat(navigator): build navigator rows from the connection library Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorRow.swift | 63 +++++ .../ConnectionNavigatorRowsBuilder.swift | 114 ++++++++ .../ConnectionNavigatorRowsBuilderTests.swift | 245 ++++++++++++++++++ 3 files changed, 422 insertions(+) create mode 100644 apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift create mode 100644 apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilder.swift create mode 100644 apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilderTests.swift diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift new file mode 100644 index 0000000000..fc66dd6a65 --- /dev/null +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift @@ -0,0 +1,63 @@ +// +// ConnectionNavigatorRow.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary + +/// A navigator row's identity. A connection appears once, in its own group, so its id alone names +/// its row; Favorites and Recent, where the Welcome list repeats a connection, are not shown here. +internal enum ConnectionNavigatorRowID: Hashable, Sendable { + case group(UUID) + case connection(UUID) +} + +/// Where a connection stands relative to the window drawing the navigator, which decides what a +/// click does and what the row is marked with. +internal enum ConnectionNavigatorPlacement: Equatable, Sendable { + case shownHere + case openHere + case openElsewhere + case notOpen +} + +internal struct ConnectionNavigatorGroupRow: Equatable { + internal let id: UUID + internal let name: String + internal let color: ConnectionColor + internal let iconName: String? + internal let connectionCount: Int + /// A collapsed group keeps its children, so the outline can open it without a rebuild. + internal let isExpanded: Bool + internal let children: [ConnectionNavigatorRow] +} + +internal struct ConnectionNavigatorConnectionRow: Equatable { + internal let connection: DatabaseConnection + internal let groupPath: [String] + internal let isDriverRejected: Bool + internal var status: ConnectionDisplayStatus + internal var placement: ConnectionNavigatorPlacement + + internal var id: UUID { connection.id } +} + +internal enum ConnectionNavigatorRow: Equatable { + case group(ConnectionNavigatorGroupRow) + case connection(ConnectionNavigatorConnectionRow) + + internal var id: ConnectionNavigatorRowID { + switch self { + case .group(let group): return .group(group.id) + case .connection(let connection): return .connection(connection.id) + } + } + + internal var children: [ConnectionNavigatorRow] { + switch self { + case .group(let group): return group.children + case .connection: return [] + } + } +} diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilder.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilder.swift new file mode 100644 index 0000000000..c25cd77d49 --- /dev/null +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilder.swift @@ -0,0 +1,114 @@ +// +// ConnectionNavigatorRowsBuilder.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary + +/// Everything a navigator row depends on, read once by the model so the build itself touches no +/// session, window or plugin state. +internal struct ConnectionNavigatorRowsInput { + internal var connections: [DatabaseConnection] + internal var groups: [ConnectionGroup] + internal var sortMode: LibrarySortMode = .manual + internal var lastConnected: [UUID: Date] = [:] + internal var filterText = "" + internal var expandedGroupIds: Set = [] + internal var statuses: [UUID: ConnectionDisplayStatus] = [:] + internal var placements: [UUID: ConnectionNavigatorPlacement] = [:] + internal var driverRejectedIds: Set = [] +} + +/// The Welcome window's outline, cut down to the Connections section: grouping, sorting and the +/// filter come from `LibraryOutlineBuilder`, so both lists agree on where a connection sits. +internal enum ConnectionNavigatorRowsBuilder { + nonisolated internal static func build(_ input: ConnectionNavigatorRowsInput) -> [ConnectionNavigatorRow] { + let request = LibraryOutlineRequest( + connections: input.connections, + groups: input.groups, + tags: [ConnectionTag](), + sortMode: input.sortMode, + query: LibraryQuery(text: input.filterText), + lastConnected: input.lastConnected, + includesFavorites: false, + includesRecent: false + ) + let outline = LibraryOutlineBuilder.build(request) + guard let nodes = outline.section(.connections)?.nodes else { return [] } + + let graph = LibraryGroupGraph(groups: input.groups) + let connectionsById = Dictionary(input.connections.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + let groupsById = Dictionary(input.groups.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + /// While a filter runs, the groups it opened are the ones that hold a match; the user's own + /// choice comes back with the filter cleared, because nothing here overwrote it. + let expanded = outline.isQueryActive ? outline.groupIdsExpandedByQuery : input.expandedGroupIds + + func row(for node: LibraryNode) -> ConnectionNavigatorRow? { + switch node { + case .group(let id, let children, let count): + guard let group = groupsById[id] else { return nil } + return .group(ConnectionNavigatorGroupRow( + id: id, + name: group.name, + color: group.color, + iconName: group.iconName, + connectionCount: count, + isExpanded: expanded.contains(id), + children: children.compactMap(row(for:)) + )) + case .connection(let id): + guard let connection = connectionsById[id] else { return nil } + let groupPath = connection.groupId.flatMap { graph.contains($0) ? graph.pathNames(to: $0) : nil } ?? [] + return .connection(ConnectionNavigatorConnectionRow( + connection: connection, + groupPath: groupPath, + isDriverRejected: input.driverRejectedIds.contains(id), + status: input.statuses[id] ?? .notConnected, + placement: input.placements[id] ?? .notOpen + )) + } + } + return nodes.compactMap(row(for:)) + } + + /// A status or a window moved, which changes how a row is marked and never which rows exist. + nonisolated internal static func applying( + statuses: [UUID: ConnectionDisplayStatus], + placements: [UUID: ConnectionNavigatorPlacement], + to rows: [ConnectionNavigatorRow] + ) -> [ConnectionNavigatorRow] { + rows.map { row in + switch row { + case .group(let group): + return .group(ConnectionNavigatorGroupRow( + id: group.id, + name: group.name, + color: group.color, + iconName: group.iconName, + connectionCount: group.connectionCount, + isExpanded: group.isExpanded, + children: applying(statuses: statuses, placements: placements, to: group.children) + )) + case .connection(var connection): + connection.status = statuses[connection.id] ?? .notConnected + connection.placement = placements[connection.id] ?? .notOpen + return .connection(connection) + } + } + } + + /// A connection hosted both here and by a window a tab was torn off into is this window's: a + /// click here switches to it, which is the answer that does not leave the window. + nonisolated internal static func placement( + of id: UUID, + shown: UUID?, + hostedHere: Set, + hostedAnywhere: Set + ) -> ConnectionNavigatorPlacement { + if id == shown { return .shownHere } + if hostedHere.contains(id) { return .openHere } + if hostedAnywhere.contains(id) { return .openElsewhere } + return .notOpen + } +} diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilderTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilderTests.swift new file mode 100644 index 0000000000..6d1298da41 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorRowsBuilderTests.swift @@ -0,0 +1,245 @@ +// +// ConnectionNavigatorRowsBuilderTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import Testing + +struct ConnectionNavigatorRowsBuilderTests { + private static func connection( + _ name: String, + host: String = "localhost", + in groupId: UUID? = nil, + sortOrder: Int = 0 + ) -> DatabaseConnection { + DatabaseConnection(name: name, host: host, groupId: groupId, sortOrder: sortOrder) + } + + private static func group(_ name: String, parent: UUID? = nil, sortOrder: Int = 0) -> ConnectionGroup { + ConnectionGroup(name: name, parentId: parent, sortOrder: sortOrder) + } + + /// Depth first, the order the outline draws them in when every group is open. + private static func ids(_ rows: [ConnectionNavigatorRow]) -> [ConnectionNavigatorRowID] { + rows.flatMap { [$0.id] + ids($0.children) } + } + + private static func groupRow(_ id: UUID, in rows: [ConnectionNavigatorRow]) -> ConnectionNavigatorGroupRow? { + for row in rows { + if case .group(let group) = row { + if group.id == id { return group } + if let nested = groupRow(id, in: group.children) { return nested } + } + } + return nil + } + + private static func connectionRow(_ id: UUID, in rows: [ConnectionNavigatorRow]) -> ConnectionNavigatorConnectionRow? { + for row in rows { + switch row { + case .connection(let connection) where connection.id == id: + return connection + case .connection: + continue + case .group(let group): + if let nested = connectionRow(id, in: group.children) { return nested } + } + } + return nil + } + + @Test("Groups nest under their parent and keep the user's order") + func groupsNestByParentAndSortOrder() throws { + let groupA = Self.group("A", sortOrder: 1) + let groupB = Self.group("B", sortOrder: 0) + let groupC = Self.group("C", parent: groupA.id) + let inA = Self.connection("a1", in: groupA.id) + let inC = Self.connection("c1", in: groupC.id) + let loose = Self.connection("u1") + + let rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: [loose, inC, inA], + groups: [groupA, groupB, groupC] + )) + + #expect(Self.ids(rows) == [ + .group(groupB.id), .group(groupA.id), .group(groupC.id), + .connection(inC.id), .connection(inA.id), .connection(loose.id), + ]) + #expect(try #require(Self.groupRow(groupA.id, in: rows)).connectionCount == 2) + } + + @Test("Name sort orders groups and connections by name") + func nameSortOrdersByName() { + let beta = Self.group("Beta", sortOrder: 0) + let alpha = Self.group("Alpha", sortOrder: 1) + let second = Self.connection("b", sortOrder: 0) + let first = Self.connection("a", sortOrder: 1) + + let rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: [second, first], + groups: [beta, alpha], + sortMode: .name + )) + + #expect(Self.ids(rows) == [.group(alpha.id), .group(beta.id), .connection(first.id), .connection(second.id)]) + } + + @Test("The filter matches names, hosts and group names, and opens the groups holding a match") + func filterMatchesNameHostAndGroupAndExpands() throws { + let production = Self.group("Production") + let analytics = Self.group("Analytics") + let byHost = Self.connection("orders", host: "prod-db.internal", in: production.id) + let other = Self.connection("billing", in: production.id) + let reports = Self.connection("reports", in: analytics.id) + let warehouse = Self.connection("warehouse", in: analytics.id) + let input = ConnectionNavigatorRowsInput( + connections: [byHost, other, reports, warehouse], + groups: [production, analytics] + ) + + var hostFilter = input + hostFilter.filterText = "prod-db" + let hostRows = ConnectionNavigatorRowsBuilder.build(hostFilter) + let matchedGroup = try #require(Self.groupRow(production.id, in: hostRows)) + #expect(matchedGroup.isExpanded) + #expect(Self.ids(matchedGroup.children) == [.connection(byHost.id)]) + #expect(Self.groupRow(analytics.id, in: hostRows) == nil) + + var groupFilter = input + groupFilter.filterText = "analytics" + let groupRows = ConnectionNavigatorRowsBuilder.build(groupFilter) + let namedGroup = try #require(Self.groupRow(analytics.id, in: groupRows)) + #expect(Set(Self.ids(namedGroup.children)) == [.connection(reports.id), .connection(warehouse.id)]) + + var nameFilter = input + nameFilter.filterText = "billing" + #expect(Self.connectionRow(other.id, in: ConnectionNavigatorRowsBuilder.build(nameFilter)) != nil) + } + + @Test("A collapsed group is marked collapsed and still carries its children") + func collapsedGroupIsMarkedCollapsed() throws { + let open = Self.group("Open", sortOrder: 0) + let closed = Self.group("Closed", sortOrder: 1) + let inClosed = Self.connection("inside", in: closed.id) + + let rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: [inClosed], + groups: [open, closed], + expandedGroupIds: [open.id] + )) + + #expect(try #require(Self.groupRow(open.id, in: rows)).isExpanded) + let collapsed = try #require(Self.groupRow(closed.id, in: rows)) + #expect(!collapsed.isExpanded) + #expect(Self.ids(collapsed.children) == [.connection(inClosed.id)]) + } + + @Test("An empty library, and a filter that matches nothing, build no rows") + func emptyLibraryAndNoMatchBuildNothing() { + #expect(ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput(connections: [], groups: [])).isEmpty) + + var input = ConnectionNavigatorRowsInput(connections: [Self.connection("orders")], groups: [Self.group("G")]) + input.filterText = "zzz" + #expect(ConnectionNavigatorRowsBuilder.build(input).isEmpty) + } + + @Test("Status, placement and a rejected driver come from the input, with quiet defaults") + func statusPlacementAndDriverComeFromInput() throws { + let marked = Self.connection("marked") + let plain = Self.connection("plain") + + let rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: [marked, plain], + groups: [], + statuses: [marked.id: .connecting], + placements: [marked.id: .openElsewhere], + driverRejectedIds: [marked.id] + )) + + let markedRow = try #require(Self.connectionRow(marked.id, in: rows)) + #expect(markedRow.status == .connecting) + #expect(markedRow.placement == .openElsewhere) + #expect(markedRow.isDriverRejected) + let plainRow = try #require(Self.connectionRow(plain.id, in: rows)) + #expect(plainRow.status == .notConnected) + #expect(plainRow.placement == .notOpen) + #expect(!plainRow.isDriverRejected) + } + + @Test("Applying new statuses changes only status and placement") + func applyingReplacesOnlyStatusAndPlacement() throws { + let group = Self.group("G") + let nested = Self.connection("nested", in: group.id) + let rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: [nested], + groups: [group], + expandedGroupIds: [group.id] + )) + + let updated = ConnectionNavigatorRowsBuilder.applying( + statuses: [nested.id: .connected], + placements: [nested.id: .shownHere], + to: rows + ) + + #expect(Self.ids(updated) == Self.ids(rows)) + #expect(try #require(Self.groupRow(group.id, in: updated)).isExpanded) + let row = try #require(Self.connectionRow(nested.id, in: updated)) + #expect(row.status == .connected) + #expect(row.placement == .shownHere) + } + + @Test("A connection's placement follows the window that shows it") + func placementOrder() { + let shown = UUID() + let hosted = UUID() + let elsewhere = UUID() + let closed = UUID() + let hostedHere: Set = [shown, hosted] + let hostedAnywhere: Set = [shown, hosted, elsewhere] + + func placement(_ id: UUID) -> ConnectionNavigatorPlacement { + ConnectionNavigatorRowsBuilder.placement( + of: id, shown: shown, hostedHere: hostedHere, hostedAnywhere: hostedAnywhere + ) + } + + #expect(placement(shown) == .shownHere) + #expect(placement(hosted) == .openHere) + #expect(placement(elsewhere) == .openElsewhere) + #expect(placement(closed) == .notOpen) + } + + /// Another Mac can delete a parent group while this one still holds its child. + @Test("A group whose parent is gone shows at the top level with its connections") + func orphanGroupShowsAtTopLevel() throws { + let orphan = Self.group("Orphan", parent: UUID()) + let inside = Self.connection("inside", in: orphan.id) + + let rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: [inside], + groups: [orphan] + )) + + #expect(rows.map { $0.id } == [.group(orphan.id)]) + #expect(Self.ids(try #require(Self.groupRow(orphan.id, in: rows)).children) == [.connection(inside.id)]) + } + + @Test("A filter of only spaces is no filter") + func blankFilterIsNoFilter() throws { + let group = Self.group("G") + let inside = Self.connection("inside", in: group.id) + var input = ConnectionNavigatorRowsInput(connections: [inside], groups: [group]) + input.filterText = " " + + let rows = ConnectionNavigatorRowsBuilder.build(input) + + let row = try #require(Self.groupRow(group.id, in: rows)) + #expect(!row.isExpanded) + #expect(Self.ids(row.children) == [.connection(inside.id)]) + } +} From 1f5910e655d7fb9501d1a55e808c2d55c010644f Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:50:53 +0700 Subject: [PATCH 018/123] feat(navigator): describe the navigator context menu Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorMenu.swift | 128 ++++++++++++++++++ .../ConnectionNavigatorMenuTests.swift | 127 +++++++++++++++++ 2 files changed, 255 insertions(+) create mode 100644 apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorMenu.swift create mode 100644 apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorMenuTests.swift diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorMenu.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorMenu.swift new file mode 100644 index 0000000000..cccfb5e307 --- /dev/null +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorMenu.swift @@ -0,0 +1,128 @@ +// +// ConnectionNavigatorMenu.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary + +/// What the navigator's context menu can do. Reordering and deleting stay in the Welcome window, +/// which owns the library's organization; the navigator only opens and edits. +internal enum ConnectionNavigatorCommand: Equatable { + case switchTo(UUID) + case open(UUID) + case openInNewWindow(UUID) + case disconnect(UUID) + case edit(UUID) + case duplicate(UUID) + case newConnection + case newGroup(parentId: UUID?) +} + +extension ConnectionNavigatorCommand: SidebarMenuShortcutProviding { + internal var shortcutAction: ShortcutAction? { + guard case .newConnection = self else { return nil } + return .newConnection + } +} + +internal typealias ConnectionNavigatorMenuItem = SidebarMenuItem +internal typealias ConnectionNavigatorMenuSection = SidebarMenuSection + +internal struct ConnectionNavigatorMenuConnection: Equatable { + internal let id: UUID + internal let placement: ConnectionNavigatorPlacement + internal let status: ConnectionDisplayStatus + internal let holdsSession: Bool + internal let canMoveToNewWindow: Bool +} + +internal enum ConnectionNavigatorMenuTarget: Equatable { + case connection(ConnectionNavigatorMenuConnection) + case group(UUID) + case empty +} + +/// A context menu shows only what applies to its row, as the strip's and Welcome's do, so a command +/// that would do nothing is left out rather than dimmed (`ConnectionMenuPolicy`). +internal enum ConnectionNavigatorMenu { + internal static func sections(for target: ConnectionNavigatorMenuTarget) -> [ConnectionNavigatorMenuSection] { + switch target { + case .group(let groupId): + return [creationSection(parentId: groupId)] + case .empty: + return [creationSection(parentId: nil)] + case .connection(let connection): + return [ + openSection(for: connection), + ConnectionNavigatorMenuSection([ + .command(Titles.editConnection, .edit(connection.id)), + .command(Titles.duplicate, .duplicate(connection.id)), + ]), + creationSection(parentId: nil), + ].nonEmptySections() + } + } + + private static func openSection(for connection: ConnectionNavigatorMenuConnection) -> ConnectionNavigatorMenuSection { + var items: [ConnectionNavigatorMenuItem] = [] + if let primary = primaryItem(for: connection) { + items.append(primary) + } + if offersNewWindow(connection) { + items.append(.command(Titles.openInNewWindow, .openInNewWindow(connection.id))) + } + if ConnectionMenuPolicy.showsDisconnect(status: connection.status, holdsSession: connection.holdsSession) { + items.append(.command(Titles.disconnect, .disconnect(connection.id))) + } + return ConnectionNavigatorMenuSection(items) + } + + /// The connection on screen needs no way to get to it. One open here is a switch, one open in + /// another window raises that window, and one nobody shows dials unless a session already runs. + private static func primaryItem(for connection: ConnectionNavigatorMenuConnection) -> ConnectionNavigatorMenuItem? { + switch connection.placement { + case .shownHere: + return nil + case .openHere: + return .command(Titles.switchTo, .switchTo(connection.id)) + case .openElsewhere: + return .command(Titles.open, .open(connection.id)) + case .notOpen: + let title = connection.status == .connected ? Titles.open : Titles.connect + return .command(title, .open(connection.id)) + } + } + + /// A connection open elsewhere already has a window of its own, and one this window hosts can + /// only leave while it is not the window's last (`WindowManager.canMoveToNewWindow`). + private static func offersNewWindow(_ connection: ConnectionNavigatorMenuConnection) -> Bool { + switch connection.placement { + case .notOpen: + return true + case .shownHere, .openHere: + return connection.canMoveToNewWindow + case .openElsewhere: + return false + } + } + + private static func creationSection(parentId: UUID?) -> ConnectionNavigatorMenuSection { + ConnectionNavigatorMenuSection([ + .command(Titles.newConnection, .newConnection), + .command(Titles.newGroup, .newGroup(parentId: parentId)), + ]) + } + + internal enum Titles { + static var connect: String { String(localized: "Connect") } + static var open: String { String(localized: "Open") } + static var switchTo: String { String(localized: "Switch To") } + static var openInNewWindow: String { String(localized: "Open in New Window") } + static var disconnect: String { String(localized: "Disconnect") } + static var editConnection: String { String(localized: "Edit Connection…") } + static var duplicate: String { String(localized: "Duplicate") } + static var newConnection: String { String(localized: "New Connection…") } + static var newGroup: String { String(localized: "New Group…") } + } +} diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorMenuTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorMenuTests.swift new file mode 100644 index 0000000000..c2cba6d1fe --- /dev/null +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorMenuTests.swift @@ -0,0 +1,127 @@ +// +// ConnectionNavigatorMenuTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import Testing + +struct ConnectionNavigatorMenuTests { + private let id = UUID() + + private func target( + _ placement: ConnectionNavigatorPlacement, + status: ConnectionDisplayStatus, + holdsSession: Bool, + canMoveToNewWindow: Bool = false + ) -> ConnectionNavigatorMenuTarget { + .connection(ConnectionNavigatorMenuConnection( + id: id, + placement: placement, + status: status, + holdsSession: holdsSession, + canMoveToNewWindow: canMoveToNewWindow + )) + } + + private static func titles(_ sections: [ConnectionNavigatorMenuSection]) -> [[String]] { + sections.map { section in + section.items.map { item in + switch item { + case .command(let entry): return entry.title + case .submenu(let title, _): return title + } + } + } + } + + private static func commands(_ sections: [ConnectionNavigatorMenuSection]) -> [ConnectionNavigatorCommand] { + sections.flatMap { section in + section.items.compactMap { item in + guard case .command(let entry) = item else { return nil } + return entry.command + } + } + } + + @Test("A connected connection this window shows offers a new window, Disconnect and editing") + func connectedAndShownHere() { + let sections = ConnectionNavigatorMenu.sections( + for: target(.shownHere, status: .connected, holdsSession: true, canMoveToNewWindow: true) + ) + + #expect(Self.titles(sections) == [ + ["Open in New Window", "Disconnect"], + ["Edit Connection…", "Duplicate"], + ["New Connection…", "New Group…"], + ]) + #expect(Self.commands(sections) == [ + .openInNewWindow(id), .disconnect(id), .edit(id), .duplicate(id), .newConnection, .newGroup(parentId: nil), + ]) + } + + @Test("A connection nobody has open offers Connect and a new window") + func notConnectedNotOpen() { + let sections = ConnectionNavigatorMenu.sections(for: target(.notOpen, status: .notConnected, holdsSession: false)) + + #expect(Self.titles(sections).first == ["Connect", "Open in New Window"]) + #expect(Array(Self.commands(sections).prefix(2)) == [.open(id), .openInNewWindow(id)]) + } + + @Test("A connected session no window shows reads Open") + func connectedButUnhostedReadsOpen() { + let sections = ConnectionNavigatorMenu.sections(for: target(.notOpen, status: .connected, holdsSession: true)) + + #expect(Self.titles(sections).first?.first == "Open") + #expect(Self.commands(sections).first == .open(id)) + } + + @Test("A connection this window hosts but does not show offers Switch To") + func openHereNotShown() { + let sections = ConnectionNavigatorMenu.sections(for: target(.openHere, status: .connected, holdsSession: true)) + + #expect(Self.titles(sections).first == ["Switch To", "Disconnect"]) + #expect(Self.commands(sections).first == .switchTo(id)) + } + + @Test("A connection open in another window offers Open and no new window") + func openElsewhere() { + let sections = ConnectionNavigatorMenu.sections( + for: target(.openElsewhere, status: .connected, holdsSession: true, canMoveToNewWindow: true) + ) + + #expect(Self.titles(sections).first == ["Open", "Disconnect"]) + #expect(!Self.commands(sections).contains(.openInNewWindow(id))) + } + + @Test("A group row creates a connection or a group inside it") + func groupRow() { + let groupId = UUID() + let sections = ConnectionNavigatorMenu.sections(for: .group(groupId)) + + #expect(Self.titles(sections) == [["New Connection…", "New Group…"]]) + #expect(Self.commands(sections) == [.newConnection, .newGroup(parentId: groupId)]) + } + + @Test("Empty space creates a connection or a top-level group") + func emptySpace() { + let sections = ConnectionNavigatorMenu.sections(for: .empty) + + #expect(Self.titles(sections) == [["New Connection…", "New Group…"]]) + #expect(Self.commands(sections) == [.newConnection, .newGroup(parentId: nil)]) + } + + @Test("Only New Connection carries a menu bar shortcut") + func newConnectionShowsItsShortcut() { + let others: [ConnectionNavigatorCommand] = [ + .switchTo(id), .open(id), .openInNewWindow(id), .disconnect(id), .edit(id), .duplicate(id), + .newGroup(parentId: nil), + ] + #expect(ConnectionNavigatorCommand.newConnection.shortcutAction == .newConnection) + for command in others { + #expect(command.shortcutAction == nil) + } + } +} From d8ce54566cced5656fda7600700d686a7e28eaca Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:50:53 +0700 Subject: [PATCH 019/123] feat(navigator): add the navigator model with its events and routes Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorModel.swift | 323 ++++++++++++++++++ .../ConnectionNavigatorFixture.swift | 116 +++++++ .../ConnectionNavigatorInteractionTests.swift | 65 ++++ .../ConnectionNavigatorModelTests.swift | 131 +++++++ 4 files changed, 635 insertions(+) create mode 100644 apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift create mode 100644 apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorFixture.swift create mode 100644 apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorInteractionTests.swift create mode 100644 apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift new file mode 100644 index 0000000000..5dd51814ea --- /dev/null +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift @@ -0,0 +1,323 @@ +// +// ConnectionNavigatorModel.swift +// TablePro +// + +import AppKit +import Combine +import Foundation +import os +import TableProConnectionLibrary + +/// How the navigator opens a connection. The router picks the window, so the navigator never adopts +/// a workspace itself and never hosts a connection twice. +@MainActor +internal protocol ConnectionNavigatorRouting: AnyObject { + func route(_ intent: LaunchIntent) async throws + func openConnectionPreferringNewWindow(id: UUID) async throws +} + +extension TabRouter: ConnectionNavigatorRouting {} + +/// What the navigator reads from the rest of the app, gathered so a test can hand it a library of +/// its own, its own events and a router that records instead of opening windows. +@MainActor +internal struct ConnectionNavigatorEnvironment { + internal var appEvents: AppEvents = .shared + internal var connectionStorage: ConnectionStorage = .shared + internal var groupStorage: GroupStorage = .shared + internal var listPreferences: ConnectionListPreferences = .shared + internal var recentConnections: RecentConnectionsStore = .shared + internal var expansionStore = ConnectionNavigatorExpansionStore() + internal var router: any ConnectionNavigatorRouting = TabRouter.shared + internal var status: (UUID) -> ConnectionDisplayStatus = { ConnectionStatusResolver.status(for: $0) } + internal var holdsSession: (UUID) -> Bool = { DatabaseManager.shared.session(for: $0) != nil } + internal var hostedConnectionIds: () -> Set = { WindowManager.shared.allConnectionIds() } + internal var canMoveToNewWindow: (UUID) -> Bool = { WindowManager.shared.canMoveToNewWindow(connectionId: $0) } + internal var isDriverRejected: (DatabaseConnection) -> Bool = { connection in + let typeId = connection.type.pluginTypeId + return PluginManager.shared.rejectedPlugins.contains { $0.providedDatabaseTypeIds.contains(typeId) } + } +} + +/// The navigator's rows and what a click on one does. +/// +/// The rows are built from storage on every library change, never patched from a cache of it, the +/// same rule the Welcome list keeps (`.claude/rules/welcome-library.md`). A status or a window +/// moving only re-marks the rows it touches, so a connect in progress does not rebuild the list. +@MainActor +internal final class ConnectionNavigatorModel: ObservableObject { + nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "ConnectionNavigator") + + /// The window drawing the navigator, which is the only one that can say which connection is on + /// screen and which ones a click can switch to. + internal weak var host: (any WorkspaceRailHost)? + internal var onOpenFailure: ((Error) -> Void)? + + @Published internal private(set) var rows: [ConnectionNavigatorRow] = [] + @Published internal private(set) var revision = 0 + @Published internal private(set) var presentationRevision = 0 + internal private(set) var isLibraryEmpty = true + internal private(set) var groups: [ConnectionGroup] = [] + + internal var filterText = "" { + didSet { + guard filterText != oldValue else { return } + rebuild() + } + } + + private let environment: ConnectionNavigatorEnvironment + private var connections: [DatabaseConnection] = [] + private var expandedGroupIds: Set = [] + private var hasLoadedExpansion = false + private var cancellables: Set = [] + + internal init(environment: ConnectionNavigatorEnvironment = ConnectionNavigatorEnvironment()) { + self.environment = environment + } + + internal var isFiltering: Bool { + !LibraryQuery(text: filterText).trimmedText.isEmpty + } + + internal var shownConnectionId: UUID? { + host?.selectedConnectionId + } + + // MARK: - Lifecycle + + /// Called each time the list comes on screen. A list that was away missed every event, so it + /// rebuilds whether or not it was already listening. + internal func start() { + if cancellables.isEmpty { + let events = environment.appEvents + Publishers.Merge(events.connectionUpdated.map { _ in () }, events.connectionListStateChanged) + .receive(on: RunLoop.main) + .sink { [weak self] in self?.rebuild() } + .store(in: &cancellables) + // The mark reads the session and the window phase, and placement reads which window + // hosts what; none of them is observable, so each of their events re-marks the rows. + Publishers.Merge3( + events.connectionStatusChanged.map { _ in () }, + events.connectionPhaseChanged.map { _ in () }, + events.connectionWindowsChanged + ) + .receive(on: RunLoop.main) + .sink { [weak self] in self?.refreshPresentation() } + .store(in: &cancellables) + } + rebuild() + } + + internal func stop() { + cancellables.removeAll() + } + + // MARK: - Rows + + internal func rebuild() { + connections = environment.connectionStorage.loadConnections() + groups = environment.groupStorage.loadGroups() + let groupIds = Set(groups.map(\.id)) + if hasLoadedExpansion { + expandedGroupIds.formIntersection(groupIds) + } else { + expandedGroupIds = environment.expansionStore.load(keeping: groupIds) + hasLoadedExpansion = true + } + isLibraryEmpty = connections.isEmpty + + let presentation = presentationMaps() + rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: connections, + groups: groups, + sortMode: environment.listPreferences.sortMode, + lastConnected: environment.recentConnections.lastConnected, + filterText: filterText, + expandedGroupIds: expandedGroupIds, + statuses: presentation.statuses, + placements: presentation.placements, + driverRejectedIds: Set(connections.filter(environment.isDriverRejected).map(\.id)) + )) + revision += 1 + } + + internal func refreshPresentation() { + let presentation = presentationMaps() + let updated = ConnectionNavigatorRowsBuilder.applying( + statuses: presentation.statuses, + placements: presentation.placements, + to: rows + ) + guard updated != rows else { return } + rows = updated + presentationRevision += 1 + } + + private func presentationMaps() -> ( + statuses: [UUID: ConnectionDisplayStatus], + placements: [UUID: ConnectionNavigatorPlacement] + ) { + let hostedHere = Set(host?.hostedConnectionIds ?? []) + let hostedAnywhere = environment.hostedConnectionIds().union(hostedHere) + let shown = host?.selectedConnectionId + var statuses: [UUID: ConnectionDisplayStatus] = [:] + var placements: [UUID: ConnectionNavigatorPlacement] = [:] + for connection in connections { + statuses[connection.id] = environment.status(connection.id) + placements[connection.id] = ConnectionNavigatorRowsBuilder.placement( + of: connection.id, + shown: shown, + hostedHere: hostedHere, + hostedAnywhere: hostedAnywhere + ) + } + return (statuses, placements) + } + + /// The groups a filter opens are the filter's, so a user expanding or collapsing one while it + /// runs does not overwrite what they chose before typing. + internal func setGroupExpanded(_ id: UUID, _ expanded: Bool) { + guard !isFiltering else { return } + if expanded { + expandedGroupIds.insert(id) + } else { + expandedGroupIds.remove(id) + } + environment.expansionStore.save(expandedGroupIds) + } + + // MARK: - Interaction + + /// A click switches only between connections this window already hosts. Anything else is a + /// highlight: a list holding production servers must not dial one because the pointer slipped. + internal func handleClick(on row: ConnectionNavigatorRowID?) { + guard case .connection(let id) = row, + let host, + host.hostedConnectionIds.contains(id), + host.selectedConnectionId != id + else { return } + host.selectHostedConnection(id) + } + + /// Double click and Return. The router raises a window that already hosts the connection, and + /// otherwise opens it in the frontmost one, which is this one. + internal func open(_ connectionId: UUID) async { + do { + try await environment.router.route(.openConnection(connectionId)) + } catch { + report(error, connectionId: connectionId) + } + } + + /// A connect that reached a window fails inline in its pane. Only an error raised before any + /// window took the connection, such as a record deleted meanwhile, is this list's to show. + private func report(_ error: Error, connectionId: UUID) { + let isShownInWindow = environment.hostedConnectionIds().contains(connectionId) + || host?.hostedConnectionIds.contains(connectionId) == true + switch WelcomeViewModel.route(for: error, isShownInWindow: isShownInWindow) { + case .ignore, .window: + Self.logger.info("Open handled in its window: \(error.publicLogShape, privacy: .public)") + case .pluginInstall, .alert: + Self.logger.error("Failed to open the connection: \(error.publicLogShape, privacy: .public)") + onOpenFailure?(error) + } + } + + internal func menuTarget(for row: ConnectionNavigatorRowID?) -> ConnectionNavigatorMenuTarget { + switch row { + case .group(let id): + return .group(id) + case .connection(let id): + let hostedHere = Set(host?.hostedConnectionIds ?? []) + return .connection(ConnectionNavigatorMenuConnection( + id: id, + placement: ConnectionNavigatorRowsBuilder.placement( + of: id, + shown: host?.selectedConnectionId, + hostedHere: hostedHere, + hostedAnywhere: environment.hostedConnectionIds().union(hostedHere) + ), + status: environment.status(id), + holdsSession: environment.holdsSession(id), + canMoveToNewWindow: environment.canMoveToNewWindow(id) + )) + case nil: + return .empty + } + } + + /// Every command but New Group, whose sheet belongs to the view that presents it. + internal func perform(_ command: ConnectionNavigatorCommand, presentingWindow: NSWindow?) { + switch command { + case .switchTo(let id): + host?.selectHostedConnection(id) + case .open(let id): + Task { await open(id) } + case .openInNewWindow(let id): + openInNewWindow(id) + case .disconnect(let id): + let name = connections.first { $0.id == id }?.name ?? "" + Task { + await ConnectionDisconnectAction.disconnect( + connectionId: id, + connectionName: name, + presentingWindow: presentingWindow + ) + } + case .edit(let id): + WindowOpener.shared.openConnectionForm(editing: id) + case .duplicate(let id): + duplicate(id) + case .newConnection: + WindowOpener.shared.openConnectionForm() + case .newGroup: + return + } + } + + /// A connection this window hosts moves out with its tabs and session, as the strip's command + /// does; one nobody hosts opens in a window of its own. + private func openInNewWindow(_ id: UUID) { + if host?.hostedConnectionIds.contains(id) == true { + WindowManager.shared.moveToNewWindow(connectionId: id) + return + } + Task { + do { + try await environment.router.openConnectionPreferringNewWindow(id: id) + } catch { + report(error, connectionId: id) + } + } + } + + private func duplicate(_ id: UUID) { + guard let connection = connections.first(where: { $0.id == id }), + let copy = environment.connectionStorage.duplicateConnection(connection) + else { + Self.logger.error("Duplicate found no connection to copy or could not save the copy") + return + } + WindowOpener.shared.openConnectionForm(editing: copy.id) + } + + /// Made through the store the Welcome window uses, so the same name, cycle and depth checks + /// apply. The group and its parent open, since a new group nobody can see looks like a failure. + internal func createGroup(_ fields: ConnectionGroupFields) throws { + let group = ConnectionGroup( + name: fields.name, + color: fields.color, + iconName: fields.iconName, + parentId: fields.parentId + ) + try environment.groupStorage.addGroup(group) + expandedGroupIds.insert(group.id) + if let parentId = fields.parentId { + expandedGroupIds.insert(parentId) + } + environment.expansionStore.save(expandedGroupIds) + rebuild() + } +} diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorFixture.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorFixture.swift new file mode 100644 index 0000000000..65d85b8638 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorFixture.swift @@ -0,0 +1,116 @@ +// +// ConnectionNavigatorFixture.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import TableProSyncTransport + +/// The window a navigator belongs to, reduced to its workspace registry. +@MainActor +final class FakeNavigatorHost: WorkspaceRailHost { + var hosted: [UUID] = [] + var selected: UUID? + + var hostedConnectionIds: [UUID] { hosted } + var selectedConnectionId: UUID? { selected } + + func selectHostedConnection(_ connectionId: UUID) { + guard hosted.contains(connectionId) else { return } + selected = connectionId + } +} + +@MainActor +final class RecordingNavigatorRouter: ConnectionNavigatorRouting { + private(set) var openedConnections: [UUID] = [] + private(set) var newWindowConnections: [UUID] = [] + var failure: Error? + + func route(_ intent: LaunchIntent) async throws { + if let failure { throw failure } + guard case .openConnection(let id) = intent else { return } + openedConnections.append(id) + } + + func openConnectionPreferringNewWindow(id: UUID) async throws { + newWindowConnections.append(id) + } +} + +/// Storage, events and window facts the navigator reads, each on its own instance so nothing +/// reaches the app's real library. +@MainActor +final class ConnectionNavigatorFixture { + let events = AppEvents() + let host = FakeNavigatorHost() + let router = RecordingNavigatorRouter() + let connectionStorage: ConnectionStorage + let groupStorage: GroupStorage + let listPreferences: ConnectionListPreferences + let expansionStore: ConnectionNavigatorExpansionStore + var statuses: [UUID: ConnectionDisplayStatus] = [:] + var hostedAnywhere: Set = [] + + private let suite: EphemeralDefaults + private let syncSuite: EphemeralDefaults + private let directory: URL + + init() throws { + suite = try EphemeralDefaults() + syncSuite = try EphemeralDefaults() + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent("navigator-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let tracker = SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: syncSuite.defaults)) + let events = events + let connectionStorage = ConnectionStorage( + fileURL: directory.appendingPathComponent("connections.json"), + userDefaults: suite.defaults, + syncTracker: tracker, + appEvents: events + ) + self.connectionStorage = connectionStorage + groupStorage = GroupStorage( + userDefaults: suite.defaults, + syncTracker: tracker, + connectionStorage: connectionStorage, + appEvents: events + ) + listPreferences = ConnectionListPreferences(defaults: suite.defaults, appEvents: events) + expansionStore = ConnectionNavigatorExpansionStore(defaults: suite.defaults) + } + + isolated deinit { + try? FileManager.default.removeItem(at: directory) + } + + func makeModel() -> ConnectionNavigatorModel { + var environment = ConnectionNavigatorEnvironment() + environment.appEvents = events + environment.connectionStorage = connectionStorage + environment.groupStorage = groupStorage + environment.listPreferences = listPreferences + environment.recentConnections = RecentConnectionsStore(defaults: suite.defaults, appEvents: events) + environment.expansionStore = expansionStore + environment.router = router + environment.status = { [unowned self] in statuses[$0] ?? .notConnected } + environment.holdsSession = { [unowned self] in statuses[$0] == .connected } + environment.hostedConnectionIds = { [unowned self] in hostedAnywhere.union(host.hosted) } + environment.canMoveToNewWindow = { _ in false } + environment.isDriverRejected = { _ in false } + let model = ConnectionNavigatorModel(environment: environment) + model.host = host + return model + } + + @discardableResult + func save(_ connections: [DatabaseConnection]) -> [DatabaseConnection] { + _ = connectionStorage.saveConnections(connections) + return connections + } +} diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorInteractionTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorInteractionTests.swift new file mode 100644 index 0000000000..d3eb56b50c --- /dev/null +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorInteractionTests.swift @@ -0,0 +1,65 @@ +// +// ConnectionNavigatorInteractionTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +/// A list that holds production servers must never dial one on a stray click, so only a double +/// click or Return opens, and a single click only switches between connections already open here. +@MainActor +struct ConnectionNavigatorInteractionTests { + private let fixture: ConnectionNavigatorFixture + private let shown = UUID() + private let hosted = UUID() + private let closed = UUID() + + init() throws { + fixture = try ConnectionNavigatorFixture() + fixture.host.hosted = [shown, hosted] + fixture.host.selected = shown + } + + @Test("A single click on a connection this window hosts switches to it") + func clickOnHostedConnectionSwitches() { + let model = fixture.makeModel() + + model.handleClick(on: .connection(hosted)) + + #expect(fixture.host.selected == hosted) + #expect(fixture.router.openedConnections.isEmpty) + } + + @Test("A single click on any other connection opens nothing") + func clickOnOtherConnectionDoesNotRoute() { + let model = fixture.makeModel() + + model.handleClick(on: .connection(closed)) + + #expect(fixture.host.selected == shown) + #expect(fixture.router.openedConnections.isEmpty) + } + + @Test("A double click opens the connection through the router") + func doubleClickRoutesOpenConnection() async { + let model = fixture.makeModel() + + await model.open(closed) + + #expect(fixture.router.openedConnections == [closed]) + } + + @Test("A route that fails is reported once") + func routeFailureReportsOnce() async { + let model = fixture.makeModel() + var failures = 0 + model.onOpenFailure = { _ in failures += 1 } + fixture.router.failure = TabRouterError.connectionNotFound(closed) + + await model.open(closed) + + #expect(failures == 1) + } +} diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift new file mode 100644 index 0000000000..de555fb73f --- /dev/null +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift @@ -0,0 +1,131 @@ +// +// ConnectionNavigatorModelTests.swift +// TableProTests +// + +import Combine +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import TableProTestSupport +import Testing + +@MainActor +struct ConnectionNavigatorModelTests { + private let fixture: ConnectionNavigatorFixture + + init() throws { + fixture = try ConnectionNavigatorFixture() + } + + private static func connectionRow(_ id: UUID, in rows: [ConnectionNavigatorRow]) -> ConnectionNavigatorConnectionRow? { + for row in rows { + switch row { + case .connection(let connection) where connection.id == id: + return connection + case .connection: + continue + case .group(let group): + if let nested = connectionRow(id, in: group.children) { return nested } + } + } + return nil + } + + @Test("A connection saved elsewhere appears once the library says it changed") + func rebuildsOnConnectionUpdated() async throws { + let model = fixture.makeModel() + model.start() + defer { model.stop() } + let before = model.revision + + fixture.save([TestFixtures.makeConnection(name: "Orders")]) + fixture.events.connectionUpdated.send(nil) + + try await waitUntil { model.rows.count == 1 } + #expect(model.revision > before) + } + + @Test("A status change repaints the status without a rebuild") + func statusChangeRepaintsOnly() async throws { + let connection = TestFixtures.makeConnection(name: "Orders") + fixture.save([connection]) + let model = fixture.makeModel() + model.start() + defer { model.stop() } + let revision = model.revision + let presentation = model.presentationRevision + + fixture.statuses[connection.id] = .connecting + fixture.events.connectionPhaseChanged.send(connection.id) + + try await waitUntil { Self.connectionRow(connection.id, in: model.rows)?.status == .connecting } + #expect(model.revision == revision) + #expect(model.presentationRevision > presentation) + } + + @Test("The shown connection, one hosted here and one open in another window are told apart") + func marksShownOpenHereAndElsewhere() throws { + let shown = TestFixtures.makeConnection(name: "Shown") + let hosted = TestFixtures.makeConnection(name: "Hosted") + let elsewhere = TestFixtures.makeConnection(name: "Elsewhere") + let closed = TestFixtures.makeConnection(name: "Closed") + fixture.save([shown, hosted, elsewhere, closed]) + fixture.host.hosted = [shown.id, hosted.id] + fixture.host.selected = shown.id + fixture.hostedAnywhere = [elsewhere.id] + let model = fixture.makeModel() + model.start() + defer { model.stop() } + + #expect(try #require(Self.connectionRow(shown.id, in: model.rows)).placement == .shownHere) + #expect(try #require(Self.connectionRow(hosted.id, in: model.rows)).placement == .openHere) + #expect(try #require(Self.connectionRow(elsewhere.id, in: model.rows)).placement == .openElsewhere) + #expect(try #require(Self.connectionRow(closed.id, in: model.rows)).placement == .notOpen) + } + + @Test("Expanding a group is remembered, but not while a filter opens groups for the user") + func expansionPersistsAndIgnoresFilter() throws { + let kept = ConnectionGroup(name: "Kept") + let filtered = ConnectionGroup(name: "Filtered") + try fixture.groupStorage.addGroup(kept) + try fixture.groupStorage.addGroup(filtered) + let model = fixture.makeModel() + model.start() + defer { model.stop() } + + model.setGroupExpanded(kept.id, true) + #expect(fixture.expansionStore.load(keeping: [kept.id, filtered.id]) == [kept.id]) + + model.filterText = "x" + model.setGroupExpanded(filtered.id, true) + #expect(fixture.expansionStore.load(keeping: [kept.id, filtered.id]) == [kept.id]) + } + + @Test("A group made from the navigator opens, and so does its parent") + func createdGroupOpensWithItsParent() throws { + let parent = ConnectionGroup(name: "Parent") + try fixture.groupStorage.addGroup(parent) + let model = fixture.makeModel() + model.start() + defer { model.stop() } + + try model.createGroup(ConnectionGroupFields(name: "Child", parentId: parent.id)) + + let child = try #require(fixture.groupStorage.loadGroups().first { $0.name == "Child" }) + #expect(fixture.expansionStore.load(keeping: [parent.id, child.id]) == [parent.id, child.id]) + } + + @Test("The library reads empty until it holds a connection") + func libraryEmptyTracksConnections() { + let model = fixture.makeModel() + model.start() + defer { model.stop() } + #expect(model.isLibraryEmpty) + + fixture.save([TestFixtures.makeConnection(name: "Orders")]) + model.rebuild() + + #expect(!model.isLibraryEmpty) + } +} From bdd09494336f5ddc2f3927d4b1283465984297c6 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:15:17 +0700 Subject: [PATCH 020/123] feat(navigator): draw the connection navigator Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorRowView.swift | 119 ++++ .../ConnectionNavigatorViewController.swift | 539 ++++++++++++++++++ ...nnectionNavigatorViewControllerTests.swift | 181 ++++++ 3 files changed, 839 insertions(+) create mode 100644 apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift create mode 100644 apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift create mode 100644 apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift new file mode 100644 index 0000000000..b40393fa65 --- /dev/null +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift @@ -0,0 +1,119 @@ +// +// ConnectionNavigatorRowView.swift +// TablePro +// + +import SwiftUI +import TableProConnectionLibrary + +/// A navigator row at the sidebar's own row size: the Welcome window's tiles are 44 points tall and +/// would not fit beside the object list. +/// +/// No `.contextMenu` here: the outline view owns the menu, so AppKit sets `clickedRow`, highlights +/// the clicked row and answers a right-click below the last one. +internal struct ConnectionNavigatorRowView: View { + let row: ConnectionNavigatorRow + let rowSizePreference: SidebarRowSizePreference + + @Environment(\.sidebarRowSize) private var systemRowSize + + var body: some View { + content + .font(rowSize.rowFont) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + + /// AppKit sizes the row from `rowSizeStyle` by laying out a text field these cells do not have, + /// so the hosted content takes the matching font itself, as the Favorites rows do. + private var rowSize: SidebarRowSize { + SidebarRowSizeResolver.resolve(preference: rowSizePreference, system: systemRowSize) + } + + @ViewBuilder + private var content: some View { + switch row { + case .group(let group): + ConnectionNavigatorGroupLabel(group: group) + case .connection(let connection): + ConnectionNavigatorConnectionLabel(row: connection, glyphSide: rowSize.iconPointSize) + } + } +} + +private struct ConnectionNavigatorGroupLabel: View { + let group: ConnectionNavigatorGroupRow + + var body: some View { + HStack(spacing: 6) { + Image(systemName: LibraryGlyph.groupSymbol(group.iconName)) + .selectionAwareTint(group.color.isDefault ? .secondary : group.color.color) + .accessibilityHidden(true) + Text(group.name) + .lineLimit(1) + Spacer(minLength: 6) + Text(group.connectionCount, format: .number) + .monospacedDigit() + .foregroundStyle(.secondary) + } + .padding(.trailing, 8) + .accessibilityElement(children: .combine) + } +} + +private struct ConnectionNavigatorConnectionLabel: View { + let row: ConnectionNavigatorConnectionRow + let glyphSide: CGFloat + + private static let identityBarWidth: CGFloat = 3 + + var body: some View { + HStack(spacing: 6) { + identityBar + LibraryGlyph.connectionImage(type: row.connection.type, iconName: row.connection.iconName) + .renderingMode(.template) + .scaledToFit() + .font(.system(size: glyphSide * 0.85)) + .frame(width: glyphSide, height: glyphSide) + .selectionAwareTint(row.connection.type.themeColor) + .accessibilityHidden(true) + Text(row.connection.name) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 4) + accessories + } + .padding(.trailing, 8) + .help(WelcomeRowPresentation.tooltip(for: row.connection, groupPath: row.groupPath, tags: [])) + .accessibilityElement(children: .combine) + } + + /// Kept, clear, when the connection has no color, so every name starts at the same x. + private var identityBar: some View { + RoundedRectangle(cornerRadius: Self.identityBarWidth / 2, style: .continuous) + .fill(row.connection.identityColor?.color ?? .clear) + .frame(width: Self.identityBarWidth, height: glyphSide) + .accessibilityHidden(true) + } + + @ViewBuilder + private var accessories: some View { + HStack(spacing: 4) { + if row.isDriverRejected { + Image(systemName: "exclamationmark.triangle.fill") + .imageScale(.small) + .selectionAwareTint(.yellow) + .help(String(localized: "Driver plugin not loaded. Open Settings to update.")) + .accessibilityLabel(String(localized: "Plugin not loaded")) + } + if row.placement == .openElsewhere { + Image(systemName: "macwindow") + .imageScale(.small) + .foregroundStyle(.secondary) + .help(String(localized: "Open in another window")) + .accessibilityLabel(String(localized: "Open in another window")) + } + ConnectionStatusMark(presentation: ConnectionStatusPresentation(row.status)) + } + } +} diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift new file mode 100644 index 0000000000..b82a81421f --- /dev/null +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift @@ -0,0 +1,539 @@ +// +// ConnectionNavigatorViewController.swift +// TablePro +// + +import AppKit +import Combine +import SwiftUI +import TableProConnectionLibrary + +/// The navigator's list. Return opens, Escape clears the filter, and a click takes the keyboard. +/// +/// Not a `SidebarOutlineView`: that class takes the keyboard whenever its window has no first +/// responder, and this list sits in a column that can be collapsed, where taking it would put the +/// keyboard in a list nobody can see. +internal final class ConnectionNavigatorOutlineView: NSOutlineView { + internal weak var navigator: ConnectionNavigatorViewController? + + /// Set the moment the column is told to hide. AppKit hides a collapsing split item only once its + /// animation ends, and until then the list would still offer itself as a key view. + internal var isColumnShown = true + + override internal var canBecomeKeyView: Bool { + isColumnShown && super.canBecomeKeyView + } + + override internal func mouseDown(with event: NSEvent) { + if let window, window.firstResponder !== self { + window.makeFirstResponder(self) + } + super.mouseDown(with: event) + } + + override internal func insertNewline(_ sender: Any?) { + navigator?.activateSelection() + } + + override internal func cancelOperation(_ sender: Any?) { + navigator?.clearFilter() + } +} + +/// One outline row, kept across reloads by id so the outline's expansion and selection follow the +/// same group or connection, as `WelcomeOutlineItem` does. +internal final class ConnectionNavigatorOutlineItem: NSObject { + internal let id: ConnectionNavigatorRowID + internal var row: ConnectionNavigatorRow + internal var children: [ConnectionNavigatorOutlineItem] = [] + + internal init(row: ConnectionNavigatorRow) { + self.id = row.id + self.row = row + } +} + +internal final class ConnectionNavigatorCellView: SidebarHostingCellView {} + +/// Every saved connection in its groups, in the window's connections column. +/// +/// AppKit on purpose, as the strip beside it and the Favorites outline are: a SwiftUI `List` cannot +/// draw an emphasized selection under a bare `NSHostingController`. The rows stay SwiftUI inside +/// source list cells, the way the sidebar's other lists draw theirs. +@MainActor +internal final class ConnectionNavigatorViewController: NSViewController, NSSearchFieldDelegate, NSMenuDelegate, + NSOutlineViewDataSource, NSOutlineViewDelegate { + internal static let defaultWidth: CGFloat = 220 + internal static let minimumWidth: CGFloat = 180 + internal static let maximumWidth: CGFloat = 400 + + private static let cellIdentifier = NSUserInterfaceItemIdentifier("ConnectionNavigatorCell") + + internal let model: ConnectionNavigatorModel + internal let filterField = NSSearchField() + internal let outlineView = ConnectionNavigatorOutlineView() + internal var onWidthChange: (() -> Void)? + + internal var isColumnShown: Bool { + get { outlineView.isColumnShown } + set { outlineView.isColumnShown = newValue } + } + + private var scrollView: NSScrollView? + private let emptyState = NSStackView() + private var items: [ConnectionNavigatorRowID: ConnectionNavigatorOutlineItem] = [:] + private var rootItems: [ConnectionNavigatorOutlineItem] = [] + private var isApplyingExpansion = false + private var isReloading = false + private var reportedWidth: CGFloat = 0 + private var rowSizePreference = AppSettingsManager.shared.general.sidebarRowSize + private var modelCancellables: Set = [] + private var rowSizeObservation: AnyCancellable? + + internal init(model: ConnectionNavigatorModel = ConnectionNavigatorModel()) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("ConnectionNavigatorViewController does not support NSCoder init") + } + + // MARK: - View + + /// The frame's width is the one the column first opens at: a split item expanding for the first + /// time takes its view's own width, and the autosaved width replaces it from then on. + override internal func loadView() { + view = NSView(frame: NSRect(x: 0, y: 0, width: Self.defaultWidth, height: 400)) + + filterField.translatesAutoresizingMaskIntoConstraints = false + filterField.placeholderString = String(localized: "Filter Connections") + filterField.controlSize = .regular + filterField.sendsSearchStringImmediately = true + filterField.delegate = self + filterField.setAccessibilityIdentifier("connection-navigator-filter") + filterField.setAccessibilityLabel(String(localized: "Filter Connections")) + view.addSubview(filterField) + + let scrollView = SidebarOutlineScaffold.makeScrollView( + outlineView: outlineView, + configuration: SidebarOutlineScaffold.Configuration( + columnIdentifier: "ConnectionNavigatorColumn", + allowsMultipleSelection: false, + rowSizePreference: rowSizePreference + ) + ) + scrollView.translatesAutoresizingMaskIntoConstraints = false + self.scrollView = scrollView + view.addSubview(scrollView) + + outlineView.navigator = self + outlineView.dataSource = self + outlineView.delegate = self + outlineView.target = self + outlineView.action = #selector(handleClick) + outlineView.doubleAction = #selector(handleDoubleClick) + outlineView.setAccessibilityIdentifier("connection-navigator") + outlineView.setAccessibilityLabel(String(localized: "Connections")) + let menu = NSMenu() + menu.delegate = self + outlineView.menu = menu + + configureEmptyState() + + /// Margins, not invariants: they yield rather than break while the column animates shut. + let insets = [ + filterField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10), + filterField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10), + ] + for inset in insets { + inset.priority = .defaultHigh + } + NSLayoutConstraint.activate(insets + [ + filterField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 5), + scrollView.topAnchor.constraint(equalTo: filterField.bottomAnchor, constant: 5), + scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), + scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), + scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + emptyState.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor), + emptyState.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor), + emptyState.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 10), + emptyState.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -10), + ]) + + observeModel() + observeRowSize() + model.onOpenFailure = { [weak self] error in + AlertHelper.showErrorSheet( + title: String(localized: "Connection Failed"), + message: error.localizedDescription, + window: self?.view.window + ) + } + } + + private func configureEmptyState() { + let title = NSTextField(labelWithString: String(localized: "No Saved Connections")) + title.textColor = .secondaryLabelColor + title.alignment = .center + let button = NSButton( + title: String(localized: "New Connection…"), + target: self, + action: #selector(newConnectionFromEmptyState) + ) + button.bezelStyle = .rounded + emptyState.orientation = .vertical + emptyState.alignment = .centerX + emptyState.spacing = 8 + emptyState.translatesAutoresizingMaskIntoConstraints = false + emptyState.setViews([title, button], in: .center) + emptyState.isHidden = true + view.addSubview(emptyState) + } + + /// The list comes back from wherever it was without knowing what it missed, so it reads the + /// library again each time it appears. + override internal func viewWillAppear() { + super.viewWillAppear() + model.start() + } + + override internal func viewDidDisappear() { + super.viewDidDisappear() + model.stop() + } + + /// Reported from here rather than from the split view's resize callback, which runs before the + /// column has taken its new width. + override internal func viewDidLayout() { + super.viewDidLayout() + guard view.frame.width != reportedWidth else { return } + reportedWidth = view.frame.width + onWidthChange?() + } + + /// `@Published` sends before it stores, so these read the rows, which the model always writes + /// before it moves either revision. + private func observeModel() { + model.$revision + .dropFirst() + .sink { [weak self] _ in self?.reload() } + .store(in: &modelCancellables) + model.$presentationRevision + .dropFirst() + .sink { [weak self] _ in self?.refreshRows() } + .store(in: &modelCancellables) + } + + /// The navigator sits beside the object list, so it takes the same row size. + private func observeRowSize() { + rowSizeObservation = AppSettingsManager.shared.onMainActorChange { [weak self] in + guard let self else { return } + let current = AppSettingsManager.shared.general.sidebarRowSize + guard current != self.rowSizePreference else { return } + self.rowSizePreference = current + if let scrollView = self.scrollView { + SidebarOutlineScaffold.applyRowSize(current, to: scrollView) + } + self.reload() + } + } + + // MARK: - Reload + + private func reload() { + guard isViewLoaded else { return } + let previous = selectedRowID + rebuildItems() + isReloading = true + outlineView.reloadData() + applyExpansion() + if let previous, row(for: previous) >= 0 { + select(row(for: previous)) + } else { + selectShownConnection() + } + isReloading = false + applyEmptyState() + } + + private func rebuildItems() { + var used: Set = [] + func item(for row: ConnectionNavigatorRow) -> ConnectionNavigatorOutlineItem { + used.insert(row.id) + let built = items[row.id] ?? ConnectionNavigatorOutlineItem(row: row) + built.row = row + built.children = row.children.map(item(for:)) + items[row.id] = built + return built + } + rootItems = model.rows.map(item(for:)) + items = items.filter { used.contains($0.key) } + } + + /// A status or a window moved: the same rows, marked differently. + private func refreshRows() { + guard isViewLoaded else { return } + func update(_ rows: [ConnectionNavigatorRow]) { + for row in rows { + items[row.id]?.row = row + update(row.children) + } + } + update(model.rows) + let visible = outlineView.rows(in: outlineView.visibleRect) + guard visible.length > 0 else { return } + outlineView.reloadData( + forRowIndexes: IndexSet(integersIn: visible.location.. Int { + guard let item = items[id] else { return -1 } + return outlineView.row(forItem: item) + } + + /// The window switched connection. The highlight follows it, and the rows' marks with it. + internal func refreshSelection() { + guard isViewLoaded else { return } + model.refreshPresentation() + selectShownConnection() + } + + /// A connection the library does not hold, one opened from a file or a link, leaves nothing + /// selected rather than a row that is not it. + private func selectShownConnection() { + guard let shown = model.shownConnectionId else { + outlineView.deselectAll(nil) + return + } + select(row(for: .connection(shown))) + } + + private func select(_ row: Int) { + guard row >= 0 else { + outlineView.deselectAll(nil) + return + } + outlineView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) + outlineView.scrollRowToVisible(row) + } + + // MARK: - Actions + + @objc + private func handleClick() { + let clicked = outlineView.clickedRow + guard clicked >= 0 else { return } + model.handleClick(on: (outlineView.item(atRow: clicked) as? ConnectionNavigatorOutlineItem)?.id) + } + + @objc + private func handleDoubleClick() { + let clicked = outlineView.clickedRow + guard clicked >= 0, let item = outlineView.item(atRow: clicked) as? ConnectionNavigatorOutlineItem else { return } + activate(item) + } + + /// Return: a connection opens, a group opens or closes. + internal func activateSelection() { + guard let item = outlineView.item(atRow: outlineView.selectedRow) as? ConnectionNavigatorOutlineItem else { return } + activate(item) + } + + private func activate(_ item: ConnectionNavigatorOutlineItem) { + switch item.id { + case .group: + if outlineView.isItemExpanded(item) { + outlineView.collapseItem(item) + } else { + outlineView.expandItem(item) + } + case .connection(let id): + Task { await model.open(id) } + } + } + + internal func clearFilter() { + filterField.stringValue = "" + model.filterText = "" + } + + internal func focusFilter() { + guard filterField.isEnabled else { return } + view.window?.makeFirstResponder(filterField) + } + + /// Find, while the keyboard is in the column, means the column's own filter. This controller is + /// ahead of the window's in the responder chain only while that is so. + @objc + internal func performFind(_ sender: Any?) { + focusFilter() + } + + @objc + private func newConnectionFromEmptyState() { + model.perform(.newConnection, presentingWindow: view.window) + } + + // MARK: - Filter + + internal func controlTextDidChange(_ obj: Notification) { + guard (obj.object as? NSSearchField) === filterField else { return } + model.filterText = filterField.stringValue + } + + internal func searchFieldDidEndSearching(_ sender: NSSearchField) { + model.filterText = "" + } + + /// Down arrow carries the keyboard from the field into the list, as the sidebar's filter does. + internal func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { + guard commandSelector == #selector(NSResponder.moveDown(_:)), outlineView.numberOfRows > 0 else { return false } + view.window?.makeFirstResponder(outlineView) + if outlineView.selectedRow < 0 { + select(0) + } + return true + } + + // MARK: - Menu + + internal func menuNeedsUpdate(_ menu: NSMenu) { + let clicked = outlineView.clickedRow + let id = clicked >= 0 ? (outlineView.item(atRow: clicked) as? ConnectionNavigatorOutlineItem)?.id : nil + SidebarMenuBuilder.fill( + menu, + with: ConnectionNavigatorMenu.sections(for: model.menuTarget(for: id)), + target: self, + action: #selector(performNavigatorMenuCommand(_:)) + ) + } + + /// Named for the navigator: an `@objc` action sits in the responder chain, and a name the menu + /// bar also sends with no target would be taken here. + @objc + private func performNavigatorMenuCommand(_ sender: NSMenuItem) { + guard let box = sender.representedObject as? SidebarMenuCommandBox else { return } + guard case .newGroup(let parentId) = box.command else { + model.perform(box.command, presentingWindow: view.window) + return + } + presentNewGroupSheet(parentId: parentId) + } + + /// The group sheet the Welcome window uses, saving through the same store. + private func presentNewGroupSheet(parentId: UUID?) { + let sheet = GroupEditorSheet(mode: .create(parentId: parentId), groups: model.groups) { [weak self] draft in + try self?.model.createGroup(draft) + } + presentAsSheet(sheet) + } + + // MARK: - Data Source + + internal func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { + children(of: item).count + } + + internal func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { + children(of: item)[index] + } + + internal func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { + !((item as? ConnectionNavigatorOutlineItem)?.children.isEmpty ?? true) + } + + private func children(of item: Any?) -> [ConnectionNavigatorOutlineItem] { + guard let item = item as? ConnectionNavigatorOutlineItem else { return rootItems } + return item.children + } + + // MARK: - Delegate + + internal func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { + guard let item = item as? ConnectionNavigatorOutlineItem else { return nil } + let cell = outlineView.makeView(withIdentifier: Self.cellIdentifier, owner: self) as? ConnectionNavigatorCellView + ?? makeCell() + cell.update(rootView: ConnectionNavigatorRowView(row: item.row, rowSizePreference: rowSizePreference)) + return cell + } + + private func makeCell() -> ConnectionNavigatorCellView { + let cell = ConnectionNavigatorCellView() + cell.identifier = Self.cellIdentifier + return cell + } + + internal func outlineView( + _ outlineView: NSOutlineView, + typeSelectStringFor tableColumn: NSTableColumn?, + item: Any + ) -> String? { + switch (item as? ConnectionNavigatorOutlineItem)?.row { + case .group(let group): return group.name + case .connection(let connection): return connection.connection.name + case nil: return nil + } + } +} diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift new file mode 100644 index 0000000000..cc5d33c557 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift @@ -0,0 +1,181 @@ +// +// ConnectionNavigatorViewControllerTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct ConnectionNavigatorViewControllerTests { + private let fixture: ConnectionNavigatorFixture + + init() throws { + fixture = try ConnectionNavigatorFixture() + } + + private struct Hosted { + let controller: ConnectionNavigatorViewController + let window: NSWindow + + func tearDown() { + window.orderOut(nil) + window.contentViewController = nil + } + } + + private func host() -> Hosted { + let controller = ConnectionNavigatorViewController(model: fixture.makeModel()) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 260, height: 500), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentViewController = controller + window.orderFront(nil) + window.layoutIfNeeded() + return Hosted(controller: controller, window: window) + } + + private static func type(_ text: String, into controller: ConnectionNavigatorViewController) { + controller.filterField.stringValue = text + controller.controlTextDidChange(Notification( + name: NSControl.textDidChangeNotification, + object: controller.filterField + )) + } + + @Test("Typing a filter narrows the list and opens the group holding the match") + func filterNarrowsAndExpands() throws { + let group = ConnectionGroup(name: "Production") + try fixture.groupStorage.addGroup(group) + fixture.save([ + DatabaseConnection(name: "prod", groupId: group.id), + DatabaseConnection(name: "dev"), + ]) + let hosted = host() + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + + Self.type("prod", into: hosted.controller) + + #expect(hosted.controller.model.filterText == "prod") + #expect(outline.numberOfRows == 2) + #expect(outline.isItemExpanded(outline.item(atRow: 0))) + } + + @Test("Escape in the list clears the filter") + func escapeInListClearsFilter() { + fixture.save([DatabaseConnection(name: "prod")]) + let hosted = host() + defer { hosted.tearDown() } + Self.type("prod", into: hosted.controller) + #expect(hosted.controller.model.filterText == "prod") + + hosted.controller.outlineView.cancelOperation(nil) + + #expect(hosted.controller.model.filterText.isEmpty) + #expect(hosted.controller.filterField.stringValue.isEmpty) + } + + @Test("Find puts the keyboard in the filter field") + func findFocusesFilter() { + fixture.save([DatabaseConnection(name: "prod")]) + let hosted = host() + defer { hosted.tearDown() } + hosted.window.makeFirstResponder(hosted.controller.outlineView) + #expect(hosted.controller.filterField.currentEditor() == nil) + + hosted.controller.performFind(nil) + + #expect(hosted.controller.filterField.currentEditor() != nil) + } + + @Test("An empty library shows the empty state in place of the list") + func emptyLibraryShowsEmptyState() { + let hosted = host() + defer { hosted.tearDown() } + + #expect(hosted.controller.isShowingEmptyState) + #expect(hosted.controller.outlineView.enclosingScrollView?.isHidden == true) + } + + @Test("The connection this window shows is the selected row") + func shownConnectionIsSelected() { + let first = DatabaseConnection(name: "first") + let second = DatabaseConnection(name: "second") + fixture.save([first, second]) + fixture.host.hosted = [first.id, second.id] + fixture.host.selected = first.id + let hosted = host() + defer { hosted.tearDown() } + + fixture.host.selected = second.id + hosted.controller.refreshSelection() + + let row = hosted.controller.row(for: .connection(second.id)) + #expect(row >= 0) + #expect(hosted.controller.outlineView.selectedRow == row) + } + + @Test("Return on a group opens it and remembers that") + func returnOnGroupToggles() throws { + let group = ConnectionGroup(name: "Group") + try fixture.groupStorage.addGroup(group) + fixture.save([DatabaseConnection(name: "inside", groupId: group.id)]) + let hosted = host() + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + let row = hosted.controller.row(for: .group(group.id)) + outline.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) + + hosted.controller.activateSelection() + + #expect(outline.isItemExpanded(outline.item(atRow: row))) + #expect(fixture.expansionStore.load(keeping: [group.id]) == [group.id]) + } + + /// A deleted connection's row must not stay selected after the list drops it. + @Test("A selected connection deleted elsewhere hands the selection back to the shown one") + func deletedSelectionFallsBackToShown() { + let shown = DatabaseConnection(name: "shown") + let doomed = DatabaseConnection(name: "doomed") + fixture.save([shown, doomed]) + fixture.host.hosted = [shown.id] + fixture.host.selected = shown.id + let hosted = host() + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + let doomedRow = hosted.controller.row(for: .connection(doomed.id)) + #expect(doomedRow >= 0) + outline.selectRowIndexes(IndexSet(integer: max(doomedRow, 0)), byExtendingSelection: false) + + fixture.save([shown]) + hosted.controller.model.rebuild() + + #expect(hosted.controller.row(for: .connection(doomed.id)) == -1) + let shownRow = hosted.controller.row(for: .connection(shown.id)) + #expect(shownRow >= 0) + #expect(outline.selectedRow == shownRow) + } + + /// A connection opened from a file or a link is hosted without ever being saved. + @Test("A shown connection the library does not hold selects nothing") + func unsavedShownConnectionSelectsNothing() { + fixture.save([DatabaseConnection(name: "saved")]) + let unsaved = UUID() + fixture.host.hosted = [unsaved] + fixture.host.selected = unsaved + let hosted = host() + defer { hosted.tearDown() } + + hosted.controller.refreshSelection() + + #expect(hosted.controller.outlineView.numberOfRows == 1) + #expect(hosted.controller.outlineView.selectedRow == -1) + } +} From ae0165aa6964bde20b5ddd662af4017d9ea70426 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:15:17 +0700 Subject: [PATCH 021/123] feat(navigator): show the navigator in the connections column Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 1 + ...inSplitViewController+MenuValidation.swift | 10 +- .../MainSplitViewController.swift | 31 ++- .../NavigationSidebarViewController.swift | 195 +++++++++++--- .../Models/UI/SplitViewAutosaveName.swift | 3 + .../NavigationSidebarNavigatorTests.swift | 242 ++++++++++++++++++ 6 files changed, 439 insertions(+), 43 deletions(-) create mode 100644 apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index 71e2e33109..2076c9aa51 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -168,6 +168,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Team library, per team: pull cursor, items, unpushed edits, conflicts (synced with tablepro-cloud's `/v2`, never iCloud) | JSON, one file per team | `TeamLibraryStateStore` through `TeamLibrarySync` | | Sidebar database and schema filters, recent tables | UserDefaults, device-local | `DatabaseTreeFilterStorage`, `RecentTablesStore` | | Connection navigator group expansion | UserDefaults `com.TablePro.navigator.groupExpansion`, device-local, never synced | `ConnectionNavigatorExpansionStore` | +| Connection navigator column width | AppKit split view autosave `com.TablePro.connectionNavigator`, device-local | `NavigationSidebarViewController` through `SplitViewAutosaveName.current(_:)` | | History drawer state | UserDefaults, device-local | `HistoryPanelPreferencesStorage` | | Server Dashboard tiles, per connection | UserDefaults, device-local | `ServerDashboardTileStorage` | | Module on/off (Settings > Extensions) | UserDefaults, device-local, never synced | `AppModuleSettings` | diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift index 3083a75b24..66401dd60a 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift @@ -92,6 +92,7 @@ struct MenuValidationContext: Equatable { var canSaveAsFavorite = false var canSwitchSidebarLayout = false var canToggleWorkspaceRail = false + var canCycleWorkspaces = false // Only embedded engines that lock their database file answer yes, so server connections never show the command at all. var canReleaseFileLock = false var canShowTableStructure = false @@ -409,10 +410,11 @@ extension MainSplitViewController: NSMenuItemValidation { // A Focus command that would focus nothing is dimmed: `makeFirstResponder` accepts a view that cannot take the keyboard. private static func isWindowCommandEnabled(_ selector: Selector, context: MenuValidationContext) -> Bool? { switch selector { - case #selector(toggleWorkspaceRail(_:)), - #selector(showPreviousWorkspace(_:)), - #selector(showNextWorkspace(_:)): + case #selector(toggleWorkspaceRail(_:)): return context.canToggleWorkspaceRail + case #selector(showPreviousWorkspace(_:)), + #selector(showNextWorkspace(_:)): + return context.canCycleWorkspaces case #selector(focusObjectList(_:)): return context.canFocusObjectList case #selector(focusEditor(_:)): return context.canFocusEditor @@ -647,6 +649,7 @@ extension MainSplitViewController: NSMenuItemValidation { canMoveTabToConnection: canMoveSelectedTabToConnection, hasOtherWindowTabs: hasOtherWindowTabs, canToggleWorkspaceRail: canToggleWorkspaceRail, + canCycleWorkspaces: canCycleWorkspaces, canDisconnect: canDisconnect, isPresentingSheet: isViewLoaded && view.window?.attachedSheet != nil ) @@ -713,6 +716,7 @@ extension MainSplitViewController: NSMenuItemValidation { canSaveAsFavorite: actions.canSaveAsFavorite, canSwitchSidebarLayout: actions.canSwitchSidebarLayout, canToggleWorkspaceRail: canToggleWorkspaceRail, + canCycleWorkspaces: canCycleWorkspaces, canReleaseFileLock: canReleaseFileLock, canShowTableStructure: actions.canShowTableStructure, canEditViewDefinition: actions.canEditViewDefinition, diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index 867911de50..ce4e7a5cbc 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -315,6 +315,7 @@ internal final class MainSplitViewController: NSSplitViewController { navigationSidebar = NavigationSidebarViewController() navigationSidebar.railController.host = self + navigationSidebar.navigatorController.model.host = self navigationSidebar.railController.onLayoutChange = { [weak self] _ in self?.navigationSidebar.applyRailLayout() self?.recomputeWindowMinSize() @@ -702,6 +703,7 @@ internal final class MainSplitViewController: NSSplitViewController { /// Only this window's rail moved, and only its highlight. Broadcasting instead made every /// rail in the app rebuild its whole entry list to answer a question none of them asked. navigationSidebar?.railController.refreshSelection() + navigationSidebar?.navigatorController.refreshSelection() syncFrontmostTabManager() /// The toolbar's shape follows the workspace, not only its coordinator. Pointing the toolbar @@ -1188,6 +1190,14 @@ internal final class MainSplitViewController: NSSplitViewController { } var canToggleWorkspaceRail: Bool { + ConnectionWindowPaneResolver.canToggleConnectionsColumn( + navigatorEnabled: AppSettingsManager.shared.general.showsConnectionNavigator, + workspaceCount: WorkspaceRailStore.entries.count + ) + } + + /// Stepping between workspaces needs a second one whichever list the column holds. + var canCycleWorkspaces: Bool { WorkspaceRailStore.entries.count > 1 } @@ -1215,13 +1225,22 @@ internal final class MainSplitViewController: NSSplitViewController { /// sibling connection opening or closing is enough. func applyRailVisibility(workspaceCount: Int) { hostedWorkspaceCount = workspaceCount + let general = AppSettingsManager.shared.general + let showsNavigator = general.showsConnectionNavigator + navigationSidebar?.setNavigatorEnabled(showsNavigator) setWorkspaceRailVisible( - ConnectionWindowPaneResolver.showsWorkspaceRail( - preferenceEnabled: AppSettingsManager.shared.general.showWorkspaceRail, - workspaceCount: workspaceCount, - pane: currentPane, - isClosing: phase == .closing - ) + showsNavigator + ? ConnectionWindowPaneResolver.showsConnectionNavigator( + preferenceEnabled: general.showWorkspaceRail, + navigatorEnabled: showsNavigator, + isClosing: phase == .closing + ) + : ConnectionWindowPaneResolver.showsWorkspaceRail( + preferenceEnabled: general.showWorkspaceRail, + workspaceCount: workspaceCount, + pane: currentPane, + isClosing: phase == .closing + ) ) applyChromeStandingOnRail() } diff --git a/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift b/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift index ed04fe4b86..0151284546 100644 --- a/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift @@ -6,7 +6,7 @@ import AppKit import SwiftUI -/// The window's single sidebar: the workspace rail beside the object browser. +/// The window's single sidebar: the connections column beside the object browser. /// /// AppKit grants full-height layout, and the titlebar section that comes with it, to exactly /// one leading sidebar. Making the rail and the object browser two sidebar items meant that @@ -16,35 +16,56 @@ import SwiftUI /// /// Inside that item the two share a split view of their own, so the line between them is a divider /// the user drags to widen the strip, and AppKit keeps the width while the strip is hidden. +/// +/// The column holds the strip or, with the setting on, the connection navigator. A split item's +/// controller cannot be swapped once installed, and one split view carries one autosave name, so +/// the navigator gets a split of its own wrapped around the strip's: `[navigator | strip split]`, +/// with the strip collapsed inside. Each list keeps its own width, and neither the strip's split nor +/// the object browser is rebuilt when the setting flips. With the setting off the hierarchy is the +/// strip's split alone, exactly as before the navigator existed. @MainActor internal final class NavigationSidebarViewController: NSViewController { /// The object browser's floor. A strip dragged wider than the browser can give up widens the sidebar. internal static let objectBrowserMinimumThickness: CGFloat = 280 internal let railController: WorkspaceRailViewController + internal let navigatorController: ConnectionNavigatorViewController internal let objectBrowser: SidebarContainerViewController - /// The strip's own width moved: a drag, a restored width, or a sidebar icon size. + /// The column's own width moved: a drag, a restored width, or a sidebar icon size. internal var onRailWidthChange: (() -> Void)? private let splitController = NSSplitViewController() private let railItem: NSSplitViewItem private let browserItem: NSSplitViewItem + private let navigatorSplitController = NSSplitViewController() + private let navigatorItem: NSSplitViewItem + private let railSplitHost = WorkspacePaneHost() + private let railSplitHostItem: NSSplitViewItem + private var isNavigatorSplitBuilt = false + private var installedSplitConstraints: [NSLayoutConstraint] = [] + + /// Whether the column is on screen, whichever list it holds. internal private(set) var isRailVisible = false + internal private(set) var showsNavigator = false - /// While the strip slides in, its width is not yet the sidebar's to make room for: the strip + /// While the column slides in, its width is not yet the sidebar's to make room for: the column /// widens the sidebar itself, a frame at a time. private var isRevealingRail = false private var revealGeneration = 0 internal init() { let railController = WorkspaceRailViewController() + let navigatorController = ConnectionNavigatorViewController() let objectBrowser = SidebarContainerViewController() self.railController = railController + self.navigatorController = navigatorController self.objectBrowser = objectBrowser self.railItem = NSSplitViewItem(viewController: railController) self.browserItem = NSSplitViewItem(viewController: objectBrowser) + self.navigatorItem = NSSplitViewItem(viewController: navigatorController) + self.railSplitHostItem = NSSplitViewItem(viewController: railSplitHost) super.init(nibName: nil, bundle: nil) } @@ -60,7 +81,12 @@ internal final class NavigationSidebarViewController: NSViewController { railController.isStripShown = false railController.refreshLayoutIfNeeded() railController.onWidthChange = { [weak self] in - guard let self, !self.isRevealingRail else { return } + guard let self, !self.isRevealingRail, !self.showsNavigator else { return } + self.onRailWidthChange?() + } + navigatorController.isColumnShown = false + navigatorController.onWidthChange = { [weak self] in + guard let self, !self.isRevealingRail, self.showsNavigator else { return } self.onRailWidthChange?() } railItem.minimumThickness = railController.currentLayout.minimumWidth @@ -80,88 +106,183 @@ internal final class NavigationSidebarViewController: NSViewController { /// AppKit applies the saved record as the split view loads, so the name goes on first. splitView.autosaveName = SplitViewAutosaveName.current(SplitViewAutosaveName.workspaceRail) - addChild(splitController) - let split = splitController.view + install(splitController) + + /// Only once the split view has loaded. Collapsing before that discards the saved width and + /// keeps the strip out of the window altogether, where it cannot find its window's selection. + railItem.isCollapsed = true + } + + /// Pinned below the titlebar: the divider would otherwise run up through it beside the window + /// buttons. + private func install(_ controller: NSSplitViewController) { + addChild(controller) + let split = controller.view split.translatesAutoresizingMaskIntoConstraints = false view.addSubview(split) - NSLayoutConstraint.activate([ + installedSplitConstraints = [ split.leadingAnchor.constraint(equalTo: view.leadingAnchor), split.trailingAnchor.constraint(equalTo: view.trailingAnchor), - /// The divider would otherwise run up through the titlebar beside the window buttons. split.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), split.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) + ] + NSLayoutConstraint.activate(installedSplitConstraints) + } - /// Only once the split view has loaded. Collapsing before that discards the saved width and - /// keeps the strip out of the window altogether, where it cannot find its window's selection. - railItem.isCollapsed = true + private func uninstall(_ controller: NSSplitViewController) { + NSLayoutConstraint.deactivate(installedSplitConstraints) + installedSplitConstraints = [] + controller.view.removeFromSuperview() + controller.removeFromParent() + } + + // MARK: - Which list + + private var columnItem: NSSplitViewItem { + showsNavigator ? navigatorItem : railItem + } + + private var columnSplitView: NSSplitView { + showsNavigator ? navigatorSplitController.splitView : splitController.splitView } - /// The width the sidebar needs on top of the object browser's own minimum. Read from the strip's - /// own frame, which AppKit leaves at the strip's width while its item collapses and expands, so + /// The navigator's view is read only once loaded, so a window that never turns the setting on + /// never builds the list or starts its observers. + private var loadedNavigatorView: NSView? { + navigatorController.isViewLoaded ? navigatorController.view : nil + } + + private var columnViewWidth: CGFloat { + showsNavigator ? loadedNavigatorView?.frame.width ?? 0 : railController.view.frame.width + } + + /// Puts the strip or the navigator in the column. The column leaves the screen as the lists + /// trade places, and the window's rule brings it back through `setRailVisible`, which reveals + /// the new list at its own width. + internal func setNavigatorEnabled(_ enabled: Bool) { + _ = view + guard showsNavigator != enabled else { return } + if isRailVisible { + isRailVisible = false + applyColumnShown() + finishReveal() + handKeyboardOnFromColumn() + columnItem.isCollapsed = true + } + showsNavigator = enabled + applyColumnShown() + if enabled { + buildNavigatorSplitIfNeeded() + uninstall(splitController) + railSplitHost.show(splitController) + install(navigatorSplitController) + } else { + uninstall(navigatorSplitController) + railSplitHost.show(nil) + install(splitController) + } + onRailWidthChange?() + } + + private func buildNavigatorSplitIfNeeded() { + guard !isNavigatorSplitBuilt else { return } + isNavigatorSplitBuilt = true + navigatorItem.minimumThickness = ConnectionNavigatorViewController.minimumWidth + navigatorItem.maximumThickness = ConnectionNavigatorViewController.maximumWidth + navigatorItem.holdingPriority = .splitPaneHolding + /// Shown and hidden only by the window's rule, as the strip is. + navigatorItem.canCollapse = false + railSplitHostItem.minimumThickness = Self.objectBrowserMinimumThickness + railSplitHostItem.holdingPriority = .defaultLow + + let splitView = navigatorSplitController.splitView + splitView.isVertical = true + splitView.dividerStyle = .thin + navigatorSplitController.addSplitViewItem(navigatorItem) + navigatorSplitController.addSplitViewItem(railSplitHostItem) + /// Its own name, so the strip keeps the narrow width it was given while the navigator is off. + splitView.autosaveName = SplitViewAutosaveName.current(SplitViewAutosaveName.connectionNavigator) + _ = navigatorSplitController.view + navigatorItem.isCollapsed = true + } + + // MARK: - Width + + /// The width the sidebar needs on top of the object browser's own minimum. Read from the column's + /// own frame, which AppKit leaves at the column's width while its item collapses and expands, so /// no animated value is ever read: reading those left the sidebar minimum behind after a show. internal var railAllowance: CGFloat { guard isRailVisible, !isRevealingRail else { return 0 } - return railWidth + splitController.splitView.dividerThickness + return railWidth + columnSplitView.dividerThickness } - /// Clamped as AppKit clamps it, because a strip never shown since launch still has no frame, and - /// a width saved at a smaller sidebar icon size lays out at the larger size's minimum. + /// Clamped as AppKit clamps it, because a column never shown since launch still has no frame, and + /// a strip width saved at a smaller sidebar icon size lays out at the larger size's minimum. private var railWidth: CGFloat { - min(max(railController.view.frame.width, railItem.minimumThickness), railItem.maximumThickness) + min(max(columnViewWidth, columnItem.minimumThickness), columnItem.maximumThickness) } /// The sidebar icon size sets the strip's minimum. AppKit widens a narrower strip to it and gives /// the earlier width back when the minimum drops again. internal func applyRailLayout() { railItem.minimumThickness = railController.currentLayout.minimumWidth + navigatorItem.minimumThickness = ConnectionNavigatorViewController.minimumWidth } - /// A collapsed strip is hidden, not only zero points wide. AppKit counts a zero-width view as + // MARK: - Visibility + + /// A collapsed column is hidden, not only zero points wide. AppKit counts a zero-width view as /// visible, so the strip's list stayed a key view: it was what the window focused when first /// shown, Tab could land on it, and its own Close then took the whole connection on a Command W - /// meant for a tab. A collapsed split item hides its wrapper, which takes the strip out of the + /// meant for a tab. A collapsed split item hides its wrapper, which takes the column out of the /// key view loop, the responder chain and the accessibility tree, and the list stops offering - /// itself as a key view as soon as the strip is told to go. + /// itself as a key view as soon as the column is told to go. /// /// The keyboard moves on as the collapse starts, because AppKit hides the wrapper only once the /// animation ends, and a list that is about to vanish must not keep answering keys until then. internal func setRailVisible(_ visible: Bool, animated: Bool, alongside: (@MainActor () -> Void)? = nil) { guard isRailVisible != visible else { return } isRailVisible = visible - railController.isStripShown = visible + applyColumnShown() finishReveal() if !visible { - handKeyboardOnFromRail() + handKeyboardOnFromColumn() } + let item = columnItem guard animated, view.window != nil else { alongside?() - railItem.isCollapsed = !visible + item.isCollapsed = !visible return } guard visible else { NSAnimationContext.runAnimationGroup { context in context.duration = Self.animationDuration alongside?() - railItem.animator().isCollapsed = true + item.animator().isCollapsed = true } return } - revealRail(then: alongside) + revealColumn(then: alongside) } - /// The strip holds its own width as a minimum while it slides in, so where the sidebar is too - /// narrow for it the strip widens the sidebar a frame at a time. Raising the sidebar's range + private func applyColumnShown() { + railController.isStripShown = isRailVisible && !showsNavigator + navigatorController.isColumnShown = isRailVisible && showsNavigator + } + + /// The column holds its own width as a minimum while it slides in, so where the sidebar is too + /// narrow for it the column widens the sidebar a frame at a time. Raising the sidebar's range /// first is a required constraint that lands on the next layout pass: the sidebar snapped its /// full width wide in one frame while the strip slid in behind it. - private func revealRail(then alongside: (@MainActor () -> Void)?) { - railItem.minimumThickness = railWidth + private func revealColumn(then alongside: (@MainActor () -> Void)?) { + let item = columnItem + item.minimumThickness = railWidth isRevealingRail = true revealGeneration += 1 let generation = revealGeneration NSAnimationContext.runAnimationGroup { context in context.duration = Self.animationDuration - railItem.animator().isCollapsed = false + item.animator().isCollapsed = false } completionHandler: { [weak self] in guard let self, self.revealGeneration == generation, self.isRevealingRail else { return } self.finishReveal() @@ -181,13 +302,19 @@ internal final class NavigationSidebarViewController: NSViewController { /// view is hidden, only at the start of the collapse rather than the end. Leaving it with the /// window instead would make every key beep until the next click. The window takes it only /// when nothing else in the loop can. - private func handKeyboardOnFromRail() { + private func handKeyboardOnFromColumn() { guard let window = view.window, let responder = window.firstResponder as? NSView, - responder.isDescendant(of: railController.view) + isInsideColumn(responder) else { return } window.selectKeyView(following: responder) - guard let next = window.firstResponder as? NSView, next.isDescendant(of: railController.view) else { return } + guard let next = window.firstResponder as? NSView, isInsideColumn(next) else { return } window.makeFirstResponder(nil) } + + private func isInsideColumn(_ responder: NSView) -> Bool { + if responder.isDescendant(of: railController.view) { return true } + guard let navigator = loadedNavigatorView else { return false } + return responder.isDescendant(of: navigator) + } } diff --git a/apple/TablePro/Models/UI/SplitViewAutosaveName.swift b/apple/TablePro/Models/UI/SplitViewAutosaveName.swift index cb17ef4ee9..e4807c1a2c 100644 --- a/apple/TablePro/Models/UI/SplitViewAutosaveName.swift +++ b/apple/TablePro/Models/UI/SplitViewAutosaveName.swift @@ -12,6 +12,9 @@ internal enum SplitViewAutosaveName { /// One width for the connections strip in every window, as the main split keeps one sidebar width. internal static let workspaceRail = "com.TablePro.workspaceRail" + /// Its own record, so the strip keeps its narrow width while the navigator holds the column. + internal static let connectionNavigator = "com.TablePro.connectionNavigator" + internal static let historyDrawerPrefix = "HistoryDrawer-" /// Per connection, not per tab: the query tab branch has no `.id(tab.id)`, so its split view keeps the name it was born with. diff --git a/apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift b/apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift new file mode 100644 index 0000000000..31117cf127 --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift @@ -0,0 +1,242 @@ +// +// NavigationSidebarNavigatorTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import TableProTestSupport +import Testing + +/// With the setting on, the connections column holds the navigator in a split of its own, wrapped +/// around the strip's split, so each list keeps its own width and the object browser is never +/// rebuilt. +@MainActor +struct NavigationSidebarNavigatorTests { + private typealias SidebarHost = NavigationSidebarRailWidthTests.SidebarHost + + private static func enclosingSplitView(of view: NSView) throws -> NSSplitView { + var current = view.superview + while let candidate = current { + if let split = candidate as? NSSplitView { return split } + current = candidate.superview + } + throw NavigatorSplitMissing() + } + + private struct NavigatorSplitMissing: Error {} + + private static func showNavigator(in host: SidebarHost) { + host.sidebar.setNavigatorEnabled(true) + host.sidebar.setRailVisible(true, animated: false) + host.layout() + } + + @Test("A navigator shown for the first time opens at its default width") + func navigatorOpensAtItsDefaultWidth() throws { + let host = SidebarHost() + defer { host.tearDown() } + + Self.showNavigator(in: host) + + let navigator = host.sidebar.navigatorController.view + let split = try Self.enclosingSplitView(of: navigator) + #expect(navigator.frame.width == ConnectionNavigatorViewController.defaultWidth) + #expect(host.sidebar.railAllowance == ConnectionNavigatorViewController.defaultWidth + split.dividerThickness) + #expect(host.frameInSidebar(host.sidebar.objectBrowser.view).minX > 0) + } + + @Test("A navigator that is not shown reserves no width") + func hiddenNavigatorReservesNothing() { + let host = SidebarHost() + defer { host.tearDown() } + + host.sidebar.setNavigatorEnabled(true) + host.layout() + + let browser = host.sidebar.objectBrowser.view + #expect(host.sidebar.showsNavigator) + #expect(throws: Never.self) { try Self.enclosingSplitView(of: host.sidebar.navigatorController.view) } + #expect(host.sidebar.railAllowance == 0) + #expect(host.frameInSidebar(browser).minX == 0) + #expect(host.frameInSidebar(browser).width == host.sidebar.view.bounds.width) + } + + @Test("The strip keeps its width while the navigator stands in its place") + func railKeepsItsWidthThroughTheNavigator() throws { + let host = SidebarHost() + defer { host.tearDown() } + host.sidebar.setRailVisible(true, animated: false) + host.layout() + try host.splitView().setPosition(170, ofDividerAt: 0) + host.layout() + + Self.showNavigator(in: host) + #expect(host.sidebar.navigatorController.view.frame.width > 0) + #expect(host.rail.isHiddenOrHasHiddenAncestor) + host.sidebar.setNavigatorEnabled(false) + host.sidebar.setRailVisible(true, animated: false) + host.layout() + + #expect(host.rail.frame.width == 170) + } + + @Test("The navigator keeps its own width while it is off") + func navigatorKeepsItsWidthWhileOff() throws { + let host = SidebarHost() + defer { host.tearDown() } + Self.showNavigator(in: host) + try Self.enclosingSplitView(of: host.sidebar.navigatorController.view).setPosition(260, ofDividerAt: 0) + host.layout() + + host.sidebar.setNavigatorEnabled(false) + host.sidebar.setRailVisible(true, animated: false) + host.layout() + Self.showNavigator(in: host) + + #expect(host.sidebar.navigatorController.view.frame.width == 260) + } + + @Test("Turning the navigator on and off keeps the same object browser in the window") + func objectBrowserIsNeverRebuilt() throws { + let host = SidebarHost() + defer { host.tearDown() } + let browser = host.sidebar.objectBrowser + + Self.showNavigator(in: host) + let navigatorSplit = try Self.enclosingSplitView(of: host.sidebar.navigatorController.view) + #expect(browser.view.isDescendant(of: navigatorSplit)) + host.sidebar.setNavigatorEnabled(false) + Self.showNavigator(in: host) + + #expect(host.sidebar.objectBrowser === browser) + #expect(browser.view.window === host.window) + #expect(browser.view.isDescendant(of: host.sidebar.view)) + } + + /// A hidden list that kept the keyboard would take every key the user meant for the window. + @Test("Hiding the navigator, or turning it off, moves the keyboard out of its list") + func hidingTheNavigatorHandsTheKeyboardOn() { + let host = SidebarHost() + defer { host.tearDown() } + let navigator = host.sidebar.navigatorController + + Self.showNavigator(in: host) + host.window.makeFirstResponder(navigator.outlineView) + #expect(Self.isInside(host.window.firstResponder, navigator.view)) + host.sidebar.setRailVisible(false, animated: false) + #expect(!Self.isInside(host.window.firstResponder, navigator.view)) + + Self.showNavigator(in: host) + host.window.makeFirstResponder(navigator.outlineView) + host.sidebar.setNavigatorEnabled(false) + #expect(!Self.isInside(host.window.firstResponder, navigator.view)) + } + + private static func isInside(_ responder: NSResponder?, _ view: NSView) -> Bool { + guard let responder = responder as? NSView else { return false } + return responder.isDescendant(of: view) + } +} + +extension GlobalStateSuites { + @MainActor + struct NavigatorWindowTests { + @Test( + "With the navigator on, the column stands in a window with one connection", + .appSettings { + $0.general.showsConnectionNavigator = true + $0.general.showWorkspaceRail = true + } + ) + func columnStandsWithOneWorkspace() async throws { + let host = NavigatorWindowHost() + defer { host.tearDown() } + + host.split.applyRailVisibility(workspaceCount: 1) + try await waitUntil { host.split.railAllowance > 0 } + + #expect(host.split.isWorkspaceRailVisible) + #expect(host.split.canToggleWorkspaceRail) + let context = host.split.menuValidationContext + #expect(MainSplitViewController.isEnabled( + #selector(MainSplitViewController.toggleWorkspaceRail(_:)), context: context + )) + #expect(!MainSplitViewController.isEnabled( + #selector(MainSplitViewController.showPreviousWorkspace(_:)), context: context + )) + } + + @Test( + "Hide Connections hides the navigator", + .appSettings { + $0.general.showsConnectionNavigator = true + $0.general.showWorkspaceRail = false + } + ) + func showConnectionsHidesTheNavigator() throws { + let host = NavigatorWindowHost() + defer { host.tearDown() } + + host.split.applyRailVisibility(workspaceCount: 1) + + #expect(!host.split.isWorkspaceRailVisible) + let sidebar = try #require(host.split.sidebarSplitItem.viewController as? NavigationSidebarViewController) + #expect(sidebar.showsNavigator) + } + + @Test( + "Turning the navigator off brings the strip's own rule back", + .appSettings { + $0.general.showsConnectionNavigator = true + $0.general.showWorkspaceRail = true + } + ) + func turningTheNavigatorOffBringsTheRailRuleBack() throws { + let host = NavigatorWindowHost() + defer { host.tearDown() } + host.split.applyRailVisibility(workspaceCount: 1) + #expect(host.split.isWorkspaceRailVisible) + + AppSettingsManager.shared.general.showsConnectionNavigator = false + host.split.applyRailVisibility(workspaceCount: 1) + + #expect(!host.split.isWorkspaceRailVisible) + let sidebar = try #require(host.split.sidebarSplitItem.viewController as? NavigationSidebarViewController) + #expect(!sidebar.showsNavigator) + } + } +} + +@MainActor +private struct NavigatorWindowHost { + let window: NSWindow + let split: MainSplitViewController + let workspace: ConnectionWorkspace + + init() { + let connection = TestFixtures.makeConnection(name: "Navigator window") + workspace = ConnectionWorkspace( + connectionId: connection.id, + payload: nil, + autoConnect: false, + payloadConnection: connection, + session: nil, + sessionState: nil, + trailingPaneState: nil, + phase: .connecting + ) + window = TabWindowController.makeEditorWindow() + window.isReleasedWhenClosed = false + split = MainSplitViewController(payload: nil, sessionState: nil, adopting: workspace) + window.contentViewController = split + window.orderFront(nil) + } + + func tearDown() { + window.orderOut(nil) + window.contentViewController = nil + workspace.teardown() + } +} From 421fe112ab5a88d284735dbce3e116b221c588a8 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:18:52 +0700 Subject: [PATCH 022/123] chore(navigator): add the navigator strings to the catalog Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Resources/Localizable.xcstrings | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 00e9b04c64..59fc6730f1 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -82546,6 +82546,9 @@ } } } + }, + "Filter Connections" : { + }, "Filter Databases…" : { "localizations" : { @@ -103712,6 +103715,9 @@ } } } + }, + "List every saved connection beside the database tree" : { + }, "List Favorite Tables" : { "localizations" : { @@ -128078,6 +128084,9 @@ } } } + }, + "Open in another window" : { + }, "Open in Editor" : { "localizations" : { @@ -177552,6 +177561,9 @@ } } } + }, + "Switch To" : { + }, "Switch to Inline Configuration" : { "localizations" : { @@ -206315,6 +206327,9 @@ } } } + }, + "Turns the connections column into a list of every saved connection, in its groups. Double-click one to open it." : { + }, "Two columns are both named “%@”. Rename one, then save again." : { "localizations" : { From aab49dbee5476297e333e2b77597f1bac3ecd0de Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:08:13 +0700 Subject: [PATCH 023/123] fix(navigator): close the New Group sheet on Cancel and after Create The navigator presents the group sheet with AppKit, where SwiftUI's dismiss reaches nothing: Cancel left the sheet open, and Create saved the group but left it open too. The sheet now takes an optional onDismiss closure, and the navigator keeps the hosting controller and closes it through that. The Welcome window passes nothing and keeps using dismiss. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Views/Connection/GroupEditorSheet.swift | 19 ++++- .../ConnectionNavigatorViewController.swift | 26 ++++-- ...nnectionNavigatorViewControllerTests.swift | 79 +++++++++++++++++++ 3 files changed, 115 insertions(+), 9 deletions(-) diff --git a/apple/TablePro/Views/Connection/GroupEditorSheet.swift b/apple/TablePro/Views/Connection/GroupEditorSheet.swift index 77006155c4..0ebee2ea9b 100644 --- a/apple/TablePro/Views/Connection/GroupEditorSheet.swift +++ b/apple/TablePro/Views/Connection/GroupEditorSheet.swift @@ -21,14 +21,19 @@ internal struct GroupEditorSheet: View { /// past the cap. A sheet that dismissed on the attempt left the caller holding the id of a /// group that was never saved. private let onSave: (ConnectionGroupFields) throws -> Void + /// Set by an AppKit presenter. `dismiss` reaches only a SwiftUI presentation, so a sheet a view + /// controller presents closes through this instead. The Welcome window leaves it nil. + private let onDismiss: (() -> Void)? internal init( mode: GroupEditorMode, groups: [ConnectionGroup], + onDismiss: (() -> Void)? = nil, onSave: @escaping (ConnectionGroupFields) throws -> Void ) { self.mode = mode self.groups = groups + self.onDismiss = onDismiss self.onSave = onSave switch mode { case .create(let parentId): @@ -83,7 +88,7 @@ internal struct GroupEditorSheet: View { HStack { Button(String(localized: "Cancel")) { - dismiss() + close() } .keyboardShortcut(.cancelAction) @@ -97,7 +102,7 @@ internal struct GroupEditorSheet: View { .frame(width: 300) .onChange(of: draft) { _ in errorMessage = nil } .onExitCommand { - dismiss() + close() } } @@ -143,9 +148,17 @@ internal struct GroupEditorSheet: View { saved.name = trimmedName do { try onSave(saved) - dismiss() + close() } catch { errorMessage = error.localizedDescription } } + + private func close() { + if let onDismiss { + onDismiss() + } else { + dismiss() + } + } } diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift index b82a81421f..3946ba68a6 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift @@ -89,6 +89,7 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear private var rowSizePreference = AppSettingsManager.shared.general.sidebarRowSize private var modelCancellables: Set = [] private var rowSizeObservation: AnyCancellable? + private var groupSheet: NSViewController? internal init(model: ConnectionNavigatorModel = ConnectionNavigatorModel()) { self.model = model @@ -482,12 +483,25 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear presentNewGroupSheet(parentId: parentId) } - /// The group sheet the Welcome window uses, saving through the same store. - private func presentNewGroupSheet(parentId: UUID?) { - let sheet = GroupEditorSheet(mode: .create(parentId: parentId), groups: model.groups) { [weak self] draft in - try self?.model.createGroup(draft) - } - presentAsSheet(sheet) + /// The group sheet the Welcome window uses, saving through the same store. SwiftUI's `dismiss` + /// does not reach a sheet AppKit presents, so the sheet closes through the controller kept here. + internal func presentNewGroupSheet(parentId: UUID?) { + guard groupSheet == nil else { return } + let sheet = GroupEditorSheet( + mode: .create(parentId: parentId), + groups: model.groups, + onDismiss: { [weak self] in self?.dismissGroupSheet() }, + onSave: { [weak self] draft in try self?.model.createGroup(draft) } + ) + let controller = NSHostingController(rootView: sheet) + groupSheet = controller + presentAsSheet(controller) + } + + private func dismissGroupSheet() { + guard let groupSheet else { return } + self.groupSheet = nil + dismiss(groupSheet) } // MARK: - Data Source diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift index cc5d33c557..7faa94dc04 100644 --- a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift @@ -6,6 +6,7 @@ import AppKit import Foundation @testable import TablePro +import TableProTestSupport import Testing @MainActor @@ -21,6 +22,9 @@ struct ConnectionNavigatorViewControllerTests { let window: NSWindow func tearDown() { + for sheet in controller.presentedViewControllers ?? [] { + controller.dismiss(sheet) + } window.orderOut(nil) window.contentViewController = nil } @@ -163,6 +167,81 @@ struct ConnectionNavigatorViewControllerTests { #expect(outline.selectedRow == shownRow) } + // MARK: - New Group sheet + + /// Escape and Return are the Cancel and Create buttons' own shortcuts, so a key equivalent runs + /// the button's action. SwiftUI builds no accessibility tree in the test host to press through. + private static func keyEquivalent(_ characters: String, keyCode: UInt16, in sheet: NSViewController) throws -> NSEvent { + let window = try #require(sheet.view.window) + return try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: characters, + charactersIgnoringModifiers: characters, + isARepeat: false, + keyCode: keyCode + )) + } + + /// Typed through the field editor, the way a key press edits it, so SwiftUI's binding hears it. + private static func type(_ text: String, intoFieldOf sheet: NSViewController) throws { + let field = try #require(editableTextField(in: sheet.view)) + let window = try #require(sheet.view.window) + #expect(window.makeFirstResponder(field)) + let editor = try #require(field.currentEditor() as? NSTextView) + editor.insertText(text, replacementRange: editor.selectedRange()) + } + + private static func editableTextField(in view: NSView) -> NSTextField? { + if let field = view as? NSTextField, field.isEditable { return field } + for subview in view.subviews { + if let field = editableTextField(in: subview) { return field } + } + return nil + } + + private func presentedSheet(of controller: ConnectionNavigatorViewController) throws -> NSViewController { + let sheet = try #require(controller.presentedViewControllers?.first) + sheet.view.layoutSubtreeIfNeeded() + return sheet + } + + /// The sheet is SwiftUI hosted in an AppKit sheet, where SwiftUI's own dismiss reaches nothing. + @Test("Cancel closes the New Group sheet") + func cancelClosesNewGroupSheet() async throws { + fixture.save([DatabaseConnection(name: "prod")]) + let hosted = host() + defer { hosted.tearDown() } + hosted.controller.presentNewGroupSheet(parentId: nil) + let sheet = try presentedSheet(of: hosted.controller) + let escape = try Self.keyEquivalent("\u{1b}", keyCode: 53, in: sheet) + + #expect(sheet.view.performKeyEquivalent(with: escape)) + try await waitUntil(timeout: .seconds(2)) { hosted.controller.presentedViewControllers?.isEmpty ?? true } + #expect(fixture.groupStorage.loadGroups().isEmpty) + } + + @Test("Create saves the group and closes the New Group sheet") + func createSavesAndClosesNewGroupSheet() async throws { + fixture.save([DatabaseConnection(name: "prod")]) + let hosted = host() + defer { hosted.tearDown() } + hosted.controller.presentNewGroupSheet(parentId: nil) + let sheet = try presentedSheet(of: hosted.controller) + try Self.type("Reports", intoFieldOf: sheet) + let returnKey = try Self.keyEquivalent("\r", keyCode: 36, in: sheet) + + /// Create turns on once SwiftUI has read the typed name, which it does on its own schedule. + try await waitUntil(timeout: .seconds(2)) { sheet.view.performKeyEquivalent(with: returnKey) } + try await waitUntil(timeout: .seconds(2)) { !fixture.groupStorage.loadGroups().isEmpty } + #expect(fixture.groupStorage.loadGroups().map(\.name) == ["Reports"]) + try await waitUntil(timeout: .seconds(2)) { hosted.controller.presentedViewControllers?.isEmpty ?? true } + } + /// A connection opened from a file or a link is hosted without ever being saved. @Test("A shown connection the library does not hold selects nothing") func unsavedShownConnectionSelectsNothing() { From a0dddf76b30cdcc3999946bd096651575c1cf0a9 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:31:06 +0700 Subject: [PATCH 024/123] test(navigator): click and double click a connection through the list A list holding production servers must not dial one on a stray click. These drive the outline's own action and double action with real mouse events, through an injected router: a single click on a connection this window does not host routes nothing, and a double click opens it. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- ...nnectionNavigatorViewControllerTests.swift | 85 ++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift index 7faa94dc04..950772f1e9 100644 --- a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift @@ -30,14 +30,23 @@ struct ConnectionNavigatorViewControllerTests { } } - private func host() -> Hosted { + /// The headless test host never gives a window the keyboard, and `NSTableView` tracks a click + /// only in the key window, so a test that clicks says the window is key. + private final class TestWindow: NSWindow { + var claimsKey = false + + override var isKeyWindow: Bool { claimsKey || super.isKeyWindow } + } + + private func host(claimingKey: Bool = false) -> Hosted { let controller = ConnectionNavigatorViewController(model: fixture.makeModel()) - let window = NSWindow( + let window = TestWindow( contentRect: NSRect(x: 0, y: 0, width: 260, height: 500), styleMask: [.titled], backing: .buffered, defer: false ) + window.claimsKey = claimingKey window.isReleasedWhenClosed = false window.contentViewController = controller window.orderFront(nil) @@ -167,6 +176,78 @@ struct ConnectionNavigatorViewControllerTests { #expect(outline.selectedRow == shownRow) } + // MARK: - Clicks + + /// NSTableView tracks a press until the mouse-up, so the mouse-up waits in the queue first. A + /// double click is a second press that AppKit reports with a click count of 2. + private static func click(row: Int, in hosted: Hosted, clickCount: Int = 1) throws { + let outline = hosted.controller.outlineView + let rect = outline.rect(ofRow: row) + let location = outline.convert(NSPoint(x: rect.midX, y: rect.midY), to: nil) + func event(_ type: NSEvent.EventType) throws -> NSEvent { + try #require(NSEvent.mouseEvent( + with: type, + location: location, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: hosted.window.windowNumber, + context: nil, + eventNumber: 0, + clickCount: clickCount, + pressure: type == .leftMouseDown ? 1 : 0 + )) + } + let up = try event(.leftMouseUp) + let down = try event(.leftMouseDown) + NSApp.postEvent(up, atStart: true) + outline.mouseDown(with: down) + _ = NSApp.nextEvent(matching: .leftMouseUp, until: .distantPast, inMode: .default, dequeue: true) + } + + /// A window showing one connection, beside saved connections it does not host. + private func hostShowingOne(beside names: [String]) -> (hosted: Hosted, shown: UUID, closed: [UUID]) { + let shown = DatabaseConnection(name: "shown") + let closed = names.map { DatabaseConnection(name: $0) } + fixture.save([shown] + closed) + fixture.host.hosted = [shown.id] + fixture.host.selected = shown.id + return (host(claimingKey: true), shown.id, closed.map(\.id)) + } + + /// A list holding production servers must not dial one because the pointer slipped. + @Test("A single click on a connection this window does not host routes nothing") + func singleClickOnClosedConnectionRoutesNothing() async throws { + let (hosted, shown, closed) = hostShowingOne(beside: ["clicked", "opened"]) + defer { hosted.tearDown() } + let clickedRow = hosted.controller.row(for: .connection(closed[0])) + let openedRow = hosted.controller.row(for: .connection(closed[1])) + try #require(clickedRow >= 0 && openedRow >= 0) + + try Self.click(row: clickedRow, in: hosted) + #expect(hosted.controller.outlineView.selectedRow == clickedRow) + /// An open the click had queued would land before this one, which is queued after it. + try Self.click(row: openedRow, in: hosted) + try Self.click(row: openedRow, in: hosted, clickCount: 2) + try await waitUntil(timeout: .seconds(2)) { !fixture.router.openedConnections.isEmpty } + + #expect(fixture.router.openedConnections == [closed[1]]) + #expect(fixture.host.selected == shown) + } + + @Test("A double click on a connection this window does not host opens it") + func doubleClickOnClosedConnectionRoutesOpen() async throws { + let (hosted, _, closed) = hostShowingOne(beside: ["closed"]) + defer { hosted.tearDown() } + let row = hosted.controller.row(for: .connection(closed[0])) + try #require(row >= 0) + + try Self.click(row: row, in: hosted) + try Self.click(row: row, in: hosted, clickCount: 2) + + try await waitUntil(timeout: .seconds(2)) { !fixture.router.openedConnections.isEmpty } + #expect(fixture.router.openedConnections == [closed[0]]) + } + // MARK: - New Group sheet /// Escape and Return are the Cancel and Create buttons' own shortcuts, so a key equivalent runs From 493109d3200000fb20dc32c878ee958ab68756e3 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:51:31 +0700 Subject: [PATCH 025/123] fix(navigator): open the selected connection on Return NSTableView moves the selection for the arrow keys but never turns Return into insertNewline(_:), so Return in the list did nothing: the override that opens the connection was never reached. The list now sends Return and Enter through the key bindings, as the data grid's table does. The test presses Return through the list's keyDown, with an injected router. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorViewController.swift | 12 +++++++ ...nnectionNavigatorViewControllerTests.swift | 35 ++++++++++++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift index 3946ba68a6..892940cf95 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift @@ -31,6 +31,18 @@ internal final class ConnectionNavigatorOutlineView: NSOutlineView { super.mouseDown(with: event) } + /// `NSTableView` moves the selection for the arrow keys itself but never turns Return into + /// `insertNewline(_:)`, so Return and Enter go through the key bindings, as the data grid's + /// table sends them. + override internal func keyDown(with event: NSEvent) { + switch event.specialKey { + case .carriageReturn?, .enter?, .newline?: + interpretKeyEvents([event]) + default: + super.keyDown(with: event) + } + } + override internal func insertNewline(_ sender: Any?) { navigator?.activateSelection() } diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift index 950772f1e9..449c950d26 100644 --- a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift @@ -176,7 +176,7 @@ struct ConnectionNavigatorViewControllerTests { #expect(outline.selectedRow == shownRow) } - // MARK: - Clicks + // MARK: - Clicks and Return /// NSTableView tracks a press until the mouse-up, so the mouse-up waits in the queue first. A /// double click is a second press that AppKit reports with a click count of 2. @@ -204,6 +204,23 @@ struct ConnectionNavigatorViewControllerTests { _ = NSApp.nextEvent(matching: .leftMouseUp, until: .distantPast, inMode: .default, dequeue: true) } + /// Through the list's key handling, which turns Return into `insertNewline(_:)`. + private static func pressReturn(in hosted: Hosted) throws { + let event = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: hosted.window.windowNumber, + context: nil, + characters: "\r", + charactersIgnoringModifiers: "\r", + isARepeat: false, + keyCode: 36 + )) + hosted.controller.outlineView.keyDown(with: event) + } + /// A window showing one connection, beside saved connections it does not host. private func hostShowingOne(beside names: [String]) -> (hosted: Hosted, shown: UUID, closed: [UUID]) { let shown = DatabaseConnection(name: "shown") @@ -248,6 +265,22 @@ struct ConnectionNavigatorViewControllerTests { #expect(fixture.router.openedConnections == [closed[0]]) } + @Test("Return on a connection this window does not host opens it") + func returnOnClosedConnectionRoutesOpen() async throws { + let (hosted, _, closed) = hostShowingOne(beside: ["closed"]) + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + let row = hosted.controller.row(for: .connection(closed[0])) + try #require(row >= 0) + hosted.window.makeFirstResponder(outline) + outline.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) + + try Self.pressReturn(in: hosted) + + try await waitUntil(timeout: .seconds(2)) { !fixture.router.openedConnections.isEmpty } + #expect(fixture.router.openedConnections == [closed[0]]) + } + // MARK: - New Group sheet /// Escape and Return are the Cancel and Create buttons' own shortcuts, so a key equivalent runs From d4fa4831f792161abd0a5455374313be16f2adba Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:51:31 +0700 Subject: [PATCH 026/123] fix(navigator): keep a subgroup closed when its parent reopens Reopening a group reapplied its subgroups' state from rows built before the user changed them, so a subgroup the user had closed opened again. The outline now reads the model's live set; a filter's choice still comes from the rows it built. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorModel.swift | 6 +++ .../ConnectionNavigatorViewController.swift | 2 +- ...nnectionNavigatorViewControllerTests.swift | 51 +++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift index 5dd51814ea..a4184afbd8 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift @@ -176,6 +176,12 @@ internal final class ConnectionNavigatorModel: ObservableObject { return (statuses, placements) } + /// Whether a group is open now. A row's own flag is what it was when the rows were built, and + /// the user opens and closes groups without a rebuild. A filter's choice lasts until it changes. + internal func isGroupExpanded(_ group: ConnectionNavigatorGroupRow) -> Bool { + isFiltering ? group.isExpanded : expandedGroupIds.contains(group.id) + } + /// The groups a filter opens are the filter's, so a user expanding or collapsing one while it /// runs does not overwrite what they chose before typing. internal func setGroupExpanded(_ id: UUID, _ expanded: Bool) { diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift index 892940cf95..807a37208e 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift @@ -325,7 +325,7 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear private func applyExpansion(to items: [ConnectionNavigatorOutlineItem]) { for item in items { guard case .group(let group) = item.row, !item.children.isEmpty else { continue } - guard group.isExpanded else { + guard model.isGroupExpanded(group) else { outlineView.collapseItem(item) continue } diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift index 449c950d26..62834bd6d7 100644 --- a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift @@ -176,6 +176,57 @@ struct ConnectionNavigatorViewControllerTests { #expect(outline.selectedRow == shownRow) } + /// The rows say how a group stood when they were built, and the user opens and closes groups + /// without a rebuild. + @Test("A subgroup the user opened is still open after its parent is closed and reopened") + func subgroupStaysOpenThroughItsParent() throws { + let parent = ConnectionGroup(name: "Parent") + let child = ConnectionGroup(name: "Child", parentId: parent.id) + try fixture.groupStorage.addGroup(parent) + try fixture.groupStorage.addGroup(child) + let inside = DatabaseConnection(name: "inside", groupId: child.id) + fixture.save([inside]) + fixture.expansionStore.save([parent.id]) + let hosted = host() + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + let parentItem = outline.item(atRow: hosted.controller.row(for: .group(parent.id))) + let childItem = outline.item(atRow: hosted.controller.row(for: .group(child.id))) + try #require(parentItem != nil && childItem != nil) + outline.expandItem(childItem) + outline.collapseItem(parentItem) + + outline.expandItem(parentItem) + + #expect(outline.isItemExpanded(childItem)) + #expect(hosted.controller.row(for: .connection(inside.id)) >= 0) + } + + @Test("A subgroup the user closed is still closed after its parent is closed and reopened") + func subgroupStaysClosedThroughItsParent() throws { + let parent = ConnectionGroup(name: "Parent") + let child = ConnectionGroup(name: "Child", parentId: parent.id) + try fixture.groupStorage.addGroup(parent) + try fixture.groupStorage.addGroup(child) + let inside = DatabaseConnection(name: "inside", groupId: child.id) + fixture.save([inside]) + fixture.expansionStore.save([parent.id, child.id]) + let hosted = host() + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + let parentItem = outline.item(atRow: hosted.controller.row(for: .group(parent.id))) + let childItem = outline.item(atRow: hosted.controller.row(for: .group(child.id))) + try #require(parentItem != nil && childItem != nil) + try #require(outline.isItemExpanded(childItem)) + outline.collapseItem(childItem) + outline.collapseItem(parentItem) + + outline.expandItem(parentItem) + + #expect(!outline.isItemExpanded(childItem)) + #expect(hosted.controller.row(for: .connection(inside.id)) == -1) + } + // MARK: - Clicks and Return /// NSTableView tracks a press until the mouse-up, so the mouse-up waits in the queue first. A From e7dee155799409536c2fec0feac11c120e25e286 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:51:31 +0700 Subject: [PATCH 027/123] fix(navigator): keep the groups another window opened Each window's navigator saved its whole copy of the open groups, so two windows wiped each other's choices. Opening, closing or creating a group now loads what is stored, changes it and saves it. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorModel.swift | 25 ++++++++--- .../ConnectionNavigatorModelTests.swift | 42 +++++++++++++++++++ 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift index a4184afbd8..886c2865b8 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorModel.swift @@ -191,7 +191,22 @@ internal final class ConnectionNavigatorModel: ObservableObject { } else { expandedGroupIds.remove(id) } - environment.expansionStore.save(expandedGroupIds) + updateStoredExpansion { stored in + if expanded { + stored.insert(id) + } else { + stored.remove(id) + } + } + } + + /// Every window's navigator saves to the same key, so a change goes onto what is stored now. + /// Saving this window's own copy wiped the groups another window had opened since it loaded. + private func updateStoredExpansion(_ change: (inout Set) -> Void) { + let store = environment.expansionStore + var stored = store.load(keeping: Set(environment.groupStorage.loadGroups().map(\.id))) + change(&stored) + store.save(stored) } // MARK: - Interaction @@ -319,11 +334,9 @@ internal final class ConnectionNavigatorModel: ObservableObject { parentId: fields.parentId ) try environment.groupStorage.addGroup(group) - expandedGroupIds.insert(group.id) - if let parentId = fields.parentId { - expandedGroupIds.insert(parentId) - } - environment.expansionStore.save(expandedGroupIds) + let opened = Set([group.id] + [fields.parentId].compactMap { $0 }) + expandedGroupIds.formUnion(opened) + updateStoredExpansion { $0.formUnion(opened) } rebuild() } } diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift index de555fb73f..57824469ad 100644 --- a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorModelTests.swift @@ -116,6 +116,48 @@ struct ConnectionNavigatorModelTests { #expect(fixture.expansionStore.load(keeping: [parent.id, child.id]) == [parent.id, child.id]) } + /// Each window holds a navigator of its own, and they share one stored set. + @Test("Two navigators keep the groups each other opened") + func twoNavigatorsKeepEachOthersExpansion() throws { + let first = ConnectionGroup(name: "First") + let second = ConnectionGroup(name: "Second") + try fixture.groupStorage.addGroup(first) + try fixture.groupStorage.addGroup(second) + let left = fixture.makeModel() + let right = fixture.makeModel() + left.start() + right.start() + defer { + left.stop() + right.stop() + } + + left.setGroupExpanded(first.id, true) + right.setGroupExpanded(second.id, true) + + #expect(fixture.expansionStore.load(keeping: [first.id, second.id]) == [first.id, second.id]) + } + + @Test("A group made in one navigator keeps the groups another one opened") + func createdGroupKeepsAnotherNavigatorsExpansion() throws { + let opened = ConnectionGroup(name: "Opened") + try fixture.groupStorage.addGroup(opened) + let left = fixture.makeModel() + let right = fixture.makeModel() + left.start() + right.start() + defer { + left.stop() + right.stop() + } + + left.setGroupExpanded(opened.id, true) + try right.createGroup(ConnectionGroupFields(name: "Made")) + + let made = try #require(fixture.groupStorage.loadGroups().first { $0.name == "Made" }) + #expect(fixture.expansionStore.load(keeping: [opened.id, made.id]) == [opened.id, made.id]) + } + @Test("The library reads empty until it holds a connection") func libraryEmptyTracksConnections() { let model = fixture.makeModel() From c9942f84d5615026521712b6c2d141c8eaba442d Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:51:31 +0700 Subject: [PATCH 028/123] fix(navigator): leave the list where it was scrolled on a rebuild The list rebuilds on every connect, since a connect records a recent connection, and each rebuild scrolled back to the selected row. Only a selection that moved scrolls now. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorViewController.swift | 11 +++++++++ ...nnectionNavigatorViewControllerTests.swift | 23 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift index 807a37208e..9daf82e818 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift @@ -268,6 +268,7 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear selectShownConnection() } isReloading = false + scrollToSelection(ifMovedFrom: previous) applyEmptyState() } @@ -370,7 +371,9 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear internal func refreshSelection() { guard isViewLoaded else { return } model.refreshPresentation() + let previous = selectedRowID selectShownConnection() + scrollToSelection(ifMovedFrom: previous) } /// A connection the library does not hold, one opened from a file or a link, leaves nothing @@ -389,6 +392,13 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear return } outlineView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) + } + + /// The list rebuilds on every connect, so only a selection that moved brings its row into view. + /// The same row staying selected leaves the list where the user scrolled it. + private func scrollToSelection(ifMovedFrom previous: ConnectionNavigatorRowID?) { + let row = outlineView.selectedRow + guard row >= 0, selectedRowID != previous else { return } outlineView.scrollRowToVisible(row) } @@ -466,6 +476,7 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear view.window?.makeFirstResponder(outlineView) if outlineView.selectedRow < 0 { select(0) + outlineView.scrollRowToVisible(0) } return true } diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift index 62834bd6d7..4db4c76e69 100644 --- a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift @@ -227,6 +227,29 @@ struct ConnectionNavigatorViewControllerTests { #expect(hosted.controller.row(for: .connection(inside.id)) == -1) } + /// The list rebuilds on every connect, since a connect records a recent connection. + @Test("A rebuild leaves the list where the user scrolled it") + func rebuildKeepsTheScrollPosition() throws { + let connections = (0..<60).map { DatabaseConnection(name: String(format: "connection %02d", $0)) } + fixture.save(connections) + let shown = try #require(connections.last) + fixture.host.hosted = [shown.id] + fixture.host.selected = shown.id + let hosted = host() + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + let clipView = try #require(outline.enclosingScrollView?.contentView) + let shownRow = hosted.controller.row(for: .connection(shown.id)) + try #require(outline.selectedRow == shownRow) + clipView.scroll(to: .zero) + try #require(!clipView.documentVisibleRect.intersects(outline.rect(ofRow: shownRow))) + + hosted.controller.model.rebuild() + + #expect(outline.selectedRow == shownRow) + #expect(clipView.bounds.origin == .zero) + } + // MARK: - Clicks and Return /// NSTableView tracks a press until the mouse-up, so the mouse-up waits in the queue first. A From 7d1ca58ab9f8ef0650699c579b660f35e4e40ca9 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:51:31 +0700 Subject: [PATCH 029/123] fix(navigator): keep the keyboard in the object browser when the setting flips Turning the navigator on or off moves the object browser into another split, which takes it out of the window for a moment, and AppKit gave the keyboard to the window. The view that held it, or the field being edited with its selection, takes it back once the browser is in place. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../NavigationSidebarViewController.swift | 35 ++++++++++++++++ .../NavigationSidebarNavigatorTests.swift | 42 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift b/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift index 0151284546..5c046fdb19 100644 --- a/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/NavigationSidebarViewController.swift @@ -171,6 +171,7 @@ internal final class NavigationSidebarViewController: NSViewController { } showsNavigator = enabled applyColumnShown() + let browserFocus = objectBrowserFocus() if enabled { buildNavigatorSplitIfNeeded() uninstall(splitController) @@ -181,9 +182,43 @@ internal final class NavigationSidebarViewController: NSViewController { railSplitHost.show(nil) install(splitController) } + restore(browserFocus) onRailWidthChange?() } + private struct BrowserFocus { + let holder: NSView + let selection: NSRange? + } + + /// Moving the object browser to the other split takes it out of the window for a moment, and + /// AppKit gives the keyboard to the window when a view holding it leaves, so the view that held + /// it is noted first. A field being edited is held by its field editor, which leaves with the + /// edit, so the field and its selection are noted instead. + private func objectBrowserFocus() -> BrowserFocus? { + guard let window = view.window, let responder = window.firstResponder as? NSView, + responder.window === window + else { return nil } + let focus: BrowserFocus + if let editor = responder as? NSTextView, editor.isFieldEditor, let field = editor.delegate as? NSView { + focus = BrowserFocus(holder: field, selection: editor.selectedRange()) + } else { + focus = BrowserFocus(holder: responder, selection: nil) + } + return focus.holder.isDescendant(of: objectBrowser.view) ? focus : nil + } + + private func restore(_ focus: BrowserFocus?) { + guard let focus, let window = view.window, focus.holder.window === window, + objectBrowserFocus()?.holder !== focus.holder, + window.makeFirstResponder(focus.holder) + else { return } + if let selection = focus.selection, let editor = window.firstResponder as? NSTextView, + NSMaxRange(selection) <= (editor.string as NSString).length { + editor.setSelectedRange(selection) + } + } + private func buildNavigatorSplitIfNeeded() { guard !isNavigatorSplitBuilt else { return } isNavigatorSplitBuilt = true diff --git a/apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift b/apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift index 31117cf127..9bb0158f23 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/NavigationSidebarNavigatorTests.swift @@ -134,6 +134,48 @@ struct NavigationSidebarNavigatorTests { #expect(!Self.isInside(host.window.firstResponder, navigator.view)) } + /// Stands in for the object list, which takes the keyboard the way any list does. + private final class FocusableView: NSView { + override var acceptsFirstResponder: Bool { true } + } + + /// Turning the setting on or off moves the object browser into another split, which takes it + /// out of the window for a moment, and AppKit hands the keyboard to the window when a view + /// holding it leaves. + @Test("Turning the navigator on and off leaves the keyboard in the object browser") + func togglingTheNavigatorKeepsTheBrowserFocused() throws { + let host = SidebarHost() + defer { host.tearDown() } + let list = FocusableView(frame: NSRect(x: 0, y: 0, width: 100, height: 100)) + host.sidebar.objectBrowser.view.addSubview(list) + host.window.makeFirstResponder(list) + try #require(host.window.firstResponder === list) + + host.sidebar.setNavigatorEnabled(true) + #expect(host.window.firstResponder === list) + + host.sidebar.setNavigatorEnabled(false) + #expect(host.window.firstResponder === list) + } + + /// A field being edited holds the keyboard through its field editor, which leaves with the edit. + @Test("Turning the navigator on and off keeps a field in the object browser editing") + func togglingTheNavigatorKeepsAFieldEditing() throws { + let host = SidebarHost() + defer { host.tearDown() } + let field = NSTextField(string: "orders") + field.frame = NSRect(x: 0, y: 0, width: 120, height: 22) + host.sidebar.objectBrowser.view.addSubview(field) + host.window.makeFirstResponder(field) + try #require(field.currentEditor() != nil) + + host.sidebar.setNavigatorEnabled(true) + #expect(field.currentEditor() != nil) + + host.sidebar.setNavigatorEnabled(false) + #expect(field.currentEditor() != nil) + } + private static func isInside(_ responder: NSResponder?, _ view: NSView) -> Bool { guard let responder = responder as? NSView else { return false } return responder.isDescendant(of: view) From 304c343a85bd34b4deb31d3a9fe0a99097f08341 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:51:31 +0700 Subject: [PATCH 030/123] fix(navigator): reveal the shown connection inside closed groups The connection this window shows was neither visible nor selected when it sat in a closed group. Its groups now open in the outline only, not saved as the user's choice, when the list first loads and when the window switches connection. A group the user then closes stays closed. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigatorViewController.swift | 33 +++++++- ...nnectionNavigatorViewControllerTests.swift | 82 +++++++++++++++++++ 2 files changed, 114 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift index 9daf82e818..46f1ae51df 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift @@ -96,6 +96,11 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear private var items: [ConnectionNavigatorRowID: ConnectionNavigatorOutlineItem] = [:] private var rootItems: [ConnectionNavigatorOutlineItem] = [] private var isApplyingExpansion = false + /// Groups opened to show the connection on screen. The outline holds them open and the model + /// never hears of them, since a reveal is not the user choosing to open a group. + private var revealedGroupIds: Set = [] + /// Each shown connection is revealed once, so a group the user closes over it stays closed. + private var revealedConnectionId: UUID? private var isReloading = false private var reportedWidth: CGFloat = 0 private var rowSizePreference = AppSettingsManager.shared.general.sidebarRowSize @@ -262,6 +267,7 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear isReloading = true outlineView.reloadData() applyExpansion() + revealShownConnection() if let previous, row(for: previous) >= 0 { select(row(for: previous)) } else { @@ -326,7 +332,7 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear private func applyExpansion(to items: [ConnectionNavigatorOutlineItem]) { for item in items { guard case .group(let group) = item.row, !item.children.isEmpty else { continue } - guard model.isGroupExpanded(group) else { + guard model.isGroupExpanded(group) || revealedGroupIds.contains(group.id) else { outlineView.collapseItem(item) continue } @@ -352,9 +358,33 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear guard !isApplyingExpansion, !isReloading, let item = notification.userInfo?["NSObject"] as? ConnectionNavigatorOutlineItem, case .group(let id) = item.id else { return } + revealedGroupIds.remove(id) model.setGroupExpanded(id, false) } + /// Opens the groups above the connection this window shows, in the outline only. A connection + /// the list does not hold yet, such as one a filter hides, is revealed once it appears. + private func revealShownConnection() { + guard let shown = model.shownConnectionId, shown != revealedConnectionId, + let groupIds = groupIds(above: .connection(shown), in: rootItems) + else { return } + revealedConnectionId = shown + revealedGroupIds.formUnion(groupIds) + applyExpansion() + } + + /// The groups holding a row, outermost first, or nil when the list does not hold the row. + private func groupIds(above id: ConnectionNavigatorRowID, in items: [ConnectionNavigatorOutlineItem]) -> [UUID]? { + for item in items { + if item.id == id { return [] } + guard case .group(let groupId) = item.id, + let inner = groupIds(above: id, in: item.children) + else { continue } + return [groupId] + inner + } + return nil + } + // MARK: - Selection private var selectedRowID: ConnectionNavigatorRowID? { @@ -372,6 +402,7 @@ internal final class ConnectionNavigatorViewController: NSViewController, NSSear guard isViewLoaded else { return } model.refreshPresentation() let previous = selectedRowID + revealShownConnection() selectShownConnection() scrollToSelection(ifMovedFrom: previous) } diff --git a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift index 4db4c76e69..72d2a671d3 100644 --- a/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift +++ b/apple/TableProTests/Views/ConnectionNavigator/ConnectionNavigatorViewControllerTests.swift @@ -250,6 +250,88 @@ struct ConnectionNavigatorViewControllerTests { #expect(clipView.bounds.origin == .zero) } + // MARK: - Revealing the shown connection + + @Test("The list opens with the shown connection selected, even inside closed groups") + func shownConnectionInClosedGroupsIsRevealedOnLoad() throws { + let outer = ConnectionGroup(name: "Outer") + let inner = ConnectionGroup(name: "Inner", parentId: outer.id) + try fixture.groupStorage.addGroup(outer) + try fixture.groupStorage.addGroup(inner) + let shown = DatabaseConnection(name: "shown", groupId: inner.id) + fixture.save([shown]) + fixture.host.hosted = [shown.id] + fixture.host.selected = shown.id + + let hosted = host() + defer { hosted.tearDown() } + + let row = hosted.controller.row(for: .connection(shown.id)) + #expect(row >= 0) + #expect(hosted.controller.outlineView.selectedRow == row) + /// Opened to show the connection, which is not the user choosing to open them. + #expect(fixture.expansionStore.load(keeping: [outer.id, inner.id]).isEmpty) + } + + @Test("Switching to a connection inside a closed group reveals and selects it") + func switchingRevealsTheShownConnection() throws { + let group = ConnectionGroup(name: "Group") + try fixture.groupStorage.addGroup(group) + let first = DatabaseConnection(name: "first") + let second = DatabaseConnection(name: "second", groupId: group.id) + fixture.save([first, second]) + fixture.host.hosted = [first.id, second.id] + fixture.host.selected = first.id + let hosted = host() + defer { hosted.tearDown() } + try #require(hosted.controller.row(for: .connection(second.id)) == -1) + + fixture.host.selected = second.id + hosted.controller.refreshSelection() + + let row = hosted.controller.row(for: .connection(second.id)) + #expect(row >= 0) + #expect(hosted.controller.outlineView.selectedRow == row) + #expect(fixture.expansionStore.load(keeping: [group.id]).isEmpty) + } + + /// The list rebuilds on every connect, and reapplying the saved expansion closed the group again. + @Test("A group opened to show the connection stays open through a rebuild") + func revealedGroupStaysOpenThroughARebuild() throws { + let group = ConnectionGroup(name: "Group") + try fixture.groupStorage.addGroup(group) + let shown = DatabaseConnection(name: "shown", groupId: group.id) + fixture.save([shown]) + fixture.host.hosted = [shown.id] + fixture.host.selected = shown.id + let hosted = host() + defer { hosted.tearDown() } + + hosted.controller.model.rebuild() + + let row = hosted.controller.row(for: .connection(shown.id)) + #expect(row >= 0) + #expect(hosted.controller.outlineView.selectedRow == row) + } + + @Test("A group the user closes after a reveal stays closed through a rebuild") + func closedRevealedGroupStaysClosed() throws { + let group = ConnectionGroup(name: "Group") + try fixture.groupStorage.addGroup(group) + let shown = DatabaseConnection(name: "shown", groupId: group.id) + fixture.save([shown]) + fixture.host.hosted = [shown.id] + fixture.host.selected = shown.id + let hosted = host() + defer { hosted.tearDown() } + let outline = hosted.controller.outlineView + outline.collapseItem(outline.item(atRow: hosted.controller.row(for: .group(group.id)))) + + hosted.controller.model.rebuild() + + #expect(hosted.controller.row(for: .connection(shown.id)) == -1) + } + // MARK: - Clicks and Return /// NSTableView tracks a press until the mouse-up, so the mouse-up waits in the queue first. A From f6ba1ef113707f35028268113a577eae06dcf2dd Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 22:54:43 +0700 Subject: [PATCH 031/123] feat(mysql): list each table's engine, create time and update time Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MySQLPluginDriver+DatabaseMetadata.swift | 3 ++ .../MySQLDatabaseMetadataTests.swift | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift b/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift index 9e2c25512d..9137b2e794 100644 --- a/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift +++ b/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift @@ -99,6 +99,9 @@ internal extension MySQLPluginDriver { CONCAT(ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2), ' MB') as total_size, CONCAT(ROUND(DATA_LENGTH / 1024 / 1024, 2), ' MB') as data_size, CONCAT(ROUND(INDEX_LENGTH / 1024 / 1024, 2), ' MB') as index_size, + ENGINE as engine, + CREATE_TIME as create_time, + UPDATE_TIME as update_time, TABLE_COMMENT as comment FROM information_schema.TABLES WHERE TABLE_SCHEMA = '\(effectiveSchemaLiteral(schema))' diff --git a/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift b/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift index 0ce0e79f80..d0fd8b157e 100644 --- a/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift +++ b/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift @@ -46,4 +46,32 @@ struct MySQLDatabaseMetadataTests { #expect(metadata.indexSize == Int64.max) #expect(metadata.totalSize == Int64.max) } + + private func unconnectedDriver() -> MySQLPluginDriver { + MySQLPluginDriver(config: DriverConnectionConfig( + host: "", port: 0, username: "", password: "", database: "", additionalFields: [:] + )) + } + + @Test("The table listing adds each table's engine, create time and update time after its index size") + func listingCarriesEngineAndTimes() throws { + let statement = try #require(unconnectedDriver().allTablesMetadataSQL(schema: "shop")) + + let indexSize = try #require(statement.range(of: "as index_size")) + let engine = try #require(statement.range(of: "ENGINE as engine")) + let created = try #require(statement.range(of: "CREATE_TIME as create_time")) + let updated = try #require(statement.range(of: "UPDATE_TIME as update_time")) + let comment = try #require(statement.range(of: "TABLE_COMMENT as comment")) + #expect(indexSize.upperBound < engine.lowerBound) + #expect(engine.upperBound < created.lowerBound) + #expect(created.upperBound < updated.lowerBound) + #expect(updated.upperBound < comment.lowerBound) + } + + // SHOW TABLE STATUS already answers Engine, Create_time and Update_time. + @Test("A server without the catalog keeps its SHOW TABLE STATUS listing as it was") + func tableStatusFallbackIsUnchanged() { + #expect(MySQLPluginDriver.tableStatusStatement(database: "shop") == "SHOW TABLE STATUS FROM `shop`") + #expect(MySQLPluginDriver.tableStatusStatement(database: "") == "SHOW TABLE STATUS") + } } From 1f47345033a2858ad784e9585c9e8d53d7a324c2 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:02:46 +0700 Subject: [PATCH 032/123] feat(listing): keep the listed kind on the tab across a relaunch Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Models/Query/QueryTab.swift | 4 ++- .../TablePro/Models/Query/QueryTabState.swift | 8 ++++++ .../Services/PersistedTabRoundTripTests.swift | 27 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Models/Query/QueryTab.swift b/apple/TablePro/Models/Query/QueryTab.swift index f5f32b7f12..e94be37182 100644 --- a/apple/TablePro/Models/Query/QueryTab.swift +++ b/apple/TablePro/Models/Query/QueryTab.swift @@ -189,7 +189,8 @@ struct QueryTab: Identifiable, Equatable { self.display = TabDisplayState( erDiagramSchemaKey: persisted.erDiagramSchemaKey, objectRef: persisted.objectRef, - versionHistorySubject: persisted.versionHistorySubject + versionHistorySubject: persisted.versionHistorySubject, + listingKind: persisted.listingKindRawValue.flatMap(SidebarObjectKind.init(rawValue:)) ) self.pendingChanges = TabChangeSnapshot() self.selectionSnapshot = .empty @@ -346,6 +347,7 @@ struct QueryTab: Identifiable, Equatable { erDiagramSchemaKey: display.erDiagramSchemaKey, objectRef: display.objectRef, versionHistorySubject: display.versionHistorySubject, + listingKindRawValue: display.listingKind?.rawValue, queryParameters: content.queryParameters.isEmpty ? nil : content.queryParameters, sortColumns: persistedSort, sortSource: persistedSortSource, diff --git a/apple/TablePro/Models/Query/QueryTabState.swift b/apple/TablePro/Models/Query/QueryTabState.swift index 764cd1df8f..a2522643f0 100644 --- a/apple/TablePro/Models/Query/QueryTabState.swift +++ b/apple/TablePro/Models/Query/QueryTabState.swift @@ -48,6 +48,8 @@ struct PersistedTab: Codable { var erDiagramSchemaKey: String? var objectRef: DatabaseObjectRef? var versionHistorySubject: VersionHistorySubject? + // Raw, like objectTypeRawValue: a kind a newer build adds decodes to nil, which is Tables. + var listingKindRawValue: String? var queryParameters: [QueryParameter]? var sortColumns: [PersistedSortColumn]? // Nil in files written before this existed: decodes to .user when columns were saved, .unset when none were. @@ -81,6 +83,7 @@ struct PersistedTab: Codable { erDiagramSchemaKey: String? = nil, objectRef: DatabaseObjectRef? = nil, versionHistorySubject: VersionHistorySubject? = nil, + listingKindRawValue: String? = nil, queryParameters: [QueryParameter]? = nil, sortColumns: [PersistedSortColumn]? = nil, sortSource: SortSource? = nil, @@ -109,6 +112,7 @@ struct PersistedTab: Codable { self.erDiagramSchemaKey = erDiagramSchemaKey self.objectRef = objectRef self.versionHistorySubject = versionHistorySubject + self.listingKindRawValue = listingKindRawValue self.queryParameters = queryParameters self.sortColumns = sortColumns self.sortSource = sortSource @@ -127,6 +131,7 @@ struct PersistedTab: Codable { private enum CodingKeys: String, CodingKey { case id, title, query, tabType, tableName, isView, objectTypeRawValue, databaseName, schemaName case sourceFileURL, sourceFileEncoding, erDiagramSchemaKey, objectRef, versionHistorySubject, queryParameters + case listingKindRawValue case sortColumns, sortSource, restoredPage, restoredPageSize, cursorOffset, cursorLength case collapsedFoldRanges case columnWidths, columnContentWidths, windowGroupIndex @@ -151,6 +156,7 @@ struct PersistedTab: Codable { erDiagramSchemaKey = try container.decodeIfPresent(String.self, forKey: .erDiagramSchemaKey) objectRef = try container.decodeIfPresent(DatabaseObjectRef.self, forKey: .objectRef) versionHistorySubject = try container.decodeIfPresent(VersionHistorySubject.self, forKey: .versionHistorySubject) + listingKindRawValue = try container.decodeIfPresent(String.self, forKey: .listingKindRawValue) queryParameters = try container.decodeIfPresent([QueryParameter].self, forKey: .queryParameters) sortColumns = try container.decodeIfPresent([PersistedSortColumn].self, forKey: .sortColumns) sortSource = try container.decodeIfPresent(SortSource.self, forKey: .sortSource) @@ -671,6 +677,8 @@ struct TabDisplayState: Equatable { var erDiagramSchemaKey: String? var objectRef: DatabaseObjectRef? var versionHistorySubject: VersionHistorySubject? + // The kind an Objects tab lists. Nil is Tables, which every tab saved before kinds existed shows. + var listingKind: SidebarObjectKind? var isResultsCollapsed: Bool = false var resultSets: [ResultSet] = [] var activeResultSetId: UUID? diff --git a/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift b/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift index 7c674cd830..75f081b25b 100644 --- a/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift +++ b/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift @@ -587,4 +587,31 @@ struct PersistedTabRoundTripTests { let decoded = try JSONDecoder().decode(PersistedTab.self, from: Data(json.utf8)) #expect(decoded.versionHistorySubject == nil) } + + @Test("A listing's kind round-trips, and Tables saves no kind") + func listingKindRoundTrips() throws { + var tab = QueryTab(title: "Views: sales", tabType: .tableListing) + tab.tableContext.databaseName = "shop" + tab.tableContext.schemaName = "sales" + tab.display.listingKind = .view + + let encoded = try JSONEncoder().encode(tab.toPersistedTab()) + let restored = QueryTab(from: try JSONDecoder().decode(PersistedTab.self, from: encoded), defaultPageSize: 1_000) + + #expect(restored.display.listingKind == .view) + #expect(QueryTab(title: "Tables", tabType: .tableListing).toPersistedTab().listingKindRawValue == nil) + } + + /// An older build wrote no kind, and a newer one may write a kind this build does not know. + @Test("A listing saved without a kind this build knows restores as Tables") + func listingWithoutAKnownKindRestoresAsTables() throws { + let id = UUID().uuidString + let older = #"{"id":"\#(id)","title":"Tables","query":"","tabType":{"tableListing":{}}}"# + let newer = #"{"id":"\#(id)","title":"Indexes","query":"","tabType":{"tableListing":{}},"listingKindRawValue":"index"}"# + + for json in [older, newer] { + let decoded = try JSONDecoder().decode(PersistedTab.self, from: Data(json.utf8)) + #expect(QueryTab(from: decoded, defaultPageSize: 1_000).display.listingKind == nil) + } + } } From 2199c2e554e16f9057184bb209ed648994d60665 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:08:53 +0700 Subject: [PATCH 033/123] feat(listing): hold every kind in one tab per container and open listings as previews Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Query/QueryTabManager.swift | 60 ++++++++++-- .../QueryTabManagerTableListingTests.swift | 94 +++++++++++++++++++ 2 files changed, 146 insertions(+), 8 deletions(-) diff --git a/apple/TablePro/Models/Query/QueryTabManager.swift b/apple/TablePro/Models/Query/QueryTabManager.swift index 7f1d233ecf..349112d522 100644 --- a/apple/TablePro/Models/Query/QueryTabManager.swift +++ b/apple/TablePro/Models/Query/QueryTabManager.swift @@ -548,14 +548,23 @@ final class QueryTabManager: ObservableObject { selectedTabId = newTab.id } + // One listing per container: asking again selects it, and another kind retargets it rather than opening a second + // tab. A preview takes the strip slot of the preview it replaces, so browsing the sidebar does not grow the strip. @discardableResult - func addTableListingTab(title: String, databaseName: String, schemaName: String?) -> UUID { + func addTableListingTab( + title: String, + databaseName: String, + schemaName: String?, + kind: SidebarObjectKind = .table, + isPreview: Bool = false, + replacing previewId: UUID? = nil + ) -> UUID { let schemaName = schemaName.flatMap { $0.isEmpty ? nil : $0 } - if let existing = tabs.first(where: { - $0.tabType == .tableListing - && $0.tableContext.databaseName == databaseName - && $0.tableContext.schemaName == schemaName - }) { + if let existing = tableListingTab(databaseName: databaseName, schemaName: schemaName) { + setTableListingKind(kind, title: title, tabId: existing.id) + if !isPreview { + promotePreviewTab(id: existing.id) + } selectedTabId = existing.id return existing.id } @@ -563,12 +572,46 @@ final class QueryTabManager: ObservableObject { newTab.tableContext.isEditable = false newTab.tableContext.databaseName = databaseName newTab.tableContext.schemaName = schemaName - newTab.hasUserInteraction = true - tabs.append(newTab) + newTab.display.listingKind = Self.storedListingKind(kind) + newTab.isPreview = isPreview + // The structure-change check promotes a preview carrying this flag; a listing preview is kept only by the user. + newTab.hasUserInteraction = !isPreview + if let previewId, let index = tabs.firstIndex(where: { $0.id == previewId && $0.isPreview }) { + var updated = tabs + updated[index] = newTab + tabs = updated + } else { + tabs.append(newTab) + } selectedTabId = newTab.id return newTab.id } + func tableListingTab(databaseName: String, schemaName: String?) -> QueryTab? { + let schemaName = schemaName.flatMap { $0.isEmpty ? nil : $0 } + return tabs.first { + $0.tabType == .tableListing + && $0.tableContext.databaseName == databaseName + && $0.tableContext.schemaName == schemaName + } + } + + func setTableListingKind(_ kind: SidebarObjectKind, title: String, tabId: UUID) { + guard let index = tabs.firstIndex(where: { $0.id == tabId && $0.tabType == .tableListing }) else { return } + let stored = Self.storedListingKind(kind) + guard tabs[index].display.listingKind != stored || tabs[index].title != title else { return } + mutate(at: index) { tab in + tab.display.listingKind = stored + tab.title = title + } + markTabRenamed(tabId) + } + + // Nil stands for Tables, so a tab saved before kinds existed reads as one. + private static func storedListingKind(_ kind: SidebarObjectKind) -> SidebarObjectKind? { + kind == .table ? nil : kind + } + // One tab per run: debugging the same routine again starts a second session rather than taking over a live one. @discardableResult func addRoutineDebugTab(id: UUID = UUID(), title: String, databaseName: String, schemaName: String?) -> UUID { @@ -674,6 +717,7 @@ final class QueryTabManager: ObservableObject { tab.display.resultsViewMode = .data tab.display.resultSets = [] tab.display.activeResultSetId = nil + tab.display.listingKind = nil tab.sortState = SortState() tab.restoredSortSource = .unset tab.selectionSnapshot = .empty diff --git a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift index beb8d6364a..767677bf2b 100644 --- a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift +++ b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift @@ -59,4 +59,98 @@ struct QueryTabManagerTableListingTests { #expect(QueryTabManager.tableListingTitle(kindTitle: "Collections", schemaName: nil) == "Collections") #expect(QueryTabManager.tableListingTitle(kindTitle: "Tables", schemaName: "") == "Tables") } + + @Test("A new kind retargets the container's tab and relabels it, never opening another") + func kindRetargetsTheContainersTab() throws { + let manager = QueryTabManager() + let first = manager.addTableListingTab(title: "Tables: sales", databaseName: "shop", schemaName: "sales") + let version = manager.tabStructureVersion + + let second = manager.addTableListingTab( + title: "Views: sales", databaseName: "shop", schemaName: "sales", kind: .view + ) + + let tab = try #require(manager.tabs.first) + #expect(second == first) + #expect(manager.tabs.count == 1) + #expect(tab.display.listingKind == .view) + #expect(tab.title == "Views: sales") + #expect(manager.tabStructureVersion > version) + #expect(manager.tableListingTab(databaseName: "shop", schemaName: "sales")?.id == first) + #expect(manager.tableListingTab(databaseName: "shop", schemaName: "") == nil) + } + + @Test("Tables is stored as no kind, so it reads like a tab saved before kinds existed") + func tablesIsStoredAsNoKind() throws { + let manager = QueryTabManager() + let id = manager.addTableListingTab(title: "Views", databaseName: "shop", schemaName: nil, kind: .view) + + manager.setTableListingKind(.table, title: "Tables", tabId: id) + + let tab = try #require(manager.tabs.first) + #expect(tab.display.listingKind == nil) + #expect(tab.title == "Tables") + } + + @Test("A preview listing stays a preview until a request to keep it") + func previewIsKeptOnlyWhenAsked() throws { + let manager = QueryTabManager() + let id = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil, isPreview: true) + #expect(manager.tabs.first?.isPreview == true) + // The structure-change check promotes a preview with this set; a listing preview is kept by the user only. + #expect(manager.tabs.first?.hasUserInteraction == false) + + manager.addTableListingTab(title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true) + #expect(manager.tabs.first?.isPreview == true) + + manager.addTableListingTab(title: "Views", databaseName: "shop", schemaName: nil, kind: .view) + #expect(manager.tabs.first?.isPreview == false) + #expect(manager.tabs.map(\.id) == [id]) + } + + @Test("A preview listing takes the strip slot of the preview it replaces") + func previewTakesThePreviewsSlot() throws { + let manager = QueryTabManager() + manager.addTab(initialQuery: "SELECT 1", databaseName: "shop") + let before = try #require(manager.selectedTabId) + let preview = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil, isPreview: true) + manager.addTab(initialQuery: "SELECT 2", databaseName: "shop") + let after = try #require(manager.selectedTabId) + manager.selectedTabId = preview + + let replacement = manager.addTableListingTab( + title: "Functions", databaseName: "archive", schemaName: nil, kind: .function, + isPreview: true, replacing: preview + ) + + #expect(replacement != preview) + #expect(manager.tabs.map(\.id) == [before, replacement, after]) + #expect(manager.selectedTabId == replacement) + #expect(manager.selectedTab?.tableContext.databaseName == "archive") + #expect(manager.selectedTab?.display.listingKind == .function) + #expect(manager.selectedTab?.isPreview == true) + } + + @Test("Only a preview is replaced: a kept tab named as the one to replace stays") + func keptTabIsNeverReplaced() throws { + let manager = QueryTabManager() + let kept = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil) + + let added = manager.addTableListingTab( + title: "Tables", databaseName: "archive", schemaName: nil, isPreview: true, replacing: kept + ) + + #expect(manager.tabs.map(\.id) == [kept, added]) + } + + @Test("A listing a table click takes over forgets its kind") + func tableRetargetForgetsTheKind() throws { + let manager = QueryTabManager() + manager.addTableListingTab(title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true) + + try manager.replaceTabContent(tableName: "orders", databaseType: .mysql, databaseName: "shop", isPreview: true) + + #expect(manager.selectedTab?.tabType == .table) + #expect(manager.selectedTab?.display.listingKind == nil) + } } From 5b72d9d729a1854a0a8c221ac52e1ce3d1d29b48 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:23:40 +0700 Subject: [PATCH 034/123] feat(listing): decide which kinds a container's Objects tab offers Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Sidebar/ObjectListingKinds.swift | 78 +++++++++++++++++++ .../Sidebar/ObjectListingKindsTests.swift | 77 ++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 apple/TablePro/Models/Sidebar/ObjectListingKinds.swift create mode 100644 apple/TableProTests/Models/Sidebar/ObjectListingKindsTests.swift diff --git a/apple/TablePro/Models/Sidebar/ObjectListingKinds.swift b/apple/TablePro/Models/Sidebar/ObjectListingKinds.swift new file mode 100644 index 0000000000..3d9b82cb28 --- /dev/null +++ b/apple/TablePro/Models/Sidebar/ObjectListingKinds.swift @@ -0,0 +1,78 @@ +// +// ObjectListingKinds.swift +// TablePro +// + +import Foundation + +/// Which kinds an Objects tab offers for its container: the groups the sidebar shows there. +internal enum ObjectListingKinds { + /// Tables always, so a container holding nothing else still has a kind to show. Another kind is + /// offered when the container holds some, as a sidebar group is, and a routine, trigger or type + /// kind only where the engine fetches it. The tab's own kind stays while it is empty. + internal static func available( + itemCounts: [SidebarObjectKind: Int], + declared: Set, + current: SidebarObjectKind + ) -> [SidebarObjectKind] { + SidebarObjectKind.allCases.filter { kind in + if kind == .table || kind == current { return true } + if kind.category != .table, !declared.contains(kind) { return false } + return itemCounts[kind, default: 0] > 0 + } + } + + /// Relation kinds come from the table list every engine reads, so only a routine, trigger or + /// type kind can stop being fetched after a reconnect; the tab then shows Tables. + internal static func effective(_ kind: SidebarObjectKind, declared: Set) -> SidebarObjectKind { + kind.category == .table || declared.contains(kind) ? kind : .table + } + + internal static func itemCounts( + tables: [TableInfo], + routines: [RoutineInfo], + triggers: [TriggerInfo], + types: [UserDefinedTypeInfo] + ) -> [SidebarObjectKind: Int] { + var counts: [SidebarObjectKind: Int] = [:] + for table in tables { + counts[SidebarObjectKind.resolve(tableType: table.type), default: 0] += 1 + } + for routine in routines { + counts[routine.kind.sidebarObjectKind, default: 0] += 1 + } + counts[.trigger] = triggers.count + counts[.type] = types.count + return counts + } +} + +extension SidebarObjectKind { + var listingFailureTitle: String { + switch self { + case .table: return String(localized: "Can't List Tables") + case .view: return String(localized: "Can't List Views") + case .materializedView: return String(localized: "Can't List Materialized Views") + case .foreignTable: return String(localized: "Can't List Foreign Tables") + case .sequence: return String(localized: "Can't List Sequences") + case .procedure: return String(localized: "Can't List Procedures") + case .function: return String(localized: "Can't List Functions") + case .trigger: return String(localized: "Can't List Triggers") + case .type: return String(localized: "Can't List Types") + } + } + + var listingEmptyTitle: String { + switch self { + case .table: return String(localized: "No Tables") + case .view: return String(localized: "No Views") + case .materializedView: return String(localized: "No Materialized Views") + case .foreignTable: return String(localized: "No Foreign Tables") + case .sequence: return String(localized: "No Sequences") + case .procedure: return String(localized: "No Procedures") + case .function: return String(localized: "No Functions") + case .trigger: return String(localized: "No Triggers") + case .type: return String(localized: "No Types") + } + } +} diff --git a/apple/TableProTests/Models/Sidebar/ObjectListingKindsTests.swift b/apple/TableProTests/Models/Sidebar/ObjectListingKindsTests.swift new file mode 100644 index 0000000000..0a7055edb3 --- /dev/null +++ b/apple/TableProTests/Models/Sidebar/ObjectListingKindsTests.swift @@ -0,0 +1,77 @@ +// +// ObjectListingKindsTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +struct ObjectListingKindsTests { + @Test("Tables lead, then the kinds the container holds, in the sidebar's order") + func kindsFollowTheSidebar() { + let kinds = ObjectListingKinds.available( + itemCounts: [.view: 2, .function: 3, .sequence: 0, .trigger: 1], + declared: [.procedure, .function, .trigger], + current: .table + ) + + #expect(kinds == [.table, .view, .function, .trigger]) + } + + @Test("A routine, trigger or type kind the engine does not fetch is left out even with rows") + func undeclaredSideKindsAreLeftOut() { + let kinds = ObjectListingKinds.available(itemCounts: [.type: 4, .view: 1], declared: [], current: .table) + + #expect(kinds == [.table, .view]) + } + + @Test("The tab's own kind stays offered while the container holds none of it") + func currentKindStays() { + let kinds = ObjectListingKinds.available(itemCounts: [:], declared: [.procedure], current: .procedure) + + #expect(kinds == [.table, .procedure]) + } + + @Test("A routine, trigger or type kind the engine stopped fetching falls back to Tables; a relation kind never does") + func undeclaredKindFallsBack() { + #expect(ObjectListingKinds.effective(.function, declared: []) == .table) + #expect(ObjectListingKinds.effective(.trigger, declared: [.procedure]) == .table) + #expect(ObjectListingKinds.effective(.function, declared: [.function]) == .function) + #expect(ObjectListingKinds.effective(.view, declared: []) == .view) + } + + @Test("Counts sort tables by their kind and routines by theirs") + func itemCountsSortObjects() { + let counts = ObjectListingKinds.itemCounts( + tables: [ + TableInfo(name: "orders", type: .table, rowCount: nil), + TableInfo(name: "events", type: .partitionedTable, rowCount: nil), + TableInfo(name: "recent", type: .view, rowCount: nil), + ], + routines: [ + RoutineInfo(name: "touch", kind: .function), + RoutineInfo(name: "archive", kind: .procedure), + RoutineInfo(name: "total", kind: .function), + ], + triggers: [TriggerInfo(name: "audit", timing: "AFTER", event: "INSERT", statement: "")], + types: [] + ) + + #expect(counts[.table] == 2) + #expect(counts[.view] == 1) + #expect(counts[.function] == 2) + #expect(counts[.procedure] == 1) + #expect(counts[.trigger] == 1) + #expect(counts[.type] == 0) + } + + @Test("Each kind names itself when it cannot be listed and when it has nothing") + func kindsNameTheirStates() { + #expect(SidebarObjectKind.table.listingFailureTitle == String(localized: "Can't List Tables")) + #expect(SidebarObjectKind.view.listingFailureTitle == String(localized: "Can't List Views")) + #expect(SidebarObjectKind.table.listingEmptyTitle == String(localized: "No Tables")) + #expect(SidebarObjectKind.trigger.listingEmptyTitle == String(localized: "No Triggers")) + } +} From e5e6e83bda45338c9f2ca0713b9412567f771acd Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:23:40 +0700 Subject: [PATCH 035/123] feat(listing): build rows for every kind and name the object behind each row Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Services/Query/ObjectListingRows.swift | 182 ++++++++++++++++++ .../Services/Query/TableListingLoader.swift | 17 +- .../Query/ObjectListingRowsTests.swift | 181 +++++++++++++++++ 3 files changed, 377 insertions(+), 3 deletions(-) create mode 100644 apple/TablePro/Core/Services/Query/ObjectListingRows.swift create mode 100644 apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift diff --git a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift new file mode 100644 index 0000000000..7e507e253e --- /dev/null +++ b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift @@ -0,0 +1,182 @@ +// +// ObjectListingRows.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +/// The object one row of an Objects tab lists, with what a row command needs to reach it again. +internal enum ObjectListingItem: Hashable, Sendable { + /// A table, view or other relation: it opens in a grid. + case relation(name: String, schema: String?, type: TableInfo.TableType) + /// A routine, trigger or type: it opens as its source. + case sourced(DatabaseObjectRef) + + var name: String { + switch self { + case .relation(let name, _, _): return name + case .sourced(let ref): return ref.name + } + } + + /// Nil for a relation the source viewer cannot read: a table's definition is on its Structure tab. + func sourceRef(database: String) -> DatabaseObjectRef? { + switch self { + case .relation(let name, let schema, let type): + let table = TableInfo(name: name, type: type, rowCount: nil, schema: schema) + return DatabaseObjectRef(relation: table, database: database, schema: schema) + case .sourced(let ref): + return ref + } + } +} + +/// Where a plugin's table listing names its objects: the plugins alias the columns `name`, +/// `schema` or `schema_name`, and `kind`. A shell command's listing has none of them. +internal struct ObjectListingColumns: Equatable { + let name: Int + let schema: Int? + let kind: Int? + + init?(columns: [String]) { + let lowered = columns.map { $0.lowercased() } + guard let name = lowered.firstIndex(of: "name") else { return nil } + self.name = name + schema = lowered.firstIndex(of: "schema") ?? lowered.firstIndex(of: "schema_name") + kind = lowered.firstIndex(of: "kind") + } + + /// `readsSchemaColumn` is off where the engine's namespace is the database: MySQL's `schema` + /// column names the database, and a table opened with it as a schema is a second tab for it. + func items(in rows: TableRows, containerSchema: String?, readsSchemaColumn: Bool) -> [RowID: ObjectListingItem] { + var items: [RowID: ObjectListingItem] = [:] + for row in rows.rows { + guard let name = row[self.name].asText, !name.isEmpty else { continue } + let listed = readsSchemaColumn ? schema.flatMap { row[$0].asText?.nilIfEmpty } : nil + let type = Self.relationType(kind.flatMap { row[$0].asText }) + items[row.id] = .relation(name: name, schema: listed ?? containerSchema, type: type) + } + return items + } + + /// An unknown word, such as a ClickHouse engine name, reads as a table: only a view must not + /// open as an editable grid. + static func relationType(_ kind: String?) -> TableInfo.TableType { + switch kind?.trimmingCharacters(in: .whitespaces).uppercased() ?? "" { + case "VIEW", "SYSTEM VIEW": return .view + case "MATERIALIZED VIEW", "MATERIALIZEDVIEW": return .materializedView + case "FOREIGN TABLE": return .foreignTable + case "SEQUENCE": return .sequence + default: return .table + } + } +} + +/// One kind's objects as the sidebar reads them, before they become rows. +internal enum CatalogObjectList: Sendable, Equatable { + case relations([TableInfo]) + case routines([RoutineInfo]) + case triggers([TriggerInfo]) + case types([UserDefinedTypeInfo]) +} + +/// The Objects tab's rows for every kind but Tables, built from the lists the sidebar shows. +internal enum ObjectListingRows { + internal static func listing(kind: SidebarObjectKind, from list: CatalogObjectList, scope: DatabaseScope) -> TableListing { + let database = scope.database + let schema = scope.schema + switch list { + case .relations(let tables): + let columns: [ListingColumn] = [ + ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn(String(localized: "Schema")) { $0.schema ?? schema }, + ListingColumn(String(localized: "Rows"), isCount: true) { $0.rowCount.map(String.init) }, + ListingColumn(String(localized: "Comment")) { $0.comment?.nilIfEmpty }, + ] + let matching = tables.filter { SidebarObjectKind.resolve(tableType: $0.type) == kind } + return build(matching, columns: columns) { .relation(name: $0.name, schema: schema ?? $0.schema, type: $0.type) } + case .routines(let routines): + let columns: [ListingColumn] = [ + ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn(String(localized: "Schema")) { $0.schema ?? schema }, + ListingColumn(String(localized: "Arguments")) { $0.argumentSignature?.nilIfEmpty }, + ListingColumn(String(localized: "Returns")) { $0.returnType?.nilIfEmpty }, + ListingColumn(String(localized: "Language")) { $0.language?.nilIfEmpty }, + ] + let matching = routines.filter { $0.kind.sidebarObjectKind == kind } + return build(matching, columns: columns) { .sourced(DatabaseObjectRef(routine: $0, database: database)) } + case .triggers(let triggers): + let columns: [ListingColumn] = [ + ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn(String(localized: "Table")) { $0.table?.nilIfEmpty }, + ListingColumn(String(localized: "Timing")) { $0.timing.nilIfEmpty }, + ListingColumn(String(localized: "Event")) { $0.event.nilIfEmpty }, + ListingColumn(String(localized: "Enabled")) { trigger in + trigger.enabled.map { $0 ? String(localized: "Yes") : String(localized: "No") } + }, + ] + return build(triggers, columns: columns) { .sourced(DatabaseObjectRef(trigger: $0, database: database)) } + case .types(let types): + let columns: [ListingColumn] = [ + ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn(String(localized: "Schema")) { $0.schema ?? schema }, + ] + return build(types, columns: columns) { .sourced(DatabaseObjectRef(userType: $0, database: database)) } + } + } + + // Row ids match `TableRows.from`, so each row's object is keyed by the row the grid shows. + private static func build( + _ objects: [Object], + columns: [ListingColumn], + item: (Object) -> ObjectListingItem + ) -> TableListing { + let kept = columns.filter { column in + !column.isOptional || objects.contains { column.value($0) != nil } + } + let rows = objects.map { object in kept.map { PluginCellValue.fromOptional($0.value(object)) } } + let types: [ColumnType] = kept.map { $0.isCount ? .integer(rawType: nil) : .text(rawType: nil) } + var items: [RowID: ObjectListingItem] = [:] + for (index, object) in objects.enumerated() { + items[.existing(index)] = item(object) + } + return TableListing( + rows: TableRows.from(queryRows: rows, columns: kept.map(\.title), columnTypes: types), + isIncomplete: false, + statusMessage: nil, + items: items + ) + } +} + +/// A column no object has a value for says nothing, as a Schema column does on an engine without schemas. +private struct ListingColumn { + let title: String + let isOptional: Bool + let isCount: Bool + let value: (Object) -> String? + + init(_ title: String, isOptional: Bool = true, isCount: Bool = false, value: @escaping (Object) -> String?) { + self.title = title + self.isOptional = isOptional + self.isCount = isCount + self.value = value + } +} + +/// The name filter works on the rows a listing already holds and fetches nothing. +internal enum ObjectListingFilter { + /// Blank text, or a listing with no names to match, keeps every row. + static func rows(of listing: TableListing, matching text: String) -> TableRows { + let needle = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !needle.isEmpty, !listing.items.isEmpty else { return listing.rows } + let hidden = Set(listing.rows.rows.compactMap { row -> RowID? in + guard let name = listing.items[row.id]?.name, name.localizedStandardContains(needle) else { return row.id } + return nil + }) + var shown = listing.rows + shown.remove(rowIDs: hidden) + return shown + } +} diff --git a/apple/TablePro/Core/Services/Query/TableListingLoader.swift b/apple/TablePro/Core/Services/Query/TableListingLoader.swift index 241da84d9f..77efd8f868 100644 --- a/apple/TablePro/Core/Services/Query/TableListingLoader.swift +++ b/apple/TablePro/Core/Services/Query/TableListingLoader.swift @@ -37,10 +37,17 @@ internal struct TableListingLoader: Sendable { } return try await driver.executeCatalogRead(query: statement) } + let rows = TableRows.from(queryRows: result.rows, columns: result.columns, columnTypes: result.columnTypes) + let items = ObjectListingColumns(columns: result.columns)?.items( + in: rows, + containerSchema: scope.schema, + readsSchemaColumn: slot == .schema + ) ?? [:] return .fetched(TableListing( - rows: TableRows.from(queryRows: result.rows, columns: result.columns, columnTypes: result.columnTypes), + rows: rows, isIncomplete: result.isTruncated, - statusMessage: result.statusMessage + statusMessage: result.statusMessage, + items: items )) } catch { if DatabaseCancellationDiagnosis.isCancellation(error) { return .cancelled } @@ -58,10 +65,14 @@ internal struct TableListing: Sendable { /// The driver's own words about the result, such as the cursor of the next page, else a plain /// statement that the listing is partial. let notice: String? + /// The object each row lists, which the name filter and the row commands read. Empty for a + /// listing with no name column, whose rows stay plain values. + let items: [RowID: ObjectListingItem] - init(rows: TableRows, isIncomplete: Bool, statusMessage: String?) { + init(rows: TableRows, isIncomplete: Bool, statusMessage: String?, items: [RowID: ObjectListingItem] = [:]) { self.rows = rows self.isIncomplete = isIncomplete + self.items = items if let statusMessage, !statusMessage.isEmpty { notice = statusMessage } else { diff --git a/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift b/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift new file mode 100644 index 0000000000..74b3e5794c --- /dev/null +++ b/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift @@ -0,0 +1,181 @@ +// +// ObjectListingRowsTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +struct ObjectListingRowsTests { + private let scope = DatabaseScope(connectionId: UUID(), database: "shop", schema: "sales") + + private func cells(_ rows: TableRows) -> [[String]] { + rows.rows.map { row in row.values.map { $0.asText ?? "" } } + } + + private func names(_ rows: TableRows) -> [String] { + rows.rows.map { $0.values.first?.asText ?? "" } + } + + private func function(_ name: String) -> RoutineInfo { + RoutineInfo(name: name, kind: .function, schema: "sales", argumentSignature: "(integer)", returnType: "integer", language: "plpgsql") + } + + // MARK: - Built kinds + + @Test("Views list name, schema and comment, leave out a Rows column nobody counted, and stand for views") + func viewsListTheirColumns() { + let tables = [ + TableInfo(name: "orders", type: .table, rowCount: 10, schema: "sales"), + TableInfo(name: "recent_orders", type: .view, rowCount: nil, schema: "sales", comment: "Last 30 days"), + ] + + let listing = ObjectListingRows.listing(kind: .view, from: .relations(tables), scope: scope) + + #expect(listing.rows.columns == [String(localized: "Name"), String(localized: "Schema"), String(localized: "Comment")]) + #expect(cells(listing.rows) == [["recent_orders", "sales", "Last 30 days"]]) + #expect(listing.items[.existing(0)] == .relation(name: "recent_orders", schema: "sales", type: .view)) + } + + @Test("A relation kind whose objects carry row counts lists them as numbers") + func countedRowsAreNumbers() { + let tables = [TableInfo(name: "ids", type: .sequence, rowCount: 1, schema: "sales")] + + let listing = ObjectListingRows.listing(kind: .sequence, from: .relations(tables), scope: scope) + + #expect(listing.rows.columns == [String(localized: "Name"), String(localized: "Schema"), String(localized: "Rows")]) + #expect(listing.rows.columnTypes[2] == .integer(rawType: nil)) + } + + @Test("Functions list name, schema, arguments, returns and language, and open as their source") + func functionsListTheirSignature() { + let routines = [function("touch"), RoutineInfo(name: "archive", kind: .procedure, schema: "sales")] + + let listing = ObjectListingRows.listing(kind: .function, from: .routines(routines), scope: scope) + + #expect(listing.rows.columns == [ + String(localized: "Name"), String(localized: "Schema"), String(localized: "Arguments"), + String(localized: "Returns"), String(localized: "Language"), + ]) + #expect(cells(listing.rows) == [["touch", "sales", "(integer)", "integer", "plpgsql"]]) + #expect(listing.items[.existing(0)] == .sourced(DatabaseObjectRef(routine: routines[0], database: "shop"))) + } + + @Test("Triggers list name, table, timing, event and whether they are enabled") + func triggersListTheirTable() { + let trigger = TriggerInfo(name: "audit", timing: "AFTER", event: "INSERT", statement: "", enabled: false, table: "orders", schema: "sales") + + let listing = ObjectListingRows.listing(kind: .trigger, from: .triggers([trigger]), scope: scope) + + #expect(listing.rows.columns == [ + String(localized: "Name"), String(localized: "Table"), String(localized: "Timing"), + String(localized: "Event"), String(localized: "Enabled"), + ]) + #expect(cells(listing.rows) == [["audit", "orders", "AFTER", "INSERT", String(localized: "No")]]) + #expect(listing.items[.existing(0)] == .sourced(DatabaseObjectRef(trigger: trigger, database: "shop"))) + } + + @Test("Types list name and schema") + func typesListNameAndSchema() { + let mood = UserDefinedTypeInfo(name: "mood", kind: .enumeration, schema: "sales") + + let listing = ObjectListingRows.listing(kind: .type, from: .types([mood]), scope: scope) + + #expect(listing.rows.columns == [String(localized: "Name"), String(localized: "Schema")]) + #expect(cells(listing.rows) == [["mood", "sales"]]) + } + + // MARK: - A plugin listing's columns + + @Test("A plugin listing's name, schema and kind columns are found by their aliases") + func columnsFoundByAlias() throws { + let postgres = try #require(ObjectListingColumns(columns: ["schema", "name", "kind", "comment"])) + let mssql = try #require(ObjectListingColumns(columns: ["schema_name", "name", "kind"])) + + #expect([postgres.name, postgres.schema, postgres.kind] == [1, 0, 2]) + #expect(mssql.schema == 0) + #expect(ObjectListingColumns(columns: ["Key", "Type"]) == nil) + } + + @Test("A listing row stands for its relation, in the listed schema where the engine has schemas") + func itemsReadTheListedSchema() throws { + let rows = TableRows.from( + queryRows: [[.text("auth"), .text("users"), .text("VIEW")], [.text(""), .text("orders"), .text("BASE TABLE")]], + columns: ["schema", "name", "kind"], + columnTypes: Array(repeating: .text(rawType: nil), count: 3) + ) + let columns = try #require(ObjectListingColumns(columns: rows.columns)) + + let items = columns.items(in: rows, containerSchema: "main", readsSchemaColumn: true) + + #expect(items[.existing(0)] == .relation(name: "users", schema: "auth", type: .view)) + #expect(items[.existing(1)] == .relation(name: "orders", schema: "main", type: .table)) + } + + // MySQL's `schema` alias is TABLE_SCHEMA, the database itself: read as a schema, the table would open as a second tab. + @Test("Where the namespace is the database, the schema column is not read as a schema") + func databaseNamespaceIgnoresTheSchemaColumn() throws { + let rows = TableRows.from( + queryRows: [[.text("shop"), .text("orders"), .text("BASE TABLE")]], + columns: ["schema", "name", "kind"], + columnTypes: Array(repeating: .text(rawType: nil), count: 3) + ) + let columns = try #require(ObjectListingColumns(columns: rows.columns)) + + let items = columns.items(in: rows, containerSchema: nil, readsSchemaColumn: false) + + #expect(items[.existing(0)] == .relation(name: "orders", schema: nil, type: .table)) + } + + static let kindWords: [(String?, TableInfo.TableType)] = [ + ("VIEW", .view), ("view", .view), ("SYSTEM VIEW", .view), ("MATERIALIZED VIEW", .materializedView), + ("FOREIGN TABLE", .foreignTable), ("SEQUENCE", .sequence), ("BASE TABLE", .table), ("MergeTree", .table), (nil, .table), + ] + + @Test("A listing's kind word decides how its row opens", arguments: kindWords) + func kindWordsDecideTheType(word: String?, type: TableInfo.TableType) { + #expect(ObjectListingColumns.relationType(word) == type) + } + + // MARK: - Filter + + @Test("The filter keeps rows whose name holds the text, ignoring case, accents and surrounding spaces") + func filterMatchesNames() { + let listing = ObjectListingRows.listing( + kind: .function, + from: .routines([function("Orders_Total"), function("café_sync"), function("audit")]), + scope: scope + ) + + #expect(names(ObjectListingFilter.rows(of: listing, matching: " ORDER ")) == ["Orders_Total"]) + #expect(names(ObjectListingFilter.rows(of: listing, matching: "cafe")) == ["café_sync"]) + #expect(names(ObjectListingFilter.rows(of: listing, matching: " ")) == ["Orders_Total", "café_sync", "audit"]) + } + + @Test("A filtered row keeps its identity, so a row action reaches the same object") + func filteredRowsKeepTheirIds() { + let listing = ObjectListingRows.listing( + kind: .function, from: .routines([function("touch"), function("audit")]), scope: scope + ) + + let shown = ObjectListingFilter.rows(of: listing, matching: "audit") + + #expect(shown.rows.map(\.id) == [.existing(1)]) + #expect(shown.index(of: .existing(1)) == 0) + } + + @Test("A listing with no name to match keeps every row") + func listingWithoutNamesIsNotFiltered() { + let listing = TableListing( + rows: TableRows.from(queryRows: [[.text("session:1")]], columns: ["Key"], columnTypes: [.text(rawType: nil)]), + isIncomplete: false, + statusMessage: nil + ) + + #expect(listing.items.isEmpty) + #expect(ObjectListingFilter.rows(of: listing, matching: "zzz").count == 1) + } +} From f76414570d6ad5efd4cc2e4fe84c53c22a511957 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:41:19 +0700 Subject: [PATCH 036/123] feat(listing): read views, routines, triggers and types from the sidebar's lists Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/CatalogObjectListSource.swift | 93 +++++++++++++++ .../Query/CatalogObjectListSourceTests.swift | 110 ++++++++++++++++++ 2 files changed, 203 insertions(+) create mode 100644 apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift create mode 100644 apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift diff --git a/apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift b/apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift new file mode 100644 index 0000000000..e24c0ef2fa --- /dev/null +++ b/apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift @@ -0,0 +1,93 @@ +// +// CatalogObjectListSource.swift +// TablePro +// + +import Foundation + +/// Where an Objects tab reads every kind but Tables. The sidebar's own lists, so the tab and the +/// tree show the same objects, and a refresh in either reaches both. +@MainActor +internal protocol CatalogObjectListSource: AnyObject, Sendable { + /// `rereading` asks the server again; otherwise a list the sidebar already holds is taken as it is. + func objects( + _ category: SidebarObjectCategory, + in scope: DatabaseScope, + rereading: Bool + ) async -> MetadataFetchOutcome +} + +extension DatabaseTreeMetadataService: CatalogObjectListSource { + func objects( + _ category: SidebarObjectCategory, + in scope: DatabaseScope, + rereading: Bool + ) async -> MetadataFetchOutcome { + let id = scope.connectionId + let database = scope.database + let schema = scope.schema + switch category { + case .table: + return await listOutcome( + rereading: rereading, + reread: { await self.refreshTableObjects(connectionId: id, database: database, schema: schema) }, + load: { await self.loadTables(connectionId: id, database: database, schema: schema) }, + state: { self.tablesLoadState(connectionId: id, database: database, schema: schema) }, + wrap: CatalogObjectList.relations + ) + case .routine: + return await listOutcome( + rereading: rereading, + reread: { await self.refreshRoutineObjects(connectionId: id, database: database, schema: schema) }, + load: { await self.loadRoutines(connectionId: id, database: database, schema: schema) }, + state: { self.routinesLoadState(connectionId: id, database: database, schema: schema) }, + wrap: CatalogObjectList.routines + ) + case .trigger: + return await listOutcome( + rereading: rereading, + reread: { await self.refreshTriggerObjects(connectionId: id, database: database, schema: schema) }, + load: { await self.loadTriggers(connectionId: id, database: database, schema: schema) }, + state: { self.triggersLoadState(connectionId: id, database: database, schema: schema) }, + wrap: CatalogObjectList.triggers + ) + case .type: + return await listOutcome( + rereading: rereading, + reread: { await self.refreshUserDefinedTypeObjects(connectionId: id, database: database, schema: schema) }, + load: { await self.loadUserDefinedTypes(connectionId: id, database: database, schema: schema) }, + state: { self.typesLoadState(connectionId: id, database: database, schema: schema) }, + wrap: CatalogObjectList.types + ) + } + } + + private func listOutcome( + rereading: Bool, + reread: () async -> Void, + load: () async -> Void, + state: () -> MetadataLoadState, + wrap: (Value) -> CatalogObjectList + ) async -> MetadataFetchOutcome { + if rereading { + await reread() + } else { + await load() + } + // A read the sidebar started meanwhile owns the list; loading again joins it at its revision. + if case .loading = state() { + await load() + } + switch state() { + case .loaded(let value): + return .fetched(wrap(value)) + case .failed(let message): + return .failed(message) + case .loading: + return .cancelled + case .idle: + // Nothing ran, which the service does only for a connection that is down. + return .failed(DatabaseError.notConnected.localizedDescription) + } + } +} diff --git a/apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift b/apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift new file mode 100644 index 0000000000..70bbf76197 --- /dev/null +++ b/apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift @@ -0,0 +1,110 @@ +// +// CatalogObjectListSourceTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +private struct ListRefused: Error, LocalizedError { + var errorDescription: String? { "permission denied for schema public" } +} + +/// PGlite cannot open a pooled connection, so a read stays on the injected session driver. +@MainActor +struct CatalogObjectListSourceTests { + private let service = DatabaseTreeMetadataService.shared + + private func connect() -> (DatabaseConnection, MockDatabaseDriver) { + let connection = TestFixtures.makeConnection(type: .pglite) + let driver = MockDatabaseDriver(connection: connection) + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + DatabaseManager.shared.injectSession(session, for: connection.id) + return (connection, driver) + } + + private func disconnect(_ connection: DatabaseConnection) async { + await service.handleDisconnect(connectionId: connection.id) + DatabaseManager.shared.removeSession(for: connection.id) + } + + private func scope(_ connection: DatabaseConnection) -> DatabaseScope { + DatabaseScope(connectionId: connection.id, database: connection.database, schema: "public") + } + + private func fetched(_ outcome: MetadataFetchOutcome) -> CatalogObjectList? { + if case .fetched(let list) = outcome { return list } + return nil + } + + private func failure(_ outcome: MetadataFetchOutcome) -> String? { + if case .failed(let message) = outcome { return message } + return nil + } + + @Test("A kind is read into the sidebar's own list, and asking again takes that list without a second read") + func readsIntoTheSidebarsList() async { + let (connection, driver) = connect() + let orders = TestFixtures.makeTableInfo(name: "orders", schema: "public") + driver.schemaTablesToReturn = ["public": [orders]] + + let first = await service.objects(.table, in: scope(connection), rereading: false) + let second = await service.objects(.table, in: scope(connection), rereading: false) + + #expect(fetched(first) == .relations([orders])) + #expect(fetched(second) == .relations([orders])) + #expect(driver.fetchScopedTablesCallCount == 1) + #expect(service.tables(connectionId: connection.id, database: connection.database, schema: "public") == [orders]) + await disconnect(connection) + } + + @Test("A refresh reads the kind again, so a change made elsewhere shows") + func refreshRereads() async { + let (connection, driver) = connect() + let orders = TestFixtures.makeTableInfo(name: "orders", schema: "public") + let customers = TestFixtures.makeTableInfo(name: "customers", schema: "public") + driver.schemaTablesToReturn = ["public": [orders]] + _ = await service.objects(.table, in: scope(connection), rereading: false) + + driver.schemaTablesToReturn = ["public": [orders, customers]] + let refreshed = await service.objects(.table, in: scope(connection), rereading: true) + + #expect(fetched(refreshed) == .relations([orders, customers])) + await disconnect(connection) + } + + @Test("Routines come from the sidebar's routine list") + func routinesComeFromTheRoutineList() async { + let (connection, driver) = connect() + let touch = RoutineInfo(name: "touch", kind: .function, schema: "public") + driver.schemaRoutinesToReturn = ["public": [touch]] + + let outcome = await service.objects(.routine, in: scope(connection), rereading: false) + + #expect(fetched(outcome) == .routines([touch])) + await disconnect(connection) + } + + @Test("A read the server refused says why") + func refusedReadSaysWhy() async { + let (connection, driver) = connect() + driver.schemaTablesErrors = ["public": ListRefused()] + + let outcome = await service.objects(.table, in: scope(connection), rereading: false) + + #expect(failure(outcome) == ListRefused().localizedDescription) + await disconnect(connection) + } + + @Test("With the connection down the read says so instead of leaving a spinner") + func notConnectedSaysSo() async { + let scope = DatabaseScope(connectionId: UUID(), database: "shop", schema: "public") + + let outcome = await service.objects(.routine, in: scope, rereading: false) + + #expect(failure(outcome) == DatabaseError.notConnected.localizedDescription) + } +} From 94891f33709d8d77b7f2224c9af5537eaea1eb9c Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:41:19 +0700 Subject: [PATCH 037/123] feat(listing): describe the commands a listed object offers Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../TableListing/ObjectListingMenu.swift | 59 +++++++++++++++++ .../TableListing/ObjectListingMenuTests.swift | 65 +++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 apple/TablePro/Views/TableListing/ObjectListingMenu.swift create mode 100644 apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift diff --git a/apple/TablePro/Views/TableListing/ObjectListingMenu.swift b/apple/TablePro/Views/TableListing/ObjectListingMenu.swift new file mode 100644 index 0000000000..3dc6d5ba1b --- /dev/null +++ b/apple/TablePro/Views/TableListing/ObjectListingMenu.swift @@ -0,0 +1,59 @@ +// +// ObjectListingMenu.swift +// TablePro +// + +import Foundation + +/// What a row of the Objects tab does, routed to the coordinator commands the sidebar's rows run. +internal enum ObjectListingAction: Equatable { + case open(ObjectListingItem) + case openInNewTab(ObjectListingItem) + case showStructure(ObjectListingItem) + case showSource(ObjectListingItem) + case copyNames([String]) +} + +internal struct ObjectListingMenuCommand: Equatable { + let title: String + let action: ObjectListingAction +} + +/// A row's commands as values, in the words the sidebar uses for the same object. +internal enum ObjectListingMenu { + internal static func primaryAction(for item: ObjectListingItem) -> ObjectListingAction { + switch item { + case .relation: return .open(item) + case .sourced: return .showSource(item) + } + } + + /// The clicked row's own commands, then Copy Name over every row the menu acts on. + internal static func commands(clicked: ObjectListingItem, targets: [ObjectListingItem]) -> [ObjectListingMenuCommand] { + var commands: [ObjectListingMenuCommand] = [] + if case .relation = clicked { + commands.append(ObjectListingMenuCommand(title: String(localized: "Open in New Tab"), action: .openInNewTab(clicked))) + commands.append(ObjectListingMenuCommand(title: String(localized: "Show Structure"), action: .showStructure(clicked))) + } + if let title = sourceTitle(for: clicked) { + commands.append(ObjectListingMenuCommand(title: title, action: .showSource(clicked))) + } + let names = (targets.isEmpty ? [clicked] : targets).map(\.name) + commands.append(ObjectListingMenuCommand(title: copyNamesTitle(count: names.count), action: .copyNames(names))) + return commands + } + + // The source viewer reads views, routines, triggers and types; a table's definition is on its Structure tab. + private static func sourceTitle(for item: ObjectListingItem) -> String? { + switch item { + case .relation(_, _, let type): + return DatabaseObjectKind(tableType: type) == nil ? nil : String(localized: "Show DDL") + case .sourced(let ref): + return ref.kind == .userType ? String(localized: "Show Definition") : String(localized: "Show DDL") + } + } + + private static func copyNamesTitle(count: Int) -> String { + count == 1 ? String(localized: "Copy Name") : String(format: String(localized: "Copy %lld Names"), count) + } +} diff --git a/apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift b/apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift new file mode 100644 index 0000000000..edb7c7b7e8 --- /dev/null +++ b/apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift @@ -0,0 +1,65 @@ +// +// ObjectListingMenuTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +struct ObjectListingMenuTests { + private let orders = ObjectListingItem.relation(name: "orders", schema: "sales", type: .table) + private let recent = ObjectListingItem.relation(name: "recent_orders", schema: "sales", type: .view) + private let touch = ObjectListingItem.sourced(DatabaseObjectRef(kind: .function, name: "touch", database: "shop", schema: "sales")) + private let mood = ObjectListingItem.sourced(DatabaseObjectRef(kind: .userType, name: "mood", database: "shop", schema: "sales")) + + private func titles(_ commands: [ObjectListingMenuCommand]) -> [String] { + commands.map(\.title) + } + + @Test("A double click opens a relation and shows the source of anything else") + func primaryActionFollowsTheKind() { + #expect(ObjectListingMenu.primaryAction(for: orders) == .open(orders)) + #expect(ObjectListingMenu.primaryAction(for: touch) == .showSource(touch)) + } + + @Test("A table offers what the sidebar offers it: a new tab, its structure and its name") + func tableCommands() { + let commands = ObjectListingMenu.commands(clicked: orders, targets: [orders]) + + #expect(commands.map(\.action) == [.openInNewTab(orders), .showStructure(orders), .copyNames(["orders"])]) + #expect(titles(commands) == [ + String(localized: "Open in New Tab"), String(localized: "Show Structure"), String(localized: "Copy Name"), + ]) + } + + @Test("A view adds Show DDL, which a table has on its Structure tab instead") + func viewAddsShowDDL() { + let commands = ObjectListingMenu.commands(clicked: recent, targets: [recent]) + + #expect(commands.map(\.action).contains(.showSource(recent))) + #expect(titles(commands).contains(String(localized: "Show DDL"))) + } + + @Test("A routine offers its DDL and its name; a type calls its source a definition, as the sidebar does") + func sourcedCommands() { + #expect(titles(ObjectListingMenu.commands(clicked: touch, targets: [touch])) == [ + String(localized: "Show DDL"), String(localized: "Copy Name"), + ]) + #expect(titles(ObjectListingMenu.commands(clicked: mood, targets: [mood])) == [ + String(localized: "Show Definition"), String(localized: "Copy Name"), + ]) + } + + @Test("Copy Name copies every row the menu acts on; the other commands act on the clicked row") + func copyNamesCoversTheSelection() { + let commands = ObjectListingMenu.commands(clicked: orders, targets: [orders, recent]) + + #expect(commands.first?.action == .openInNewTab(orders)) + #expect(commands.last == ObjectListingMenuCommand( + title: String(format: String(localized: "Copy %lld Names"), 2), + action: .copyNames(["orders", "recent_orders"]) + )) + } +} From 6d55a525b62ca8e8e1cc06db08d8c4f639e8e734 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:41:20 +0700 Subject: [PATCH 038/123] feat(grid): let a double click or Return open the object a row stands for Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../DataGrid/DataGridOwnerProtocols.swift | 4 +++ .../DataGridViewController+Editing.swift | 9 +++++ .../Views/Structure/HeldRowsGridAdapter.swift | 11 ++++++ .../Views/DataGrid/DataGridEditingTests.swift | 35 +++++++++++++++++++ 4 files changed, 59 insertions(+) diff --git a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift index 7844ea8b62..259149bd03 100644 --- a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift +++ b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift @@ -21,6 +21,8 @@ enum DataGridCommand: Hashable, CaseIterable { case valueFilter case copyAsSQL case loadUnloadedValues + // A double click or Return opens what the row stands for instead of the cell's value. + case openRow } enum DataGridLayoutScope: Equatable { @@ -98,6 +100,7 @@ protocol DataGridActions: AnyObject { func gridClearResults() func gridSearchAllRows(term: String) func gridSetCheckbox(_ isOn: Bool, rowIDs: [RowID], column: DataGridColumn) + func gridOpenRow(_ rowID: RowID) func gridLoadUnloadedValues(rowIDs: [RowID], columns: IndexSet?, completion: @escaping @MainActor (Bool) -> Void) var gridSQLExporter: (any DataGridSQLExporting)? { get } @@ -130,6 +133,7 @@ extension DataGridActions { func gridClearResults() {} func gridSearchAllRows(term: String) {} func gridSetCheckbox(_ isOn: Bool, rowIDs: [RowID], column: DataGridColumn) {} + func gridOpenRow(_ rowID: RowID) {} func gridLoadUnloadedValues(rowIDs: [RowID], columns: IndexSet?, completion: @escaping @MainActor (Bool) -> Void) { completion(false) } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Editing.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Editing.swift index 67a2942f6b..d9a8d191cd 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Editing.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Editing.swift @@ -70,6 +70,7 @@ extension DataGridViewController { func beginEditingActiveCell() { guard let active = model.selection.activeCell else { return } + guard !openRow(at: active.row) else { return } reveal(row: active.row, displayColumn: active.displayColumn) openEditor(at: active) } @@ -103,9 +104,17 @@ extension DataGridViewController { } func handleCellDoubleClick(at cell: GridCoord) { + guard !openRow(at: cell.row) else { return } openEditor(at: cell) } + // Rows that stand for objects open the object, the way a double click opens a file in Finder. + private func openRow(at row: Int) -> Bool { + guard gridCommands.offers(.openRow), let rowID = model.rowID(at: row) else { return false } + model.actions?.gridOpenRow(rowID) + return true + } + func handleClickOnActiveCell(_ cell: GridCoord) { guard let clicked = editCell(at: cell), textEditableValue(of: clicked) != nil else { return } openEditor(at: cell) diff --git a/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift b/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift index 5f4b3217c1..02d7fc567d 100644 --- a/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift +++ b/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift @@ -23,6 +23,9 @@ final class HeldRowsGridAdapter: ObservableObject { var spokenTexts: [RowID: [Int: String]] = [:] var checkboxState: ((RowID, DataGridColumn) -> Bool?)? var checkboxChange: ((Bool, [RowID], DataGridColumn) -> Void)? + // For an owner whose rows stand for objects; the grid opens a row only when its commands offer .openRow. + var rowMenuItems: (([RowID], RowID) -> [NSMenuItem])? + var opensRow: ((RowID) -> Void)? private(set) var heldRows = TableRows() private var displayedRows = TableRows() @@ -117,6 +120,14 @@ extension HeldRowsGridAdapter: DataGridActions { func gridSetCheckbox(_ isOn: Bool, rowIDs: [RowID], column: DataGridColumn) { checkboxChange?(isOn, rowIDs, column) } + + func gridOpenRow(_ rowID: RowID) { + opensRow?(rowID) + } + + func gridRowMenuItems(for rowIDs: [RowID], clickedRow: RowID) -> [NSMenuItem] { + rowMenuItems?(rowIDs, clickedRow) ?? [] + } } extension DataGridModel { diff --git a/apple/TableProTests/Views/DataGrid/DataGridEditingTests.swift b/apple/TableProTests/Views/DataGrid/DataGridEditingTests.swift index 3ba71aaa0e..7f404ec355 100644 --- a/apple/TableProTests/Views/DataGrid/DataGridEditingTests.swift +++ b/apple/TableProTests/Views/DataGrid/DataGridEditingTests.swift @@ -17,6 +17,12 @@ final class EditingGridOwner: DataGridDataSource, DataGridActions { weak var model: DataGridModel? private(set) var commits: [(edits: [DataGridResolvedEdit], actionName: String)] = [] private(set) var loadRequests: [[RowID]] = [] + + private(set) var openedRows: [RowID] = [] + + func gridOpenRow(_ rowID: RowID) { + openedRows.append(rowID) + } var loadsValue: ((inout TableRows) -> Void)? init(_ tableRows: TableRows) { @@ -144,6 +150,35 @@ struct EditingGrid { @MainActor struct DataGridEditingTests { + // MARK: - Opening rows + + @Test("A grid whose rows open opens the row on a double click and on Return, and edits nothing") + func openRowTakesDoubleClickAndReturn() { + var configuration = DataGridConfiguration() + configuration.commands = [.openRow] + let grid = EditingGrid(configuration: configuration) + defer { grid.tearDown() } + + grid.controller.handleCellDoubleClick(at: GridCoord(row: 1, displayColumn: 1)) + grid.select(2, 1) + grid.controller.beginEditingActiveCell() + + #expect(grid.owner.openedRows == [.existing(1), .existing(2)]) + #expect(grid.controller.editedCell == nil) + #expect(!grid.model.isEditing) + } + + @Test("A grid whose rows do not open keeps the double click for the cell") + func doubleClickEditsWithoutOpenRow() { + let grid = EditingGrid() + defer { grid.tearDown() } + + grid.controller.handleCellDoubleClick(at: GridCoord(row: 1, displayColumn: 1)) + + #expect(grid.owner.openedRows.isEmpty) + #expect(grid.controller.editedCell == GridCoord(row: 1, displayColumn: 1)) + } + // MARK: - Field lifecycle @Test("Beginning an edit mounts the field in that one cell and hands it the field editor") From 823e3e5509b8cbb2cc94f8e0788ed4c7b49f741a Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Mon, 9 Nov 2026 23:56:55 +0700 Subject: [PATCH 039/123] feat(listing): list any kind, filter by name and act on the object a row names A read cancelled elsewhere with nothing on screen reads once more on the sidebar's lists, then offers Try Again instead of a spinner that waits for nothing. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ViewModels/TableListingViewModel.swift | 149 ++++++- .../Main/Child/MainEditorContentView.swift | 16 +- .../TableListingViewModelTests.swift | 367 +++++++++++++++++- 3 files changed, 500 insertions(+), 32 deletions(-) diff --git a/apple/TablePro/ViewModels/TableListingViewModel.swift b/apple/TablePro/ViewModels/TableListingViewModel.swift index e8322970af..f474453897 100644 --- a/apple/TablePro/ViewModels/TableListingViewModel.swift +++ b/apple/TablePro/ViewModels/TableListingViewModel.swift @@ -3,19 +3,42 @@ // TablePro // +import AppKit import Combine import Foundation +internal struct ObjectListingCount: Equatable { + let shown: Int + let total: Int +} + @MainActor internal final class TableListingViewModel: ObservableObject { @Published private(set) var state: MetadataLoadState = .idle + @Published private(set) var isRefreshing = false + /// A read that ended cancelled with nothing on screen: no read is on its way, so the pane offers + /// Try Again instead of a spinner that would wait for nothing. + @Published private(set) var wasInterrupted = false + @Published private(set) var count: ObjectListingCount? + // View state: it hides rows and fetches nothing. + @Published var filterText = "" { + didSet { + guard filterText != oldValue else { return } + showRows() + onInteraction() + } + } // Outlives the tab's view, so the sort, the selection and the column widths survive a tab switch. let grid = HeldRowsGridAdapter(configuration: DataGridConfiguration(), sortsHeldRows: true) + let target: DatabaseTreeObjectGroup private let scope: DatabaseScope private let loader: TableListingLoader private let metadataProvider: any ScopedMetadataProviding + private let objectSource: any CatalogObjectListSource + private let perform: (ObjectListingAction) -> Void + private let onInteraction: () -> Void private var loadTask: Task? private var generation = 0 private var refreshSubscription: AnyCancellable? @@ -23,66 +46,166 @@ internal final class TableListingViewModel: ObservableObject { init( tabId: UUID, scope: DatabaseScope, + kind: SidebarObjectKind = .table, loader: TableListingLoader, metadataProvider: any ScopedMetadataProviding = DatabaseManager.shared, - refreshRequests: AnyPublisher = AppEvents.shared.tabRefreshRequested.eraseToAnyPublisher() + objectSource: any CatalogObjectListSource = DatabaseTreeMetadataService.shared, + refreshRequests: AnyPublisher = AppEvents.shared.tabRefreshRequested.eraseToAnyPublisher(), + perform: @escaping (ObjectListingAction) -> Void = { _ in }, + onInteraction: @escaping () -> Void = {} ) { self.scope = scope + self.target = DatabaseTreeObjectGroup(database: scope.database, schema: scope.schema, kind: kind) self.loader = loader self.metadataProvider = metadataProvider + self.objectSource = objectSource + self.perform = perform + self.onInteraction = onInteraction refreshSubscription = refreshRequests .filter { $0 == tabId } .sink { [weak self] _ in self?.reload() } + grid.onSortChange = { [weak self] _ in self?.onInteraction() } + grid.rowMenuItems = { [weak self] rowIDs, clicked in + self?.menuItems(for: rowIDs, clicked: clicked) ?? [] + } + grid.opensRow = { [weak self] rowID in self?.open(rowID) } + } + + /// Whether each row names an object, which the name filter and the row commands need. + var rowsNameObjects: Bool { + state.value.map { !$0.items.isEmpty } ?? false } @discardableResult func loadIfNeeded() -> Task? { guard case .idle = state else { return nil } - return reload() + return load(rereading: false) } + // Refresh and Try Again ask the server again; the first load takes a list the sidebar already holds. @discardableResult func reload() -> Task { + load(rereading: true) + } + + func cancel() { + loadTask?.cancel() + generation &+= 1 + isRefreshing = false + wasInterrupted = false + if case .loading = state { + state = .idle + } + } + + // The tab moved to another container or kind: nothing shows this model again, so it stops without publishing. + func retire() { + loadTask?.cancel() + generation &+= 1 + refreshSubscription = nil + } + + private func load(rereading: Bool) -> Task { loadTask?.cancel() generation &+= 1 let token = generation state = state.enteringLoad + isRefreshing = true + wasInterrupted = false let scope = scope + let kind = target.kind let loader = loader let provider = metadataProvider + let source = objectSource let task = Task { [weak self] in - let outcome = await loader.fetch(scope: scope, from: provider) + let outcome: MetadataFetchOutcome + if kind == .table { + outcome = await loader.fetch(scope: scope, from: provider) + } else { + var read = await source.objects(kind.category, in: scope, rereading: rereading) + // The sidebar's own reads can supersede this one. With nothing on screen, read once more, + // which joins the newest read rather than starting another. + if case .cancelled = read, self?.awaitsFirstRows(token) == true { + read = await source.objects(kind.category, in: scope, rereading: false) + } + switch read { + case .fetched(let list): + outcome = .fetched(ObjectListingRows.listing(kind: kind, from: list, scope: scope)) + case .failed(let message): + outcome = .failed(message) + case .cancelled: + outcome = .cancelled + } + } self?.commit(outcome, token: token) } loadTask = task return task } - func cancel() { - loadTask?.cancel() - generation &+= 1 - if case .loading = state { - state = .idle - } + private func awaitsFirstRows(_ token: Int) -> Bool { + guard token == generation, !Task.isCancelled else { return false } + if case .loading = state { return true } + return false } private func commit(_ outcome: MetadataFetchOutcome, token: Int) { guard token == generation else { return } + isRefreshing = false state = state.settled(by: outcome, discardingValue: false) - if case .loaded(let listing) = state { - grid.setRows(listing.rows) + // A cancel from here bumps the generation, so this one came from elsewhere and nothing else is coming. + if case .cancelled = outcome, case .idle = state { + wasInterrupted = true + } + showRows() + } + + private func showRows() { + guard let listing = state.value else { + count = nil + return + } + let shown = ObjectListingFilter.rows(of: listing, matching: filterText) + count = ObjectListingCount(shown: shown.count, total: listing.rows.count) + grid.setRows(shown) + } + + private func menuItems(for rowIDs: [RowID], clicked: RowID) -> [NSMenuItem] { + guard let items = state.value?.items, let clickedItem = items[clicked] else { return [] } + let targets = rowIDs.compactMap { items[$0] } + return ObjectListingMenu.commands(clicked: clickedItem, targets: targets).map { command in + ClosureMenuTarget.item(title: command.title) { [weak self] in self?.run(command.action) } } } + + private func open(_ rowID: RowID) { + guard let item = state.value?.items[rowID] else { return } + run(ObjectListingMenu.primaryAction(for: item)) + } + + private func run(_ action: ObjectListingAction) { + onInteraction() + perform(action) + } } @MainActor internal final class TableListingModelStore { private var models: [UUID: TableListingViewModel] = [:] - func model(forTab tabId: UUID, make: () -> TableListingViewModel) -> TableListingViewModel { + /// A tab keeps its model while it lists the same container and kind. A retarget gets a fresh one, + /// so another kind's rows never stand in for the new kind's while it loads. + func model( + forTab tabId: UUID, + target: DatabaseTreeObjectGroup, + make: () -> TableListingViewModel + ) -> TableListingViewModel { if let existing = models[tabId] { - return existing + if existing.target == target { + return existing + } + existing.retire() } let model = make() models[tabId] = model diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index 10f531ed79..c8e8dbdb63 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -226,14 +226,18 @@ struct MainEditorContentView: View { // MARK: - Table Listing Tab Content private func tableListingContent(tab: QueryTab) -> some View { - let model = tableListingModels.model(forTab: tab.id) { + let scope = DatabaseScope( + connectionId: connection.id, + database: tab.tableContext.databaseName, + schema: tab.tableContext.schemaName + ) + let kind = tab.display.listingKind ?? .table + let target = DatabaseTreeObjectGroup(database: scope.database, schema: scope.schema, kind: kind) + let model = tableListingModels.model(forTab: tab.id, target: target) { TableListingViewModel( tabId: tab.id, - scope: DatabaseScope( - connectionId: connection.id, - database: tab.tableContext.databaseName, - schema: tab.tableContext.schemaName - ), + scope: scope, + kind: kind, loader: TableListingLoader( databaseType: connection.type, slot: EngineNamespaceSlot(databaseType: connection.type) diff --git a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift index 8440368d9a..187c47f700 100644 --- a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift +++ b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift @@ -1,5 +1,6 @@ // A listing tab loads its own rows over a metadata connection; these pin what a refresh, a failure and a late answer leave. +import AppKit import Combine import Foundation @testable import TablePro @@ -38,13 +39,15 @@ private final class ScriptedListingProvider: ScopedMetadataProviding { private let connection: DatabaseConnection private let log = ListingQueryLog() private let pluginListsTables: Bool + private let nameColumn: String private var replies: [ListingReply] = [] private var nextHold: (reached: AsyncGate, release: AsyncGate)? private(set) var requestedScopes: [DatabaseScope] = [] - init(connection: DatabaseConnection, pluginListsTables: Bool = true) { + init(connection: DatabaseConnection, pluginListsTables: Bool = true, nameColumn: String = "name") { self.connection = connection self.pluginListsTables = pluginListsTables + self.nameColumn = nameColumn } var executedQueries: [String] { @@ -75,11 +78,11 @@ private final class ScriptedListingProvider: ScopedMetadataProviding { } switch reply { case .names(let names): - let driver = ListingPluginDriver(names: names, listsTables: pluginListsTables, log: log) + let driver = ListingPluginDriver(names: names, listsTables: pluginListsTables, log: log, column: nameColumn) return try await body(PluginDriverAdapter(connection: connection, pluginDriver: driver)) case .page(let names, let status): let driver = ListingPluginDriver( - names: names, listsTables: pluginListsTables, log: log, isPartial: true, status: status + names: names, listsTables: pluginListsTables, log: log, isPartial: true, status: status, column: nameColumn ) return try await body(PluginDriverAdapter(connection: connection, pluginDriver: driver)) case .failure(let error): @@ -92,6 +95,43 @@ private final class ScriptedListingProvider: ScopedMetadataProviding { } } +private struct ObjectSourceRequest: Equatable { + let category: SidebarObjectCategory + let scope: DatabaseScope + let rereading: Bool +} + +// Answers the way the sidebar's service does, and can hold a read until the test releases it. +@MainActor +private final class ScriptedObjectSource: CatalogObjectListSource { + var reply: MetadataFetchOutcome = .fetched(.routines([])) + // Taken in order before `reply`, for a read that answers differently the next time. + var replies: [MetadataFetchOutcome] = [] + private(set) var requests: [ObjectSourceRequest] = [] + private var nextHold: (reached: AsyncGate, release: AsyncGate)? + + func holdNextRead() -> (reached: AsyncGate, release: AsyncGate) { + let hold = (reached: AsyncGate(), release: AsyncGate()) + nextHold = hold + return hold + } + + func objects( + _ category: SidebarObjectCategory, + in scope: DatabaseScope, + rereading: Bool + ) async -> MetadataFetchOutcome { + requests.append(ObjectSourceRequest(category: category, scope: scope, rereading: rereading)) + let reply = replies.isEmpty ? reply : replies.removeFirst() + if let hold = nextHold { + nextHold = nil + await hold.reached.open() + await hold.release.wait() + } + return reply + } +} + @MainActor struct TableListingViewModelTests { private let connection = TestFixtures.makeConnection(database: "shop", type: .postgresql) @@ -106,15 +146,26 @@ struct TableListingViewModelTests { private func makeViewModel( databaseType: DatabaseType = .postgresql, slot: EngineNamespaceSlot = .schema, - pluginListsTables: Bool = true + pluginListsTables: Bool = true, + nameColumn: String = "name", + kind: SidebarObjectKind = .table, + objectSource: ScriptedObjectSource? = nil, + perform: @escaping (ObjectListingAction) -> Void = { _ in }, + onInteraction: @escaping () -> Void = {} ) -> (TableListingViewModel, ScriptedListingProvider) { - let provider = ScriptedListingProvider(connection: connection, pluginListsTables: pluginListsTables) + let provider = ScriptedListingProvider( + connection: connection, pluginListsTables: pluginListsTables, nameColumn: nameColumn + ) let viewModel = TableListingViewModel( tabId: tabId, scope: scope, + kind: kind, loader: TableListingLoader(databaseType: databaseType, slot: slot), metadataProvider: provider, - refreshRequests: refreshRequests.eraseToAnyPublisher() + objectSource: objectSource ?? ScriptedObjectSource(), + refreshRequests: refreshRequests.eraseToAnyPublisher(), + perform: perform, + onInteraction: onInteraction ) return (viewModel, provider) } @@ -327,13 +378,13 @@ struct TableListingViewModelTests { let openId = UUID() let closingId = UUID() - #expect(store.model(forTab: openId) { open } === open) - #expect(store.model(forTab: openId) { TableListingViewModel( + #expect(store.model(forTab: openId, target: open.target) { open } === open) + #expect(store.model(forTab: openId, target: open.target) { TableListingViewModel( tabId: openId, scope: scope, loader: TableListingLoader(databaseType: .postgresql, slot: .schema) ) } === open) - #expect(store.model(forTab: closingId) { closing } === closing) + #expect(store.model(forTab: closingId, target: closing.target) { closing } === closing) provider.answer(with: .names(["stale"])) let (reached, release) = provider.holdNextRead() @@ -345,7 +396,7 @@ struct TableListingViewModelTests { await load.value #expect(closing.state.erased == .idle) - #expect(store.model(forTab: openId) { closing } === open) + #expect(store.model(forTab: openId, target: open.target) { closing } === open) } // MARK: - Grid @@ -396,6 +447,287 @@ struct TableListingViewModelTests { #expect(gridNames(viewModel) == ["zones", "orders", "accounts"]) #expect(viewModel.grid.model.store.sortState == descending) } + // MARK: - Other kinds + + private func functions(_ names: String...) -> CatalogObjectList { + .routines(names.map { + RoutineInfo(name: $0, kind: .function, schema: "sales", argumentSignature: "(integer)", returnType: "integer", language: "plpgsql") + }) + } + + @Test("Another kind lists the sidebar's own objects of that kind and runs no listing statement") + func otherKindsListTheSidebarObjects() async { + let source = ScriptedObjectSource() + source.reply = .fetched(functions("touch", "audit")) + let (viewModel, provider) = makeViewModel(kind: .function, objectSource: source) + + await viewModel.loadIfNeeded()?.value + + #expect(names(viewModel.state) == ["touch", "audit"]) + #expect(viewModel.target == DatabaseTreeObjectGroup(database: "shop", schema: "sales", kind: .function)) + #expect(source.requests == [ObjectSourceRequest(category: .routine, scope: scope, rereading: false)]) + #expect(provider.executedQueries.isEmpty) + } + + @Test("The first load takes the list the sidebar holds, and a refresh reads it again") + func firstLoadTakesTheListAndRefreshRereads() async { + let source = ScriptedObjectSource() + source.reply = .fetched(functions("touch")) + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + + await viewModel.loadIfNeeded()?.value + await viewModel.reload().value + + #expect(source.requests.map(\.rereading) == [false, true]) + } + + @Test("A refresh of another kind keeps its rows on screen until the new ones land") + func otherKindRefreshKeepsRows() async { + let source = ScriptedObjectSource() + source.reply = .fetched(functions("touch")) + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + await viewModel.reload().value + + source.reply = .fetched(functions("touch", "audit")) + let (reached, release) = source.holdNextRead() + let refresh = viewModel.reload() + await reached.wait() + #expect(names(viewModel.state) == ["touch"]) + #expect(viewModel.isRefreshing) + + await release.open() + await refresh.value + #expect(names(viewModel.state) == ["touch", "audit"]) + #expect(!viewModel.isRefreshing) + } + + @Test("A failed read of another kind says why") + func otherKindFailureCommitsItsMessage() async { + let source = ScriptedObjectSource() + source.reply = .failed("permission denied for schema sales") + let (viewModel, _) = makeViewModel(kind: .trigger, objectSource: source) + + await viewModel.reload().value + + #expect(viewModel.state.erased == .failed("permission denied for schema sales")) + } + + // MARK: - Filter and count + + @Test("The filter narrows the rows and the count, fetches nothing, and keeps the preview") + func filterNarrowsRowsAndCount() async { + var interactions = 0 + let (viewModel, provider) = makeViewModel(onInteraction: { interactions += 1 }) + provider.answer(with: .names(["orders", "order_items", "customers"])) + await viewModel.reload().value + #expect(viewModel.count == ObjectListingCount(shown: 3, total: 3)) + + viewModel.filterText = "ORDER" + + #expect(gridNames(viewModel) == ["orders", "order_items"]) + #expect(viewModel.count == ObjectListingCount(shown: 2, total: 3)) + #expect(provider.executedQueries.count == 1) + #expect(interactions == 1) + + viewModel.filterText = "" + #expect(viewModel.count == ObjectListingCount(shown: 3, total: 3)) + } + + @Test("A refresh applies the filter to the rows it brings back") + func filterSurvivesARefresh() async { + let (viewModel, provider) = makeViewModel() + provider.answer(with: .names(["orders", "customers"])) + await viewModel.reload().value + viewModel.filterText = "cust" + + provider.answer(with: .names(["orders", "customers", "customer_notes"])) + await viewModel.reload().value + + #expect(gridNames(viewModel) == ["customers", "customer_notes"]) + #expect(viewModel.count == ObjectListingCount(shown: 2, total: 3)) + } + + @Test("A header sort keeps the preview") + func sortKeepsThePreview() async { + var interactions = 0 + let (viewModel, provider) = makeViewModel(onInteraction: { interactions += 1 }) + provider.answer(with: .names(["orders", "customers"])) + await viewModel.reload().value + + viewModel.grid.model.setSort(SortState(columns: [SortColumn(columnIndex: 0, direction: .ascending)], source: .user)) + + #expect(interactions == 1) + } + + // MARK: - Row actions + + @Test("Each row of a Tables listing stands for its table in the tab's own schema") + func tablesListingNamesItsRows() async { + let (viewModel, provider) = makeViewModel() + provider.answer(with: .names(["orders"])) + + await viewModel.reload().value + + #expect(viewModel.state.value?.items[.existing(0)] == .relation(name: "orders", schema: "sales", type: .table)) + #expect(viewModel.rowsNameObjects) + } + + @Test("A double click opens the row's object and keeps the preview; the row's menu offers its commands") + func rowOpensAndOffersItsCommands() async { + var actions: [ObjectListingAction] = [] + var interactions = 0 + let (viewModel, provider) = makeViewModel(perform: { actions.append($0) }, onInteraction: { interactions += 1 }) + provider.answer(with: .names(["orders"])) + await viewModel.reload().value + let orders = ObjectListingItem.relation(name: "orders", schema: "sales", type: .table) + + viewModel.grid.gridOpenRow(.existing(0)) + let titles = viewModel.grid.gridRowMenuItems(for: [.existing(0)], clickedRow: .existing(0)).map(\.title) + + #expect(actions == [.open(orders)]) + #expect(interactions == 1) + #expect(titles == [ + String(localized: "Open in New Tab"), String(localized: "Show Structure"), String(localized: "Copy Name"), + ]) + } + + @Test("After a sort and a filter, a row's command acts on the object that row shows") + func rowActionsFollowTheShownRow() async throws { + var actions: [ObjectListingAction] = [] + let (viewModel, provider) = makeViewModel(perform: { actions.append($0) }) + provider.answer(with: .names(["orders", "customers", "order_items"])) + await viewModel.reload().value + viewModel.grid.model.setSort(SortState(columns: [SortColumn(columnIndex: 0, direction: .descending)], source: .user)) + viewModel.filterText = "order" + + let second = try #require(viewModel.grid.model.rowID(at: 1)) + viewModel.grid.gridOpenRow(second) + + #expect(gridNames(viewModel) == ["orders", "order_items"]) + #expect(actions == [.open(.relation(name: "order_items", schema: "sales", type: .table))]) + } + + @Test("A listing with no name column has no filter and no row commands") + func listingWithoutNamesHasNoRowActions() async { + var actions: [ObjectListingAction] = [] + let (viewModel, provider) = makeViewModel( + databaseType: .redis, slot: .database, pluginListsTables: false, nameColumn: "Key", + perform: { actions.append($0) } + ) + provider.answer(with: .names(["session:1"])) + await viewModel.reload().value + + viewModel.grid.gridOpenRow(.existing(0)) + + #expect(!viewModel.rowsNameObjects) + #expect(viewModel.grid.gridRowMenuItems(for: [.existing(0)], clickedRow: .existing(0)).isEmpty) + #expect(actions.isEmpty) + } + + // MARK: - Store + + @Test("A tab moved to another kind gets a fresh model, and the old one stops answering") + func storeReplacesTheModelOfAnotherTarget() async { + let store = TableListingModelStore() + let tab = UUID() + let (tables, provider) = makeViewModel() + let (views, _) = makeViewModel(kind: .view) + #expect(store.model(forTab: tab, target: tables.target) { tables } === tables) + + provider.answer(with: .names(["stale"])) + let (reached, release) = provider.holdNextRead() + let load = tables.reload() + await reached.wait() + + #expect(store.model(forTab: tab, target: views.target) { views } === views) + await release.open() + await load.value + + #expect(tables.state.value == nil) + #expect(store.model(forTab: tab, target: views.target) { tables } === views) + } + + // MARK: - A read cancelled elsewhere + + // The sidebar's own reads can supersede the pane's. Nothing else is coming, so a spinner would wait forever. + @Test("A read the sidebar keeps superseding reads once more, then offers Try Again instead of a spinner") + func supersededReadNeverLeavesASpinner() async { + let source = ScriptedObjectSource() + source.replies = [.cancelled, .cancelled] + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + + await viewModel.loadIfNeeded()?.value + + #expect(source.requests.map(\.rereading) == [false, false]) + #expect(viewModel.state.erased == .idle) + #expect(viewModel.wasInterrupted) + #expect(!viewModel.isRefreshing) + + source.reply = .fetched(functions("touch")) + await viewModel.reload().value + #expect(names(viewModel.state) == ["touch"]) + #expect(!viewModel.wasInterrupted) + } + + @Test("A read superseded once reads again and shows what it finds") + func supersededReadReadsAgain() async { + let source = ScriptedObjectSource() + source.replies = [.cancelled] + source.reply = .fetched(functions("touch")) + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + + await viewModel.loadIfNeeded()?.value + + #expect(names(viewModel.state) == ["touch"]) + #expect(source.requests.count == 2) + #expect(!viewModel.wasInterrupted) + } + + @Test("A cancelled refresh keeps the rows on screen and reads nothing more") + func cancelledRefreshKeepsTheRows() async { + let source = ScriptedObjectSource() + source.reply = .fetched(functions("touch")) + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + await viewModel.reload().value + + source.replies = [.cancelled] + await viewModel.reload().value + + #expect(names(viewModel.state) == ["touch"]) + #expect(source.requests.count == 2) + #expect(!viewModel.wasInterrupted) + } + + @Test("A Tables read cancelled with nothing on screen offers Try Again, and loads again when asked") + func cancelledTablesReadOffersTryAgain() async throws { + let (viewModel, provider) = makeViewModel() + provider.answer(with: .failure(CancellationError())) + + await viewModel.reload().value + #expect(viewModel.wasInterrupted) + + provider.answer(with: .names(["customers"])) + let again = try #require(viewModel.loadIfNeeded()) + await again.value + #expect(names(viewModel.state) == ["customers"]) + #expect(!viewModel.wasInterrupted) + } + + @Test("A load this tab cancelled is not an interruption: the tab is closing") + func ownCancelIsNotAnInterruption() async { + let (viewModel, provider) = makeViewModel() + provider.answer(with: .names(["stale"])) + let (reached, release) = provider.holdNextRead() + let load = viewModel.reload() + await reached.wait() + + viewModel.cancel() + await release.open() + await load.value + + #expect(!viewModel.wasInterrupted) + } + } private final class ListingPluginDriver: PluginDriverStub, @unchecked Sendable { @@ -404,13 +736,22 @@ private final class ListingPluginDriver: PluginDriverStub, @unchecked Sendable { private let log: ListingQueryLog private let isPartial: Bool private let status: String? - - init(names: [String], listsTables: Bool, log: ListingQueryLog, isPartial: Bool = false, status: String? = nil) { + private let column: String + + init( + names: [String], + listsTables: Bool, + log: ListingQueryLog, + isPartial: Bool = false, + status: String? = nil, + column: String = "name" + ) { self.names = names self.listsTables = listsTables self.log = log self.isPartial = isPartial self.status = status + self.column = column } func allTablesMetadataSQL(schema: String?) -> String? { @@ -420,7 +761,7 @@ private final class ListingPluginDriver: PluginDriverStub, @unchecked Sendable { func execute(query: String) async throws -> PluginQueryResult { log.record(query) return PluginQueryResult( - columns: ["name"], + columns: [column], columnTypeNames: ["TEXT"], rows: names.map { [.text($0)] }, rowsAffected: 0, From 4fe2d8c84602f688b2241e553d982e00810b9dac Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:07:29 +0700 Subject: [PATCH 040/123] feat(listing): open a container's objects as a preview or a kept tab, and act on its rows Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainContentCoordinator+Navigation.swift | 23 +-- ...MainContentCoordinator+ObjectListing.swift | 102 ++++++++++++++ .../MainContentCoordinator+TabClosing.swift | 8 ++ ...abaseTreeOutlineCoordinator+Commands.swift | 2 +- .../Main/CoordinatorTableListingTests.swift | 133 +++++++++++++++++- 5 files changed, 245 insertions(+), 23 deletions(-) create mode 100644 apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift index dec5899f1f..c7a50ada63 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift @@ -437,26 +437,13 @@ extension MainContentCoordinator { tabManager.promotePreviewTab(id: selectedTabId) } - func showAllTablesMetadata() { - guard allTablesListing() != nil else { return } - openTableListing() - } - - /// A read-only grid of the browsed container's tables, never an editor holding the statement that - /// lists them: the tab builds its statement from the plugin each time it loads. - func openTableListing() { + /// The flat list's sections are the browsed container's, so their Show Objects lists that one. + func showBrowsedObjects(_ kind: SidebarObjectKind) { let schemaName = EngineNamespaceSlot(databaseType: connection.type) == .schema ? browseSchemaName : nil - let kindTitle = SidebarObjectKind.table.title( - tableEntityName: PluginManager.shared.tableEntityName(for: connection.type) - ) - let tabId = tabManager.addTableListingTab( - title: QueryTabManager.tableListingTitle(kindTitle: kindTitle, schemaName: schemaName), - databaseName: browseDatabaseName, - schemaName: schemaName + showObjects( + DatabaseTreeObjectGroup(database: browseDatabaseName, schema: schemaName, kind: kind), + asPreview: false ) - /// Asking again for a listing already open brings it up to date, the way Refresh would. A tab - /// opened just now loads when its view first appears, and nothing is listening for this yet. - AppEvents.shared.tabRefreshRequested.send(tabId) } /// The schema the sidebar lists, which a cross-database tab can leave the shared driver off. diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift new file mode 100644 index 0000000000..7d96cccbf9 --- /dev/null +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift @@ -0,0 +1,102 @@ +// +// MainContentCoordinator+ObjectListing.swift +// TablePro +// + +import Combine +import Foundation +import TableProPluginKit + +extension MainContentCoordinator { + /// A sidebar selection previews a container's objects and the next selection replaces them; a + /// menu command opens them to keep, and brings a tab already open up to date. + func showObjects(_ target: DatabaseTreeObjectGroup, asPreview: Bool) { + let schemaName = target.schema?.nilIfEmpty + let isOpen = tabManager.tableListingTab(databaseName: target.database, schemaName: schemaName) != nil + let replaced = asPreview && !isOpen ? replaceablePreview : nil + if let replaced { + releasePreviewForReplacement(replaced) + } + let tabId = tabManager.addTableListingTab( + title: listingTitle(kind: target.kind, schemaName: schemaName), + databaseName: target.database, + schemaName: schemaName, + kind: target.kind, + isPreview: asPreview, + replacing: replaced?.id + ) + guard !asPreview else { return } + /// Asking again for a listing already open brings it up to date, the way Refresh would. A tab + /// opened just now loads when its view first appears, and nothing is listening for this yet. + AppEvents.shared.tabRefreshRequested.send(tabId) + } + + /// The kind picker is the user using the tab, so it keeps a preview. + func selectListingKind(_ kind: SidebarObjectKind, inTab tabId: UUID) { + tabManager.promotePreviewTab(id: tabId) + retargetListing(tabId, to: kind) + } + + /// An engine that stopped fetching the tab's kind shows Tables; that is not the user keeping the tab. + func adoptListingKind(_ kind: SidebarObjectKind, inTab tabId: UUID) { + retargetListing(tabId, to: kind) + } + + /// A row reaches its object the way the sidebar's row does, in the tab's own database. The tab is + /// kept first: a table opened from a preview would otherwise take the preview's place. + func performListingAction(_ action: ObjectListingAction, fromTab tabId: UUID) { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId && $0.tabType == .tableListing }) else { return } + tabManager.promotePreviewTab(id: tabId) + let database = tab.tableContext.databaseName + switch action { + case .open(let item): + openListedRelation(item, database: database, showStructure: false, forceNewTab: false) + case .openInNewTab(let item): + openListedRelation(item, database: database, showStructure: false, forceNewTab: true) + case .showStructure(let item): + openListedRelation(item, database: database, showStructure: true, forceNewTab: false) + case .showSource(let item): + guard let objectRef = item.sourceRef(database: database) else { return } + showObjectSource(objectRef) + case .copyNames(let names): + ClipboardService.shared.writeText(names.joined(separator: ",")) + } + } + + private func openListedRelation(_ item: ObjectListingItem, database: String, showStructure: Bool, forceNewTab: Bool) { + guard case .relation(let name, let schema, let type) = item else { return } + openTableTab( + name, + schema: schema, + database: database, + showStructure: showStructure, + isView: !type.allowsRowEditing, + objectType: type, + forceNonPreview: true, + activateGridFocus: showStructure, + forceNewTab: forceNewTab + ) + } + + private func retargetListing(_ tabId: UUID, to kind: SidebarObjectKind) { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId && $0.tabType == .tableListing }) else { return } + tabManager.setTableListingKind( + kind, + title: listingTitle(kind: kind, schemaName: tab.tableContext.schemaName), + tabId: tabId + ) + } + + private func listingTitle(kind: SidebarObjectKind, schemaName: String?) -> String { + QueryTabManager.tableListingTitle( + kindTitle: kind.title(tableEntityName: PluginManager.shared.tableEntityName(for: connection.type)), + schemaName: schemaName + ) + } + + /// Kept, pinned and busy tabs are never taken over: the rule a table preview follows. + private var replaceablePreview: QueryTab? { + guard let tab = tabManager.selectedTab, tab.isPreview, isActiveTabReusable else { return nil } + return tab + } +} diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift index 3a7f159b30..1b460b2c1c 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift @@ -64,6 +64,14 @@ extension MainContentCoordinator { } } + // A preview the next sidebar selection replaces. Not a user close, so nothing goes to Reopen Closed Tab. + func releasePreviewForReplacement(_ tab: QueryTab) { + flushColumnLayoutPersistence() + saveLastFilters(of: tab) + releaseResources(of: tab) + releaseExecution(of: tab) + } + // All keyed by tab id, so a stale entry would hand another tab's state to the next tab given that id. func cleanupTabCaches(openTabIds: Set) { prune(&displayFormatsCache, keeping: openTabIds) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift index ce7738617b..4835b71a77 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift @@ -128,7 +128,7 @@ extension DatabaseTreeOutlineCoordinator { case .copyObjectsTo, .copyContainerTo, .duplicateDatabase, .searchContainer: performSheetCommand(command) case .showAllTablesMetadata: - mainCoordinator?.showAllTablesMetadata() + mainCoordinator?.showBrowsedObjects(.table) case .refreshObjectKind(let kind): refreshObjectKind(kind) case .refreshContainerObjectKind(let group): diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index 71fdeb5abb..8a24552ac7 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -35,7 +35,7 @@ struct CoordinatorTableListingTests { let (coordinator, tabManager, log) = makeCoordinator() defer { coordinator.teardown() } - coordinator.openTableListing() + coordinator.showBrowsedObjects(.table) let tab = try #require(tabManager.selectedTab) #expect(tab.tabType == .tableListing) @@ -55,10 +55,10 @@ struct CoordinatorTableListingTests { let subscription = AppEvents.shared.tabRefreshRequested.sink { refreshed.append($0) } defer { subscription.cancel() } - coordinator.openTableListing() + coordinator.showBrowsedObjects(.table) let first = try #require(tabManager.selectedTabId) tabManager.addTab(initialQuery: "SELECT 1", databaseName: "shop") - coordinator.openTableListing() + coordinator.showBrowsedObjects(.table) #expect(tabManager.selectedTabId == first) #expect(tabManager.tabs.filter { $0.tabType == .tableListing }.count == 1) @@ -69,7 +69,7 @@ struct CoordinatorTableListingTests { func refreshReloadsTheListing() throws { let (coordinator, tabManager, _) = makeCoordinator() defer { coordinator.teardown() } - coordinator.openTableListing() + coordinator.showBrowsedObjects(.table) let id = try #require(tabManager.selectedTabId) var refreshed: [UUID] = [] let subscription = AppEvents.shared.tabRefreshRequested.sink { refreshed.append($0) } @@ -79,4 +79,129 @@ struct CoordinatorTableListingTests { #expect(refreshed == [id]) } + + private func group(_ database: String, _ kind: SidebarObjectKind = .table) -> DatabaseTreeObjectGroup { + DatabaseTreeObjectGroup(database: database, schema: nil, kind: kind) + } + + @Test("Show Objects opens the clicked container and kind, not the browsed one, to keep") + func showObjectsOpensTheClickedContainer() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + + coordinator.showObjects(group("archive", .view), asPreview: false) + + let tab = try #require(tabManager.selectedTab) + #expect(tab.tabType == .tableListing) + #expect(tab.tableContext.databaseName == "archive") + #expect(tab.display.listingKind == .view) + #expect(tab.title == "Views") + #expect(!tab.isPreview) + } + + @Test("A selection previews a container's objects, and the next selection takes the preview's place") + func selectionPreviewsAndReplaces() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + tabManager.addTab(initialQuery: "SELECT 1", databaseName: "shop") + let kept = try #require(tabManager.selectedTabId) + + coordinator.showObjects(group("shop"), asPreview: true) + let preview = try #require(tabManager.selectedTab) + coordinator.showObjects(group("archive", .function), asPreview: true) + + let replacement = try #require(tabManager.selectedTab) + #expect(preview.isPreview) + #expect(replacement.id != preview.id) + #expect(tabManager.tabs.map(\.id) == [kept, replacement.id]) + #expect(replacement.isPreview) + #expect(replacement.tableContext.databaseName == "archive") + #expect(replacement.display.listingKind == .function) + } + + @Test("A selection on a container whose objects are open retargets that tab and leaves it a preview") + func selectionRetargetsTheContainersTab() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("shop"), asPreview: true) + let id = try #require(tabManager.selectedTabId) + + coordinator.showObjects(group("shop", .trigger), asPreview: true) + + #expect(tabManager.tabs.map(\.id) == [id]) + #expect(tabManager.selectedTab?.display.listingKind == .trigger) + #expect(tabManager.selectedTab?.isPreview == true) + } + + @Test("A table preview gives its place to the objects a selection opens") + func tablePreviewGivesWay() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + try tabManager.addTableTab(tableName: "orders", databaseType: .mysql, databaseName: "shop", isPreview: true) + let table = try #require(tabManager.selectedTabId) + + coordinator.showObjects(group("shop"), asPreview: true) + + #expect(tabManager.tabs.count == 1) + #expect(tabManager.selectedTab?.tabType == .tableListing) + #expect(tabManager.selectedTabId != table) + } + + @Test("A selection never replaces a tab the user kept") + func keptTabsStay() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("shop"), asPreview: false) + + coordinator.showObjects(group("archive"), asPreview: true) + + #expect(tabManager.tabs.count == 2) + } + + @Test("Picking a kind retargets the tab, relabels it and keeps the preview") + func pickingAKindKeepsThePreview() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("shop"), asPreview: true) + let id = try #require(tabManager.selectedTabId) + + coordinator.selectListingKind(.view, inTab: id) + + let tab = try #require(tabManager.selectedTab) + #expect(tab.id == id) + #expect(tab.display.listingKind == .view) + #expect(tab.title == "Views") + #expect(!tab.isPreview) + } + + @Test("Falling back to Tables relabels the tab and leaves a preview a preview") + func fallbackKeepsThePreview() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("shop", .function), asPreview: true) + let id = try #require(tabManager.selectedTabId) + + coordinator.adoptListingKind(.table, inTab: id) + + let tab = try #require(tabManager.selectedTab) + #expect(tab.display.listingKind == nil) + #expect(tab.title == "Tables") + #expect(tab.isPreview) + } + + @Test("A row opens its table in the listing's own database as a kept tab, and keeps the listing") + func rowOpensItsTableInTheListingsDatabase() throws { + let (coordinator, tabManager, log) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("archive"), asPreview: true) + let listing = try #require(tabManager.selectedTabId) + + coordinator.performListingAction(.open(.relation(name: "orders", schema: nil, type: .table)), fromTab: listing) + + let payload = try #require(log.payloads.last) + #expect(payload.tableName == "orders") + #expect(payload.databaseName == "archive") + #expect(!payload.isPreview) + #expect(tabManager.tabs.first { $0.id == listing }?.isPreview == false) + } } From 862ebe746f419cb9cfacfaf50eaac2e93833f484 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:16:47 +0700 Subject: [PATCH 041/123] feat(listing): add the kind picker, name filter, count and Refresh to the Objects tab The count reads "12 objects" or "3 of 12 objects", since the picker names the kind. A read that stopped with nothing on screen offers Try Again. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Main/Child/MainEditorContentView.swift | 46 +++++++++-- .../Views/TableListing/ObjectListingBar.swift | 78 +++++++++++++++++++ .../TableListing/TableListingTabView.swift | 57 ++++++++++---- 3 files changed, 157 insertions(+), 24 deletions(-) create mode 100644 apple/TablePro/Views/TableListing/ObjectListingBar.swift diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index c8e8dbdb63..106c8ae106 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -156,7 +156,8 @@ struct MainEditorContentView: View { usersRolesViewModels = usersRolesViewModels.filter { openTabIds.contains($0.key) } queryInsightsViewModels = queryInsightsViewModels.filter { openTabIds.contains($0.key) } tableHealthViewModels = tableHealthViewModels.filter { openTabIds.contains($0.key) } - tableListingModels.retainTabs(openTabIds) + // A listing a table click took over keeps its id, and its model must go with the listing. + tableListingModels.retainTabs(Set(tabManager.tabs.filter { $0.tabType == .tableListing }.map(\.id))) SchemaProviderRegistry.shared.reclaimUnheldProviders(for: connectionId) } .onChange(of: tabManager.selectedTabId) { _ in @@ -226,26 +227,57 @@ struct MainEditorContentView: View { // MARK: - Table Listing Tab Content private func tableListingContent(tab: QueryTab) -> some View { + let declared = connection.type.declaredObjectKinds + let kind = ObjectListingKinds.effective(tab.display.listingKind ?? .table, declared: declared) let scope = DatabaseScope( connectionId: connection.id, database: tab.tableContext.databaseName, schema: tab.tableContext.schemaName ) - let kind = tab.display.listingKind ?? .table let target = DatabaseTreeObjectGroup(database: scope.database, schema: scope.schema, kind: kind) - let model = tableListingModels.model(forTab: tab.id, target: target) { + let tabId = tab.id + let model = tableListingModels.model(forTab: tabId, target: target) { TableListingViewModel( - tabId: tab.id, + tabId: tabId, scope: scope, kind: kind, loader: TableListingLoader( databaseType: connection.type, slot: EngineNamespaceSlot(databaseType: connection.type) - ) + ), + perform: { [weak coordinator = self.coordinator] action in + coordinator?.performListingAction(action, fromTab: tabId) + }, + onInteraction: { [weak tabManager = self.tabManager] in + tabManager?.promotePreviewTab(id: tabId) + } ) } - return TableListingTabView(model: model, databaseType: connection.type) - .id(tab.id) + let tableEntityName = PluginManager.shared.tableEntityName(for: connection.type) + return TableListingTabView( + model: model, + databaseType: connection.type, + kinds: ObjectListingKinds.available(itemCounts: listedObjectCounts(in: scope), declared: declared, current: kind), + kindTitle: { $0.title(tableEntityName: tableEntityName) }, + onSelectKind: { coordinator.selectListingKind($0, inTab: tabId) } + ) + .task(id: target) { + if (tab.display.listingKind ?? .table) != kind { + coordinator.adoptListingKind(kind, inTab: tabId) + } + // The picker offers the groups the sidebar shows, so the container's lists are read once here. + await treeService.loadObjects(connectionId: scope.connectionId, database: scope.database, schema: scope.schema) + } + .id(tab.id) + } + + private func listedObjectCounts(in scope: DatabaseScope) -> [SidebarObjectKind: Int] { + ObjectListingKinds.itemCounts( + tables: treeService.tables(connectionId: scope.connectionId, database: scope.database, schema: scope.schema), + routines: treeService.routines(connectionId: scope.connectionId, database: scope.database, schema: scope.schema), + triggers: treeService.triggers(connectionId: scope.connectionId, database: scope.database, schema: scope.schema), + types: treeService.userDefinedTypes(connectionId: scope.connectionId, database: scope.database, schema: scope.schema) + ) } // MARK: - Version History Tab Content diff --git a/apple/TablePro/Views/TableListing/ObjectListingBar.swift b/apple/TablePro/Views/TableListing/ObjectListingBar.swift new file mode 100644 index 0000000000..29b1f5cb45 --- /dev/null +++ b/apple/TablePro/Views/TableListing/ObjectListingBar.swift @@ -0,0 +1,78 @@ +// +// ObjectListingBar.swift +// TablePro +// + +import SwiftUI + +internal struct ObjectListingBar: View { + @ObservedObject var model: TableListingViewModel + let kinds: [SidebarObjectKind] + let kindTitle: (SidebarObjectKind) -> String + let onSelectKind: (SidebarObjectKind) -> Void + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 8) { + Picker(String(localized: "Object Kind"), selection: kindSelection) { + ForEach(kinds, id: \.self) { kind in + Text(kindTitle(kind)).tag(kind) + } + } + .labelsHidden() + .pickerStyle(.menu) + .fixedSize() + .accessibilityIdentifier("objects-kind-picker") + + NativeSearchField( + text: $model.filterText, + placeholder: String(localized: "Filter by Name"), + controlSize: .small, + maxWidth: 240, + accessibilityIdentifier: "objects-name-filter" + ) + .disabled(!model.rowsNameObjects) + + Spacer(minLength: 8) + + if let count = model.count { + ObjectListingCountText(count: count) + .font(.callout) + .foregroundStyle(.secondary) + .monospacedDigit() + } + + PaneRefreshControls( + isRefreshing: model.isRefreshing, + lastRefreshDate: nil, + accessibilityIdentifier: "objects-refresh-button" + ) { + model.reload() + } + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + + Divider() + } + .paneBarBackground() + } + + private var kindSelection: Binding { + Binding(get: { model.target.kind }, set: { onSelectKind($0) }) + } +} + +// The picker names the kind, so the count says objects. The number sits inside the inflect span, so the +// noun agrees with it in every language. +internal struct ObjectListingCountText: View { + let count: ObjectListingCount + + var body: some View { + if count.shown == count.total { + Text("^[\(count.total) object](inflect: true)") + } else { + Text("\(count.shown) of ^[\(count.total) object](inflect: true)") + } + } +} diff --git a/apple/TablePro/Views/TableListing/TableListingTabView.swift b/apple/TablePro/Views/TableListing/TableListingTabView.swift index 44fd926e3b..08aaf24cb4 100644 --- a/apple/TablePro/Views/TableListing/TableListingTabView.swift +++ b/apple/TablePro/Views/TableListing/TableListingTabView.swift @@ -9,31 +9,36 @@ import SwiftUI internal struct TableListingTabView: View { @ObservedObject var model: TableListingViewModel let databaseType: DatabaseType + let kinds: [SidebarObjectKind] + let kindTitle: (SidebarObjectKind) -> String + let onSelectKind: (SidebarObjectKind) -> Void var body: some View { - content - .task { model.loadIfNeeded() } + VStack(spacing: 0) { + ObjectListingBar( + model: model, + kinds: kinds, + kindTitle: kindTitle, + onSelectKind: onSelectKind + ) + content + } + // Keyed by target: a retarget hands this view a fresh model that has not loaded yet. + .task(id: model.target) { model.loadIfNeeded() } } @ViewBuilder private var content: some View { switch model.state { + // Nothing is on its way, so a spinner would wait forever. + case .idle where model.wasInterrupted: + failure(String(localized: "The read stopped before it finished.")) case .idle, .loading: ProgressView() .frame(maxWidth: .infinity, maxHeight: .infinity) .gridStandInBackground() case .failed(let message): - UnavailableStateView { - Label(String(localized: "Can't List Tables"), systemImage: "exclamationmark.triangle") - } description: { - Text(message) - } actions: { - Button(String(localized: "Try Again")) { - model.reload() - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .gridStandInBackground() + failure(message) case .loaded(let listing) where listing.rows.rows.isEmpty: emptyState(listing) case .loaded(let listing): @@ -46,6 +51,20 @@ internal struct TableListingTabView: View { } } + private func failure(_ message: String) -> some View { + UnavailableStateView { + Label(model.target.kind.listingFailureTitle, systemImage: "exclamationmark.triangle") + } description: { + Text(message) + } actions: { + Button(String(localized: "Try Again")) { + model.reload() + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .gridStandInBackground() + } + private func emptyState(_ listing: TableListing) -> some View { Group { if listing.isIncomplete { @@ -55,7 +74,7 @@ internal struct TableListingTabView: View { description: listing.notice.map { Text($0) } ) } else { - UnavailableStateView(String(localized: "No Tables"), systemImage: "tablecells") + UnavailableStateView(model.target.kind.listingEmptyTitle, systemImage: model.target.kind.iconName) } } .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -75,16 +94,20 @@ internal struct TableListingTabView: View { private var rowsGrid: some View { DataGridView(model: model.grid.model) - .onAppear { model.grid.model.configuration = configuration } + .onAppear { model.grid.model.configuration = configuration(opensRows: model.rowsNameObjects) } + .onChange(of: model.rowsNameObjects) { opensRows in + model.grid.model.configuration = configuration(opensRows: opensRows) + } } - private var configuration: DataGridConfiguration { + // A row that names an object opens it; a shell command's rows keep the cell viewer. + private func configuration(opensRows: Bool) -> DataGridConfiguration { var configuration = DataGridConfiguration() configuration.traits = DataGridEngineTraits(databaseType: databaseType) configuration.showRowNumbers = true configuration.supportsValueFilter = false configuration.appliesRowCopyFormat = true - configuration.commands = [.freezeColumns, .displayAs] + configuration.commands = opensRows ? [.freezeColumns, .displayAs, .openRow] : [.freezeColumns, .displayAs] return configuration } } From 78bdacd6b0308dbf15f5fa7022c01d41b535b65b Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:22:22 +0700 Subject: [PATCH 042/123] feat(settings): add the setting to show objects when a container is selected Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Models/Settings/GeneralSettings.swift | 7 +++++++ apple/TablePro/Views/Settings/GeneralSettingsView.swift | 3 +++ apple/TableProTests/Models/GeneralSettingsTests.swift | 1 + 3 files changed, 11 insertions(+) diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 0182a79ee7..78e9361cd4 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -61,6 +61,7 @@ struct GeneralSettings: Codable, Equatable { var queryTimeoutSeconds: Int var shareAnalytics: Bool var showRecentTables: Bool + var showsObjectsOnSelection: Bool var showObjectComments: Bool var showObjectIcons: Bool var showSystemContainers: Bool @@ -77,6 +78,7 @@ struct GeneralSettings: Codable, Equatable { queryTimeoutSeconds: 60, shareAnalytics: true, showRecentTables: false, + showsObjectsOnSelection: false, showObjectComments: true, showObjectIcons: true, showSystemContainers: false, @@ -94,6 +96,7 @@ struct GeneralSettings: Codable, Equatable { queryTimeoutSeconds: Int = 60, shareAnalytics: Bool = true, showRecentTables: Bool = false, + showsObjectsOnSelection: Bool = false, showObjectComments: Bool = true, showObjectIcons: Bool = true, showSystemContainers: Bool = false, @@ -109,6 +112,7 @@ struct GeneralSettings: Codable, Equatable { self.queryTimeoutSeconds = queryTimeoutSeconds self.shareAnalytics = shareAnalytics self.showRecentTables = showRecentTables + self.showsObjectsOnSelection = showsObjectsOnSelection self.showObjectComments = showObjectComments self.showObjectIcons = showObjectIcons self.showSystemContainers = showSystemContainers @@ -128,6 +132,9 @@ struct GeneralSettings: Codable, Equatable { queryTimeoutSeconds = container.decodeSetting(.queryTimeoutSeconds, default: fallback.queryTimeoutSeconds) shareAnalytics = container.decodeSetting(.shareAnalytics, default: fallback.shareAnalytics) showRecentTables = container.decodeSetting(.showRecentTables, default: fallback.showRecentTables) + showsObjectsOnSelection = container.decodeSetting( + .showsObjectsOnSelection, default: fallback.showsObjectsOnSelection + ) showObjectComments = container.decodeSetting(.showObjectComments, default: fallback.showObjectComments) showObjectIcons = container.decodeSetting(.showObjectIcons, default: fallback.showObjectIcons) showSystemContainers = container.decodeSetting(.showSystemContainers, default: fallback.showSystemContainers) diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 3da21219a9..f556dc6907 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -70,6 +70,9 @@ struct GeneralSettingsView: View { 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 objects when a database, schema or group is selected", isOn: $settings.showsObjectsOnSelection) + .help("Clicking a database, schema or object group in the sidebar lists its objects in the main area. Show Objects in the row's menu lists them either way.") + 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.") diff --git a/apple/TableProTests/Models/GeneralSettingsTests.swift b/apple/TableProTests/Models/GeneralSettingsTests.swift index 991468ecbd..9abf6fe439 100644 --- a/apple/TableProTests/Models/GeneralSettingsTests.swift +++ b/apple/TableProTests/Models/GeneralSettingsTests.swift @@ -65,6 +65,7 @@ struct GeneralSettingsBoolSettingTests { static let settings = [ BoolSetting(key: "shareAnalytics", defaultValue: true), BoolSetting(key: "showRecentTables", defaultValue: false), + BoolSetting(key: "showsObjectsOnSelection", defaultValue: false), BoolSetting(key: "showObjectComments", defaultValue: true), BoolSetting(key: "showObjectIcons", defaultValue: true), BoolSetting(key: "showSystemContainers", defaultValue: false), From 3cbc5ac2b53dad20dd3cfd2fcaabd40c87218e29 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:29:49 +0700 Subject: [PATCH 043/123] feat(sidebar): show a selected database, schema or group's objects when the setting is on Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../DatabaseTreeOutlineCoordinator.swift | 27 ++++++++++ .../Views/Sidebar/DatabaseTreeSelection.swift | 39 +++++++++++++++ .../Sidebar/DatabaseTreeSelectionTests.swift | 50 +++++++++++++++++++ 3 files changed, 116 insertions(+) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 89584a37d4..825f7bedf2 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -992,6 +992,7 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { openRedis(redisNode) } else { publishSelection() + showObjectsForSelection(nodes) } lastSelection = refs } @@ -1020,6 +1021,32 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work) } + /// With the setting on, a container or group row lists its objects as a preview, the way a table + /// row previews the table. A held arrow key waits out the burst, as a table open does. + private func showObjectsForSelection(_ nodes: [DatabaseTreeNode]) { + guard let mainCoordinator, + let target = DatabaseTreeSelection.selectionObjectsTarget( + selectedNodes: nodes, + showsObjectsOnSelection: AppSettingsManager.shared.general.showsObjectsOnSelection, + databaseHoldsSchemas: supportsSchemaLevel, + hierarchicalDatabase: browsingDatabase ?? "" + ), + target.kind != .table || mainCoordinator.allTablesListing() != nil + else { return } + let asPreview = AppSettingsManager.shared.tabs.enablePreviewTabs + pendingOpenWork?.cancel() + pendingOpenWork = nil + guard isAutorepeatingSelection else { + mainCoordinator.showObjects(target, asPreview: asPreview) + return + } + let work = DispatchWorkItem { [weak self] in + self?.mainCoordinator?.showObjects(target, asPreview: asPreview) + } + pendingOpenWork = work + DispatchQueue.main.asyncAfter(deadline: .now() + NSEvent.keyRepeatInterval, execute: work) + } + private func makeCell() -> DatabaseTreeCellView { let cell = DatabaseTreeCellView() cell.identifier = Self.cellIdentifier diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift index 2bdda6a750..806ae4689c 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift @@ -66,4 +66,43 @@ internal enum DatabaseTreeSelection { guard selectedNodes.count == 1 else { return nil } return SelectionDelta.singleAddition(old: previousRefs, new: newRefs) } + + /// The container and kind a row stands for. A database row on an engine grouped by schema holds + /// schemas, not objects, so it names none; each schema does. + internal static func objectsTarget( + of kind: DatabaseTreeNode.Kind, + databaseHoldsSchemas: Bool, + hierarchicalDatabase: String + ) -> DatabaseTreeObjectGroup? { + switch kind { + case .database(let metadata): + return databaseHoldsSchemas ? nil : DatabaseTreeObjectGroup(database: metadata.name, schema: nil, kind: .table) + case .schema(let database, let schema): + return DatabaseTreeObjectGroup(database: database, schema: schema, kind: .table) + case .hierarchicalSchemaSection(let schema): + return DatabaseTreeObjectGroup(database: hierarchicalDatabase, schema: schema, kind: .table) + case .containerObjectKindSection(let group): + return group + case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, .redisKeysSection, + .redisNode: + return nil + } + } + + /// Only a selection of one row lists anything: one row added to a selection is the user + /// gathering rows for a command, not picking a container. + internal static func selectionObjectsTarget( + selectedNodes: [DatabaseTreeNode], + showsObjectsOnSelection: Bool, + databaseHoldsSchemas: Bool, + hierarchicalDatabase: String + ) -> DatabaseTreeObjectGroup? { + guard showsObjectsOnSelection, selectedNodes.count == 1 else { return nil } + return objectsTarget( + of: selectedNodes[0].kind, + databaseHoldsSchemas: databaseHoldsSchemas, + hierarchicalDatabase: hierarchicalDatabase + ) + } } diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift index ea37ab7006..34c71f23e5 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift @@ -79,3 +79,53 @@ struct SelectionDeltaTests { #expect(SelectionDelta.singleAddition(old: old, new: new) == nil) } } + +struct DatabaseTreeObjectsTargetTests { + private func target( + _ kinds: [DatabaseTreeNode.Kind], + showsObjects: Bool = true, + databaseHoldsSchemas: Bool = false + ) -> DatabaseTreeObjectGroup? { + DatabaseTreeSelection.selectionObjectsTarget( + selectedNodes: kinds.map { DatabaseTreeNode(id: UUID().uuidString, kind: $0) }, + showsObjectsOnSelection: showsObjects, + databaseHoldsSchemas: databaseHoldsSchemas, + hierarchicalDatabase: "warehouse" + ) + } + + @Test("With the setting off, selecting a database row lists nothing") + func settingOffListsNothing() { + #expect(target([.database(DatabaseMetadata.minimal(name: "shop"))], showsObjects: false) == nil) + } + + @Test("A database, schema or group row lists its own container's objects") + func containerRowsNameTheirContainer() { + let group = DatabaseTreeObjectGroup(database: "shop", schema: "sales", kind: .function) + + #expect(target([.database(DatabaseMetadata.minimal(name: "shop"))]) + == DatabaseTreeObjectGroup(database: "shop", schema: nil, kind: .table)) + #expect(target([.schema(database: "archive", schema: "sales")]) + == DatabaseTreeObjectGroup(database: "archive", schema: "sales", kind: .table)) + #expect(target([.hierarchicalSchemaSection(schema: "SALES")]) + == DatabaseTreeObjectGroup(database: "warehouse", schema: "SALES", kind: .table)) + #expect(target([.containerObjectKindSection(group)]) == group) + } + + @Test("A database row that holds schemas lists nothing itself") + func databaseOfSchemasListsNothing() { + #expect(target([.database(DatabaseMetadata.minimal(name: "shop"))], databaseHoldsSchemas: true) == nil) + } + + @Test("Objects, section headers and a selection of two rows list nothing") + func otherRowsListNothing() { + let table = DatabaseTreeTableRef( + database: "shop", schema: nil, table: TableInfo(name: "orders", type: .table, rowCount: nil) + ) + + #expect(target([.table(table)]) == nil) + #expect(target([.objectKindSection(.view)]) == nil) + #expect(target([.recentSection]) == nil) + #expect(target([.schema(database: "shop", schema: "a"), .schema(database: "shop", schema: "b")]) == nil) + } +} From fe9f905a8fb76d3e4a864ba809524f1ddc42f05d Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:29:50 +0700 Subject: [PATCH 044/123] feat(sidebar): replace Show All Tables with Show Objects on containers and groups Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- ...abaseTreeOutlineCoordinator+Commands.swift | 6 +- .../DatabaseTreeOutlineCoordinator+Menu.swift | 1 + .../Menu/DatabaseTreeMenuContext.swift | 6 +- .../Sidebar/Menu/DatabaseTreeMenuSpec.swift | 47 +++++++++++----- .../Sidebar/Menu/SidebarMenuCommand.swift | 4 +- .../Sidebar/DatabaseTreeMenuSpecTests.swift | 56 ++++++++++++++++--- 6 files changed, 93 insertions(+), 27 deletions(-) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift index 4835b71a77..e2309b63a8 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift @@ -127,8 +127,10 @@ extension DatabaseTreeOutlineCoordinator { mainCoordinator?.requestContainerDrop(targets) case .copyObjectsTo, .copyContainerTo, .duplicateDatabase, .searchContainer: performSheetCommand(command) - case .showAllTablesMetadata: - mainCoordinator?.showBrowsedObjects(.table) + case .showObjects(let target): + mainCoordinator?.showObjects(target, asPreview: false) + case .showBrowsedObjects(let kind): + mainCoordinator?.showBrowsedObjects(kind) case .refreshObjectKind(let kind): refreshObjectKind(kind) case .refreshContainerObjectKind(let group): diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift index 51e7267908..2fbf7dd547 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift @@ -123,6 +123,7 @@ extension DatabaseTreeOutlineCoordinator: NSMenuDelegate { tableFolderOptions: tableFolderMenuOptions(clicked: clicked, selected: selectedRefs()), offersBrowsedFolders: creation.offersBrowsedFolders, canShowAllTables: mainCoordinator?.allTablesListing() != nil, + databaseRowsHoldSchemas: supportsSchemaLevel, listsAttachedSchemas: listsAttachedSchemas, canDebugRoutine: DatabaseTreeMenuContext.canDebugRoutine(clicked?.kind, modules: .shared) { mainCoordinator?.routineDebugTarget(for: $0) diff --git a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift index b604a70942..a27bc2124a 100644 --- a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift +++ b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuContext.swift @@ -76,9 +76,11 @@ internal struct DatabaseTreeMenuContext { /// Whether the flat list is on screen, the one shape whose folders belong to the browsed /// database and schema rather than to a container row the user right-clicked. internal var offersBrowsedFolders: Bool = false - /// Whether Show All Tables has a listing to open, so an engine without one is not offered a command - /// that does nothing. + /// Whether the Tables kind has a listing to open, so an engine without one is not offered Show + /// Objects for a kind that would only fail. internal var canShowAllTables: Bool = false + /// On an engine grouped by schema a database row holds schemas, not objects. + internal var databaseRowsHoldSchemas: Bool = false /// The engine's schema rows are databases attached beside the opened file: reached by their /// qualifier, never made active, and not exported or copied as a unit. internal var listsAttachedSchemas: Bool = false diff --git a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift index 5b4649571c..0a33e8bfed 100644 --- a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift @@ -54,7 +54,9 @@ internal enum DatabaseTreeMenuSpec { let database = group.database.nilIfEmpty return [ DatabaseTreeMenuSection(newTypeItems(kind: group.kind, database: database, schema: group.schema, context: context)), - DatabaseTreeMenuSection([.command(String(localized: "Refresh"), .refreshContainerObjectKind(group))]), + DatabaseTreeMenuSection( + showObjectsItems(context) + [.command(String(localized: "Refresh"), .refreshContainerObjectKind(group))] + ), DatabaseTreeMenuSection(newFolderItems( kind: group.kind, container: .container(database: database, schema: group.schema) @@ -410,15 +412,7 @@ internal enum DatabaseTreeMenuSpec { _ kind: SidebarObjectKind, context: DatabaseTreeMenuContext ) -> [DatabaseTreeMenuSection] { - var items: [DatabaseTreeMenuItem] = [] - if kind == .table, context.canShowAllTables { - let title = context.objectKindTitles[kind] ?? kind.pluralDisplayName - items.append(.command( - String(format: String(localized: "Show All %@"), title), - .showAllTablesMetadata - )) - } - items.append(.command(String(localized: "Refresh"), .refreshObjectKind(kind))) + let items = showObjectsItems(context) + [.command(String(localized: "Refresh"), .refreshObjectKind(kind))] return [ DatabaseTreeMenuSection(newTypeItems(kind: kind, database: nil, schema: nil, context: context)), DatabaseTreeMenuSection(items), @@ -426,6 +420,29 @@ internal enum DatabaseTreeMenuSpec { ] } + /// Opens the clicked container's objects, or its group's, to keep. Tables need the engine's + /// listing statement; the other kinds are the sidebar's own lists, there whenever their row is. + private static func showObjectsItems(_ context: DatabaseTreeMenuContext) -> [DatabaseTreeMenuItem] { + guard let clicked = context.clicked else { return [] } + let command: SidebarMenuCommand + let kind: SidebarObjectKind + if case .objectKindSection(let sectionKind) = clicked { + command = .showBrowsedObjects(sectionKind) + kind = sectionKind + } else if let target = DatabaseTreeSelection.objectsTarget( + of: clicked, + databaseHoldsSchemas: context.databaseRowsHoldSchemas, + hierarchicalDatabase: context.activeDatabase ?? "" + ) { + command = .showObjects(target) + kind = target.kind + } else { + return [] + } + guard kind != .table || context.canShowAllTables else { return [] } + return [.command(String(localized: "Show Objects"), command)] + } + /// An engine whose tree hangs tables off schemas draws no database rows at all, so its schemas /// arrive here rather than as `.schema`. Without this the rename an engine declares and /// implements is unreachable on Snowflake and Trino, which are the two that do. @@ -445,7 +462,9 @@ internal enum DatabaseTreeMenuSpec { writes += editSchemaItems([ref], context: context) return [ DatabaseTreeMenuSection(newSchemaItems(database: context.activeDatabase, context: context)), - DatabaseTreeMenuSection([.command(String(localized: "Refresh"), .refreshHierarchicalSchema(schema))]), + DatabaseTreeMenuSection( + showObjectsItems(context) + [.command(String(localized: "Refresh"), .refreshHierarchicalSchema(schema))] + ), /// Oracle, Snowflake, Trino, Dameng and BigQuery draw their schemas here rather than as /// container rows, and several of them need a schema-scoped source, so leaving Copy To /// on the container path alone put it out of reach on exactly the engines that require it. @@ -461,13 +480,15 @@ internal enum DatabaseTreeMenuSpec { context: DatabaseTreeMenuContext ) -> [DatabaseTreeMenuSection] { let targets = SidebarMenuTarget.resolveContainers(clicked: clicked, selection: context.selectedContainers) + // A command for the clicked container alone, so not offered across a selection of several. + let showObjects = targets.count == 1 ? showObjectsItems(context) : [] if context.listsAttachedSchemas, clicked.kind == .schema { return [ - DatabaseTreeMenuSection([.command(String(localized: "Refresh"), .refreshContainers(targets))]), + DatabaseTreeMenuSection(showObjects + [.command(String(localized: "Refresh"), .refreshContainers(targets))]), DatabaseTreeMenuSection([.command(copyNamesTitle(count: targets.count), .copyContainerNames(targets))]) ] } - var open: [DatabaseTreeMenuItem] = [] + var open: [DatabaseTreeMenuItem] = showObjects /// Omitted rather than disabled: a menu item that can never fire in this state is noise, and /// the HIG prefers removing an item that does not apply over showing it greyed out. if targets.count == 1, !isActive(clicked, context: context) { diff --git a/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift b/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift index 4c9725b627..94a9072afe 100644 --- a/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift +++ b/apple/TablePro/Views/Sidebar/Menu/SidebarMenuCommand.swift @@ -71,7 +71,9 @@ internal enum SidebarMenuCommand: Equatable { case copyContainerTo(DatabaseContainerRef) case duplicateDatabase(DatabaseContainerRef) case searchContainer(DatabaseContainerRef) - case showAllTablesMetadata + case showObjects(DatabaseTreeObjectGroup) + /// The flat list's kind sections, whose container is the one the sidebar is browsing. + case showBrowsedObjects(SidebarObjectKind) case refreshObjectKind(SidebarObjectKind) case refreshContainerObjectKind(DatabaseTreeObjectGroup) case refreshHierarchicalSchema(String) diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift index 73dca888e4..8775f70d48 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift @@ -705,6 +705,7 @@ struct DatabaseTreeMenuSpecTests { attached.listsAttachedSchemas = true #expect(commands(DatabaseTreeMenuSpec.sections(for: attached)) == [ + .showObjects(DatabaseTreeObjectGroup(database: "app.db", schema: "auth", kind: .table)), .refreshContainers([clicked]), .copyContainerNames([clicked]) ]) @@ -1000,18 +1001,55 @@ struct DatabaseTreeMenuSpecTests { #expect(SidebarMenuCommand.exportContainers([.schema(database: "app", schema: "public")]).shortcutAction == nil) } - /// Elasticsearch, Typesense and Weaviate have no listing, and the item used to run a MongoDB command - /// against them. - @Test("Show All Tables is offered only when the engine has a listing") - func showAllTablesNeedsAListing() { - let offered = commands(DatabaseTreeMenuSpec.sections(for: context(clicked: .objectKindSection(.table)))) + /// Elasticsearch, Typesense and Weaviate have no listing, so their Tables kind has nothing to show. + @Test("Show Objects replaces Show All Tables, and Tables need a listing") + func showObjectsNeedsAListingForTables() { + let offered = DatabaseTreeMenuSpec.sections(for: context(clicked: .objectKindSection(.table))) let withheld = commands(DatabaseTreeMenuSpec.sections( for: context(clicked: .objectKindSection(.table), canShowAllTables: false) )) + let functions = commands(DatabaseTreeMenuSpec.sections( + for: context(clicked: .objectKindSection(.function), canShowAllTables: false) + )) - #expect(offered.contains(.showAllTablesMetadata)) - #expect(!withheld.contains(.showAllTablesMetadata)) + #expect(commands(offered).contains(.showBrowsedObjects(.table))) + #expect(!titles(offered).contains(String(format: String(localized: "Show All %@"), "Tables"))) + #expect(!withheld.contains(.showBrowsedObjects(.table))) #expect(withheld.contains(.refreshObjectKind(.table))) + #expect(functions.contains(.showBrowsedObjects(.function))) + } + + @Test("Show Objects lists the clicked container or group, not the browsed one") + func showObjectsNamesTheClickedContainer() { + let group = DatabaseTreeObjectGroup(database: "archive", schema: "audit", kind: .view) + let cases: [(DatabaseTreeNode.Kind, DatabaseTreeObjectGroup)] = [ + (.database(DatabaseMetadata.minimal(name: "analytics")), DatabaseTreeObjectGroup(database: "analytics", schema: nil, kind: .table)), + (.schema(database: "archive", schema: "billing"), DatabaseTreeObjectGroup(database: "archive", schema: "billing", kind: .table)), + (.hierarchicalSchemaSection(schema: "reporting"), DatabaseTreeObjectGroup(database: "app", schema: "reporting", kind: .table)), + (.containerObjectKindSection(group), group), + ] + + for (clicked, expected) in cases { + let issued = commands(DatabaseTreeMenuSpec.sections(for: context(clicked: clicked))) + #expect(issued.contains(.showObjects(expected)), "\(expected)") + } + } + + @Test("A database row that holds schemas, or a selection of several containers, offers no Show Objects") + func showObjectsNeedsOneContainerOfObjects() { + var bySchema = context(clicked: .database(DatabaseMetadata.minimal(name: "analytics"))) + bySchema.databaseRowsHoldSchemas = true + let several = context( + clicked: .schema(database: "app", schema: "sales"), + selectedContainers: [.schema(database: "app", schema: "sales"), .schema(database: "app", schema: "hr")] + ) + + for menu in [bySchema, several] { + #expect(!commands(DatabaseTreeMenuSpec.sections(for: menu)).contains { command in + if case .showObjects = command { return true } + return false + }) + } } @Test("A status row keeps the background menu") @@ -1098,11 +1136,11 @@ struct DatabaseTreeMenuSpecTests { @Test("The Types sections offer only Refresh where the driver cannot create a type") func typesSectionsWithoutCreation() { let flat = commands(DatabaseTreeMenuSpec.sections(for: context(clicked: .objectKindSection(.type)))) - #expect(flat == [.refreshObjectKind(.type)]) + #expect(flat == [.showBrowsedObjects(.type), .refreshObjectKind(.type)]) let group = DatabaseTreeObjectGroup(database: "warehouse", schema: "billing", kind: .type) let tree = commands(DatabaseTreeMenuSpec.sections(for: context(clicked: .containerObjectKindSection(group)))) - #expect(tree == [.refreshContainerObjectKind(group)]) + #expect(tree == [.showObjects(group), .refreshContainerObjectKind(group)]) } @Test("New Type leads the Types sections, scoped to the section, and is withheld read-only") From 17c4768b675e5eac4a323ace1a51b3733549d0a4 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 00:33:22 +0700 Subject: [PATCH 045/123] chore(listing): add the Objects tab strings to the catalog Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../TablePro/Resources/Localizable.xcstrings | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 59fc6730f1..e106cf5156 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -11208,6 +11208,16 @@ } } }, + "%lld of ^[%lld object](inflect: true)" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$lld of ^[%2$lld object](inflect: true)" + } + } + } + }, "%lld of ^[%lld row](inflect: true)" : { "localizations" : { "en" : { @@ -12595,6 +12605,9 @@ } } } + }, + "^[%lld object](inflect: true)" : { + }, "^[%lld row](inflect: true)" : { "localizations" : { @@ -27780,6 +27793,9 @@ } } } + }, + "Arguments" : { + }, "Array element scope" : { "localizations" : { @@ -33520,9 +33536,24 @@ }, "Can't Export Messages" : { + }, + "Can't List Foreign Tables" : { + + }, + "Can't List Functions" : { + + }, + "Can't List Materialized Views" : { + + }, + "Can't List Procedures" : { + }, "Can't List Routines" : { + }, + "Can't List Sequences" : { + }, "Can't List Tables" : { "localizations" : { @@ -33563,6 +33594,15 @@ } } } + }, + "Can't List Triggers" : { + + }, + "Can't List Types" : { + + }, + "Can't List Views" : { + }, "Can't reach a PGlite socket server at %@:%d. Start it with 'npx @electric-sql/pglite-socket', then try again." : { "extractionState" : "manual", @@ -40754,6 +40794,9 @@ } } } + }, + "Clicking a database, schema or object group in the sidebar lists its objects in the main area. Show Objects in the row's menu lists them either way." : { + }, "Client" : { "localizations" : { @@ -82486,6 +82529,9 @@ } } } + }, + "Filter by Name" : { + }, "Filter by Tag" : { "localizations" : { @@ -100311,6 +100357,9 @@ }, "Lakehouse analytics, MySQL protocol" : { + }, + "Language" : { + }, "Language %@" : { "localizations" : { @@ -115782,6 +115831,9 @@ } } } + }, + "No" : { + }, "No %@" : { "localizations" : { @@ -117876,6 +117928,9 @@ } } } + }, + "No Foreign Tables" : { + }, "No functions" : { "localizations" : { @@ -117916,6 +117971,9 @@ } } } + }, + "No Functions" : { + }, "No generator can fill %@ (%@), and it cannot be left empty." : { "localizations" : { @@ -118761,6 +118819,9 @@ } } } + }, + "No Materialized Views" : { + }, "No measurable change" : { "localizations" : { @@ -119477,6 +119538,9 @@ } } } + }, + "No Procedures" : { + }, "No providers configured" : { "localizations" : { @@ -120714,6 +120778,9 @@ }, "No sequences" : { + }, + "No Sequences" : { + }, "No servers yet." : { "localizations" : { @@ -121476,6 +121543,9 @@ } } } + }, + "No Types" : { + }, "No Users or Roles" : { "localizations" : { @@ -121729,6 +121799,9 @@ } } } + }, + "No Views" : { + }, "No Warnings" : { "localizations" : { @@ -125553,6 +125626,9 @@ } } } + }, + "Object Kind" : { + }, "Object kinds this operation may name, as list_tables reports them. Empty when it acts on the whole database only." : { "localizations" : { @@ -152152,6 +152228,9 @@ } } } + }, + "Returns" : { + }, "Returns %@" : { "localizations" : { @@ -166323,6 +166402,12 @@ } } } + }, + "Show Objects" : { + + }, + "Show objects when a database, schema or group is selected" : { + }, "Show only the objects whose name contains this text" : { "localizations" : { @@ -191283,6 +191368,9 @@ } } } + }, + "The read stopped before it finished." : { + }, "The Realtime Database cannot filter with %@. It supports =, <, <=, >, >=, BETWEEN, STARTS WITH and IS NULL." : { "extractionState" : "manual", @@ -217682,6 +217770,9 @@ } } } + }, + "Yes" : { + }, "Yesterday" : { "localizations" : { From 1a637083da65f5f63ec548ed4fa330d37e3ce8a3 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:24:06 +0700 Subject: [PATCH 046/123] fix(listing): keep a kept Objects tab when a selection previews another kind A sidebar selection retargeted the container's only listing tab, so a kept tab lost its kind, filter and sort to the next click. A preview now never changes a kept listing: it returns to one showing the kind, else it opens or retargets a preview beside it. A request to keep retargets the kept listing and closes that preview. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Query/QueryTabManager.swift | 58 +++++++-- ...MainContentCoordinator+ObjectListing.swift | 10 +- .../QueryTabManagerTableListingTests.swift | 110 +++++++++++++++++- .../Main/CoordinatorTableListingTests.swift | 53 +++++++++ 4 files changed, 218 insertions(+), 13 deletions(-) diff --git a/apple/TablePro/Models/Query/QueryTabManager.swift b/apple/TablePro/Models/Query/QueryTabManager.swift index 349112d522..5acfd0763a 100644 --- a/apple/TablePro/Models/Query/QueryTabManager.swift +++ b/apple/TablePro/Models/Query/QueryTabManager.swift @@ -548,8 +548,9 @@ final class QueryTabManager: ObservableObject { selectedTabId = newTab.id } - // One listing per container: asking again selects it, and another kind retargets it rather than opening a second - // tab. A preview takes the strip slot of the preview it replaces, so browsing the sidebar does not grow the strip. + // A container holds at most one kept listing and one preview, the way a table preview sits beside kept table tabs. + // Asking again lands on one of them and another kind retargets it, rather than opening a third. A new preview takes + // the strip slot of the preview it replaces, so browsing the sidebar does not grow the strip. @discardableResult func addTableListingTab( title: String, @@ -560,13 +561,20 @@ final class QueryTabManager: ObservableObject { replacing previewId: UUID? = nil ) -> UUID { let schemaName = schemaName.flatMap { $0.isEmpty ? nil : $0 } - if let existing = tableListingTab(databaseName: databaseName, schemaName: schemaName) { - setTableListingKind(kind, title: title, tabId: existing.id) + if let landing = tableListingLanding( + databaseName: databaseName, schemaName: schemaName, kind: kind, isPreview: isPreview + ) { + if landing.retargets { + setTableListingKind(kind, title: title, tabId: landing.tabId) + } if !isPreview { - promotePreviewTab(id: existing.id) + promotePreviewTab(id: landing.tabId) } - selectedTabId = existing.id - return existing.id + selectedTabId = landing.tabId + if let closing = landing.closesPreviewId { + closeTab(id: closing) + } + return landing.tabId } var newTab = QueryTab(title: title, tabType: .tableListing) newTab.tableContext.isEditable = false @@ -587,13 +595,36 @@ final class QueryTabManager: ObservableObject { return newTab.id } - func tableListingTab(databaseName: String, schemaName: String?) -> QueryTab? { + /// Where a request for a container's objects lands among the listings open for it, nil for a new + /// tab. A preview never changes a kept listing, so its kind, filter and sort survive browsing: it + /// returns to one showing the kind, else it takes the container's preview. A request to keep takes + /// the kept listing, else the preview, and the preview beside a kept listing goes. + func tableListingLanding( + databaseName: String, + schemaName: String?, + kind: SidebarObjectKind, + isPreview: Bool + ) -> TableListingLanding? { let schemaName = schemaName.flatMap { $0.isEmpty ? nil : $0 } - return tabs.first { + let listings = tabs.filter { $0.tabType == .tableListing && $0.tableContext.databaseName == databaseName && $0.tableContext.schemaName == schemaName } + let kept = listings.filter { !$0.isPreview } + // A preview the user kept, or one a relaunch restored as kept, can make a second kept listing. + let keptShowingKind = kept.first { ($0.display.listingKind ?? .table) == kind } + let preview = listings.first { $0.isPreview } + if isPreview { + if let keptShowingKind { + return TableListingLanding(tabId: keptShowingKind.id, retargets: false, closesPreviewId: nil) + } + return preview.map { TableListingLanding(tabId: $0.id, retargets: true, closesPreviewId: nil) } + } + if let keptTab = keptShowingKind ?? kept.first { + return TableListingLanding(tabId: keptTab.id, retargets: true, closesPreviewId: preview?.id) + } + return preview.map { TableListingLanding(tabId: $0.id, retargets: true, closesPreviewId: nil) } } func setTableListingKind(_ kind: SidebarObjectKind, title: String, tabId: UUID) { @@ -907,3 +938,12 @@ extension QueryTabManager { AppEvents.shared.visibleContainerChanged.send() } } + +/// The open listing a request for a container's objects selects. +internal struct TableListingLanding: Equatable { + let tabId: UUID + /// False for a kept listing a preview returns to: it keeps its kind, filter and sort. + let retargets: Bool + /// The preview beside the kept listing a request to keep lands on, which closes. + let closesPreviewId: UUID? +} diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift index 7d96cccbf9..0f0b764758 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift @@ -12,11 +12,17 @@ extension MainContentCoordinator { /// menu command opens them to keep, and brings a tab already open up to date. func showObjects(_ target: DatabaseTreeObjectGroup, asPreview: Bool) { let schemaName = target.schema?.nilIfEmpty - let isOpen = tabManager.tableListingTab(databaseName: target.database, schemaName: schemaName) != nil - let replaced = asPreview && !isOpen ? replaceablePreview : nil + let landing = tabManager.tableListingLanding( + databaseName: target.database, schemaName: schemaName, kind: target.kind, isPreview: asPreview + ) + let replaced = asPreview && landing == nil ? replaceablePreview : nil if let replaced { releasePreviewForReplacement(replaced) } + // The kept listing takes a request to keep, so the preview beside it goes the way a replaced one does. + if let closing = landing?.closesPreviewId.flatMap({ id in tabManager.tabs.first { $0.id == id } }) { + releasePreviewForReplacement(closing) + } let tabId = tabManager.addTableListingTab( title: listingTitle(kind: target.kind, schemaName: schemaName), databaseName: target.database, diff --git a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift index 767677bf2b..6424ad3190 100644 --- a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift +++ b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift @@ -76,8 +76,114 @@ struct QueryTabManagerTableListingTests { #expect(tab.display.listingKind == .view) #expect(tab.title == "Views: sales") #expect(manager.tabStructureVersion > version) - #expect(manager.tableListingTab(databaseName: "shop", schemaName: "sales")?.id == first) - #expect(manager.tableListingTab(databaseName: "shop", schemaName: "") == nil) + #expect( + manager.tableListingLanding(databaseName: "shop", schemaName: "sales", kind: .function, isPreview: false)?.tabId + == first + ) + #expect(manager.tableListingLanding(databaseName: "shop", schemaName: "", kind: .view, isPreview: false) == nil) + } + + // MARK: - A kept listing and a preview beside it + + @Test("A preview of another kind opens beside a kept listing and leaves it as it was") + func previewOpensBesideTheKeptListing() throws { + let manager = QueryTabManager() + let kept = manager.addTableListingTab(title: "Tables: sales", databaseName: "shop", schemaName: "sales") + let version = manager.tabStructureVersion + + let preview = manager.addTableListingTab( + title: "Views: sales", databaseName: "shop", schemaName: "sales", kind: .view, isPreview: true + ) + + let keptTab = try #require(manager.tabs.first { $0.id == kept }) + let previewTab = try #require(manager.tabs.first { $0.id == preview }) + #expect(preview != kept) + #expect(manager.tabs.map(\.id) == [kept, preview]) + #expect(manager.selectedTabId == preview) + #expect(keptTab.display.listingKind == nil) + #expect(keptTab.title == "Tables: sales") + #expect(!keptTab.isPreview) + #expect(previewTab.display.listingKind == .view) + #expect(previewTab.isPreview) + #expect(manager.tabStructureVersion > version) + } + + @Test("A preview asking for the kind a kept listing shows selects that listing") + func previewSelectsTheKeptListingShowingItsKind() throws { + let manager = QueryTabManager() + let kept = manager.addTableListingTab(title: "Views", databaseName: "shop", schemaName: nil, kind: .view) + manager.addTab(initialQuery: "SELECT 1", databaseName: "shop") + let count = manager.tabs.count + + let landed = manager.addTableListingTab( + title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true + ) + + #expect(landed == kept) + #expect(manager.tabs.count == count) + #expect(manager.selectedTabId == kept) + #expect(manager.tabs.first { $0.id == kept }?.isPreview == false) + } + + @Test("Another preview kind retargets the preview beside the kept listing, never the kept one") + func previewRetargetsOnlyThePreview() throws { + let manager = QueryTabManager() + let kept = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil) + let preview = manager.addTableListingTab( + title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true + ) + + let landed = manager.addTableListingTab( + title: "Functions", databaseName: "shop", schemaName: nil, kind: .function, isPreview: true + ) + + #expect(landed == preview) + #expect(manager.tabs.map(\.id) == [kept, preview]) + #expect(manager.tabs.first { $0.id == kept }?.display.listingKind == nil) + #expect(manager.tabs.first { $0.id == preview }?.display.listingKind == .function) + #expect(manager.tabs.first { $0.id == preview }?.title == "Functions") + #expect(manager.tabs.first { $0.id == preview }?.isPreview == true) + } + + @Test("A request to keep retargets the kept listing and closes the preview beside it") + func keepRequestRetargetsTheKeptListingAndClosesThePreview() throws { + let manager = QueryTabManager() + let kept = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil) + let preview = manager.addTableListingTab( + title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true + ) + let landing = try #require( + manager.tableListingLanding(databaseName: "shop", schemaName: nil, kind: .function, isPreview: false) + ) + #expect(landing.tabId == kept) + #expect(landing.closesPreviewId == preview) + + let landed = manager.addTableListingTab( + title: "Functions", databaseName: "shop", schemaName: nil, kind: .function + ) + + #expect(landed == kept) + #expect(manager.tabs.map(\.id) == [kept]) + #expect(manager.selectedTabId == kept) + #expect(manager.selectedTab?.display.listingKind == .function) + #expect(manager.selectedTab?.title == "Functions") + #expect(manager.selectedTab?.isPreview == false) + } + + @Test("Each container keeps its own kept listing and preview") + func otherContainersKeepTheirOwnPair() throws { + let manager = QueryTabManager() + let shop = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil) + let archive = manager.addTableListingTab(title: "Tables", databaseName: "archive", schemaName: nil) + let shopViews = manager.addTableListingTab( + title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true + ) + + manager.addTableListingTab(title: "Functions", databaseName: "archive", schemaName: nil, kind: .function) + + #expect(manager.tabs.map(\.id) == [shop, archive, shopViews]) + #expect(manager.tabs.first { $0.id == archive }?.display.listingKind == .function) + #expect(manager.tabs.first { $0.id == shopViews }?.display.listingKind == .view) } @Test("Tables is stored as no kind, so it reads like a tab saved before kinds existed") diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index 8a24552ac7..586529675f 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -158,6 +158,59 @@ struct CoordinatorTableListingTests { #expect(tabManager.tabs.count == 2) } + @Test("A selection of another kind in a kept listing's container previews it beside the kept tab") + func selectionBesideAKeptListingLeavesItAlone() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("shop"), asPreview: false) + let kept = try #require(tabManager.selectedTabId) + + coordinator.showObjects(group("shop", .view), asPreview: true) + + let preview = try #require(tabManager.selectedTab) + let keptTab = try #require(tabManager.tabs.first { $0.id == kept }) + #expect(tabManager.tabs.map(\.id) == [kept, preview.id]) + #expect(preview.isPreview) + #expect(preview.display.listingKind == .view) + #expect(keptTab.display.listingKind == nil) + #expect(keptTab.title == "Tables") + #expect(!keptTab.isPreview) + } + + @Test("A selection of the kind a kept listing shows returns to it") + func selectionReturnsToTheKeptListing() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("shop", .view), asPreview: false) + let kept = try #require(tabManager.selectedTabId) + tabManager.addTab(initialQuery: "SELECT 1", databaseName: "shop") + + coordinator.showObjects(group("shop", .view), asPreview: true) + + #expect(tabManager.selectedTabId == kept) + #expect(tabManager.tabs.filter { $0.tabType == .tableListing }.count == 1) + #expect(tabManager.selectedTab?.isPreview == false) + } + + @Test("Show Objects retargets the kept listing, closes the preview beside it and refreshes the kept one") + func showObjectsTakesTheKeptListing() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("shop"), asPreview: false) + let kept = try #require(tabManager.selectedTabId) + coordinator.showObjects(group("shop", .view), asPreview: true) + var refreshed: [UUID] = [] + let subscription = AppEvents.shared.tabRefreshRequested.sink { refreshed.append($0) } + defer { subscription.cancel() } + + coordinator.showObjects(group("shop", .function), asPreview: false) + + #expect(tabManager.tabs.map(\.id) == [kept]) + #expect(tabManager.selectedTab?.display.listingKind == .function) + #expect(tabManager.selectedTab?.isPreview == false) + #expect(refreshed == [kept]) + } + @Test("Picking a kind retargets the tab, relabels it and keeps the preview") func pickingAKindKeepsThePreview() throws { let (coordinator, tabManager, _) = makeCoordinator() From b0b70a46033e92f6e965426bb83a4b950c72c851 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:26:22 +0700 Subject: [PATCH 047/123] test(listing): pin where a container selection leaves the browse cursor Run the coordinator with a real per-database container target: a selection in the browsed database leaves the browse cursor alone, and one in another database moves it there, since tabs are per container. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Main/CoordinatorTableListingTests.swift | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index 586529675f..793f099084 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -5,6 +5,7 @@ import Combine import Foundation +import TableProTestSupport import Testing @testable import TablePro @@ -257,4 +258,58 @@ struct CoordinatorTableListingTests { #expect(!payload.isPreview) #expect(tabManager.tabs.first { $0.id == listing }?.isPreview == false) } + + // MARK: - The browse cursor + + /// Each database is an entry of its own on the strip, so a listing tab names the entry it shows in. + private func withConnectedCoordinator( + _ body: (MainContentCoordinator, QueryTabManager) async throws -> Void + ) async throws { + let connection = TestFixtures.makeConnection(database: "shop", type: .mysql) + let driver = PluginDriverAdapter(connection: connection, pluginDriver: SwitchingDriverStub()) + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + DatabaseManager.shared.injectSession(session, for: connection.id) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + + let tabManager = QueryTabManager(containerTarget: .database, visibleContainer: "shop") + let coordinator = MainContentCoordinator( + connection: connection, + tabManager: tabManager, + changeManager: DataChangeManager(), + toolbarState: ConnectionToolbarState() + ) + defer { coordinator.teardown() } + + try await body(coordinator, tabManager) + } + + @Test("A selection in the browsed database leaves the browse cursor where it is") + func selectionInTheBrowsedContainerKeepsTheCursor() async throws { + try await withConnectedCoordinator { coordinator, tabManager in + #expect(coordinator.browseCursorCoordinator.browsedContainer == "shop") + + coordinator.showObjects(group("shop", .view), asPreview: true) + + #expect(tabManager.selectedTab?.tabType == .tableListing) + #expect(tabManager.selectedTab?.tableContext.databaseName == "shop") + #expect(tabManager.visibleContainer == "shop") + #expect(coordinator.browseCursorCoordinator.pendingRequest == nil) + #expect(coordinator.browseCursorCoordinator.browsedContainer == "shop") + } + } + + /// Accepted: tabs are per database, so showing another database's objects shows its entry, and + /// the connection follows the entry on screen. + @Test("A selection in another database takes the browse cursor there") + func selectionInAnotherContainerMovesTheCursor() async throws { + try await withConnectedCoordinator { coordinator, tabManager in + coordinator.showObjects(group("archive", .view), asPreview: true) + + #expect(tabManager.selectedTab?.tableContext.databaseName == "archive") + #expect(tabManager.visibleContainer == "archive") + try await waitUntil { coordinator.browseCursorCoordinator.browsedContainer == "archive" } + #expect(coordinator.browseCursorCoordinator.pendingRequest == nil) + } + } } From 8ab13095c827cfe367fb641533540a87f251adef Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:35:29 +0700 Subject: [PATCH 048/123] fix(listing): keep the selection on the same object after a refresh An Objects tab's row ids are positions and the grid restores its selection by row id, so an object created or dropped above the selected one moved the highlight to its neighbour, and Return or the menu acted on the wrong object. Rows that replace a listing now carry the selection to the same object, matched by name and schema, and drop it when the object went. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Core/DataGrid/DataGridModel.swift | 6 +++ .../Engine/GridSelectionSnapshot.swift | 18 +++++++++ .../Services/Query/ObjectListingRows.swift | 40 +++++++++++++++++++ .../ViewModels/TableListingViewModel.swift | 9 +++-- .../Views/Structure/HeldRowsGridAdapter.swift | 7 +++- .../Engine/GridSelectionSnapshotTests.swift | 25 ++++++++++++ .../TableListingViewModelTests.swift | 27 +++++++++++++ 7 files changed, 127 insertions(+), 5 deletions(-) diff --git a/apple/TablePro/Core/DataGrid/DataGridModel.swift b/apple/TablePro/Core/DataGrid/DataGridModel.swift index 608496a96f..418483f6b9 100644 --- a/apple/TablePro/Core/DataGrid/DataGridModel.swift +++ b/apple/TablePro/Core/DataGrid/DataGridModel.swift @@ -214,6 +214,12 @@ final class DataGridModel: ObservableObject { setSelection(.empty) } + /// Before a reload whose rows took other ids: the selection stays on the rows the map names, and + /// the reload resolves it as it resolves any kept selection. + func carrySelection(_ rowMap: [RowID: RowID]) { + store.selectionSnapshot = store.selectionSnapshot.remappingRows(rowMap) + } + // The change that follows tells the view: a selection moved ahead of it would end an open edit. private func restoreSelection(in rows: TableRows) { let resolved = store.selectionSnapshot diff --git a/apple/TablePro/Core/DataGrid/Engine/GridSelectionSnapshot.swift b/apple/TablePro/Core/DataGrid/Engine/GridSelectionSnapshot.swift index 14e8eb047c..795ea16e6e 100644 --- a/apple/TablePro/Core/DataGrid/Engine/GridSelectionSnapshot.swift +++ b/apple/TablePro/Core/DataGrid/Engine/GridSelectionSnapshot.swift @@ -57,6 +57,24 @@ struct GridSelectionSnapshot: Equatable { self.mode = selection.mode } + /// For rows a new read gave other ids: each selected row keeps its place under its new id, and a + /// row the map leaves out went with the read, so it leaves the selection. + func remappingRows(_ rowMap: [RowID: RowID]) -> GridSelectionSnapshot { + func cell(_ cell: Cell?) -> Cell? { + guard let cell, let rowID = rowMap[cell.rowID] else { return nil } + return Cell(rowID: rowID, columnID: cell.columnID) + } + var remapped = self + remapped.rowIDs = rowIDs.compactMap { rowMap[$0] } + remapped.rectangles = rectangles.compactMap { rectangle in + let rowIDs = rectangle.rowIDs.compactMap { rowMap[$0] } + return rowIDs.isEmpty ? nil : Rectangle(rowIDs: rowIDs, columnIDs: rectangle.columnIDs) + } + remapped.activeCell = cell(activeCell) + remapped.anchor = cell(anchor) + return remapped.rowIDs.isEmpty && remapped.rectangles.isEmpty ? .empty : remapped + } + func resolved(order: DataGridRowOrder, rows: TableRows, columns: DataGridColumnSet) -> GridSelection { func coord(_ cell: Cell?) -> GridCoord? { guard let cell, diff --git a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift index 7e507e253e..934936991a 100644 --- a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift +++ b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift @@ -32,6 +32,46 @@ internal enum ObjectListingItem: Hashable, Sendable { } } +extension ObjectListingItem { + /// One object from one read to the next. Counts and comments change between reads, and overloads + /// or triggers on different tables share a name, so the key is the name, the schema and what + /// tells those apart. + struct Key: Hashable { + let name: String + let schema: String? + let table: String? + let argumentSignature: String? + } + + var key: Key { + switch self { + case .relation(let name, let schema, _): + return Key(name: name, schema: schema, table: nil, argumentSignature: nil) + case .sourced(let ref): + return Key(name: ref.name, schema: ref.schema, table: ref.table, argumentSignature: ref.argumentSignature) + } + } +} + +extension TableListing { + /// Where each object `previous` listed sits in this listing, by row id. Row ids are positions, so + /// an object created or dropped above another moves it to another id. Nil when `previous` names no + /// objects: its rows are plain values with nothing to follow. + func rowIDs(carriedFrom previous: TableListing) -> [RowID: RowID]? { + guard !previous.items.isEmpty else { return nil } + var rowIDsByKey: [ObjectListingItem.Key: RowID] = [:] + for row in rows.rows { + guard let item = items[row.id], rowIDsByKey[item.key] == nil else { continue } + rowIDsByKey[item.key] = row.id + } + var carried: [RowID: RowID] = [:] + for (rowID, item) in previous.items { + carried[rowID] = rowIDsByKey[item.key] + } + return carried + } +} + /// Where a plugin's table listing names its objects: the plugins alias the columns `name`, /// `schema` or `schema_name`, and `kind`. A shell command's listing has none of them. internal struct ObjectListingColumns: Equatable { diff --git a/apple/TablePro/ViewModels/TableListingViewModel.swift b/apple/TablePro/ViewModels/TableListingViewModel.swift index f474453897..e32f71e81d 100644 --- a/apple/TablePro/ViewModels/TableListingViewModel.swift +++ b/apple/TablePro/ViewModels/TableListingViewModel.swift @@ -153,22 +153,25 @@ internal final class TableListingViewModel: ObservableObject { private func commit(_ outcome: MetadataFetchOutcome, token: Int) { guard token == generation else { return } isRefreshing = false + let previous = state.value state = state.settled(by: outcome, discardingValue: false) // A cancel from here bumps the generation, so this one came from elsewhere and nothing else is coming. if case .cancelled = outcome, case .idle = state { wasInterrupted = true } - showRows() + showRows(replacing: previous) } - private func showRows() { + /// The grid keeps its selection by row id, which is a position here, so rows replacing `previous` + /// carry it to the same objects: Return and the menu act on what the reader picked. + private func showRows(replacing previous: TableListing? = nil) { guard let listing = state.value else { count = nil return } let shown = ObjectListingFilter.rows(of: listing, matching: filterText) count = ObjectListingCount(shown: shown.count, total: listing.rows.count) - grid.setRows(shown) + grid.setRows(shown, carryingSelection: previous.flatMap { listing.rowIDs(carriedFrom: $0) }) } private func menuItems(for rowIDs: [RowID], clicked: RowID) -> [NSMenuItem] { diff --git a/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift b/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift index 02d7fc567d..c2ec053777 100644 --- a/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift +++ b/apple/TablePro/Views/Structure/HeldRowsGridAdapter.swift @@ -55,8 +55,11 @@ final class HeldRowsGridAdapter: ObservableObject { } } - // The rows were replaced. - func setRows(_ rows: TableRows) { + // The rows were replaced. An owner whose row ids are positions passes where each selected row went. + func setRows(_ rows: TableRows, carryingSelection rowMap: [RowID: RowID]? = nil) { + if let rowMap { + model.carrySelection(rowMap) + } let previousColumns = displayedRows.columns heldRows = rows displayedRows = sortsHeldRows ? TableRowsSorting.sorted(rows, by: model.store.sortState) : rows diff --git a/apple/TableProTests/Core/DataGrid/Engine/GridSelectionSnapshotTests.swift b/apple/TableProTests/Core/DataGrid/Engine/GridSelectionSnapshotTests.swift index a9499cb74e..6c57457123 100644 --- a/apple/TableProTests/Core/DataGrid/Engine/GridSelectionSnapshotTests.swift +++ b/apple/TableProTests/Core/DataGrid/Engine/GridSelectionSnapshotTests.swift @@ -213,4 +213,29 @@ struct GridSelectionSnapshotTests { #expect(snapshot(.empty) == .empty) #expect(GridSelectionSnapshot.empty.resolved(order: .unfiltered, rows: storage, columns: columns()) == .empty) } + + @Test("Rows a new read gave other ids keep their place in the selection, and rows that went leave it") + func remappingFollowsMovedRows() { + let selected = snapshot(GridSelection( + rectangles: [GridRect(rows: 1...2, columns: 0...3)], + activeCell: cell(2, 1), + anchor: cell(1, 0), + mode: .cursor + )) + + let moved = selected.remappingRows([.existing(1): .existing(4), .existing(2): .existing(5)]) + #expect(moved.rowIDs == [.existing(4), .existing(5)]) + #expect(moved.rectangles.map(\.rowIDs) == [[.existing(4), .existing(5)]]) + #expect(moved.activeCell?.rowID == .existing(5)) + #expect(moved.activeCell?.columnID == selected.activeCell?.columnID) + #expect(moved.anchor?.rowID == .existing(4)) + #expect(moved.mode == .cursor) + + let partly = selected.remappingRows([.existing(2): .existing(0)]) + #expect(partly.rowIDs == [.existing(0)]) + #expect(partly.activeCell?.rowID == .existing(0)) + #expect(partly.anchor == nil) + + #expect(selected.remappingRows([:]) == .empty) + } } diff --git a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift index 187c47f700..2c3eef1070 100644 --- a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift +++ b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift @@ -433,6 +433,33 @@ struct TableListingViewModelTests { #expect(model.displayIndex(of: orders) == 2) } + // Row ids are positions, so without this a table created above the selected one moved the highlight + // to its neighbour, and Return or the menu acted on the wrong table. + @Test("A refresh keeps the selection on the same object, and clears it when the object went") + func selectionFollowsItsObjectAcrossARefresh() async throws { + var actions: [ObjectListingAction] = [] + let (viewModel, provider) = makeViewModel(perform: { actions.append($0) }) + provider.answer(with: .names(["customers", "orders"])) + await viewModel.reload().value + let model = viewModel.grid.model + model.selectCell(GridCoord(row: 1, displayColumn: 0)) + #expect(model.selectedRowIDs == [.existing(1)]) + + provider.answer(with: .names(["accounts", "customers", "orders"])) + await viewModel.reload().value + + let selected = try #require(model.selectedRowIDs.first) + #expect(model.selectedRowIDs.count == 1) + #expect(viewModel.state.value?.items[selected]?.name == "orders") + viewModel.grid.gridOpenRow(selected) + #expect(actions == [.open(.relation(name: "orders", schema: "sales", type: .table))]) + + provider.answer(with: .names(["accounts", "customers"])) + await viewModel.reload().value + + #expect(model.selectedRowIDs.isEmpty) + } + @Test("The sort the reader chose orders the next listing too") func sortSurvivesARefresh() async { let (viewModel, provider) = makeViewModel() From 887d1fde4d17b63a2f7bc840e1a1f5289d46325d Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:44:38 +0700 Subject: [PATCH 049/123] fix(listing): refresh the new kind when Show Objects retargets an open tab The refresh Show Objects sends reached the model for the tab's old kind before the next draw replaced it, so the new kind showed the sidebar's list unread. The coordinator now owns the listing models, and a request that moves a tab to another kind retires the old model at once and has the new kind's model read the server on its first load. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ViewModels/TableListingViewModel.swift | 23 +++++- .../Main/Child/MainEditorContentView.swift | 5 +- ...MainContentCoordinator+ObjectListing.swift | 9 +++ .../Views/Main/MainContentCoordinator.swift | 3 + .../Main/CoordinatorTableListingTests.swift | 80 +++++++++++++++++++ 5 files changed, 116 insertions(+), 4 deletions(-) diff --git a/apple/TablePro/ViewModels/TableListingViewModel.swift b/apple/TablePro/ViewModels/TableListingViewModel.swift index e32f71e81d..13302d46a4 100644 --- a/apple/TablePro/ViewModels/TableListingViewModel.swift +++ b/apple/TablePro/ViewModels/TableListingViewModel.swift @@ -42,6 +42,7 @@ internal final class TableListingViewModel: ObservableObject { private var loadTask: Task? private var generation = 0 private var refreshSubscription: AnyCancellable? + private var firstLoadRereads = false init( tabId: UUID, @@ -79,7 +80,13 @@ internal final class TableListingViewModel: ObservableObject { @discardableResult func loadIfNeeded() -> Task? { guard case .idle = state else { return nil } - return load(rereading: false) + return load(rereading: firstLoadRereads) + } + + /// The tab was asked for fresh rows before this model existed, so its first load asks the server + /// rather than taking the list the sidebar holds. + func rereadOnFirstLoad() { + firstLoadRereads = true } // Refresh and Try Again ask the server again; the first load takes a list the sidebar already holds. @@ -196,6 +203,7 @@ internal final class TableListingViewModel: ObservableObject { @MainActor internal final class TableListingModelStore { private var models: [UUID: TableListingViewModel] = [:] + private var pendingRereads: [UUID: DatabaseTreeObjectGroup] = [:] /// A tab keeps its model while it lists the same container and kind. A retarget gets a fresh one, /// so another kind's rows never stand in for the new kind's while it loads. @@ -211,14 +219,27 @@ internal final class TableListingModelStore { existing.retire() } let model = make() + if pendingRereads.removeValue(forKey: tabId) == target { + model.rereadOnFirstLoad() + } models[tabId] = model return model } + /// A command asked the tab for fresh rows of `target`. A model already listing it takes the + /// request as a refresh event. Any other model goes now, so that event does not reach it, and the + /// model the tab's next draw makes for `target` reads it again rather than taking the sidebar's list. + func expectReread(forTab tabId: UUID, target: DatabaseTreeObjectGroup) { + guard models[tabId]?.target != target else { return } + models.removeValue(forKey: tabId)?.retire() + pendingRereads[tabId] = target + } + func retainTabs(_ openTabIds: Set) { for (tabId, model) in models where !openTabIds.contains(tabId) { model.cancel() } models = models.filter { openTabIds.contains($0.key) } + pendingRereads = pendingRereads.filter { openTabIds.contains($0.key) } } } diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index 106c8ae106..99bcd19552 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -56,7 +56,6 @@ struct MainEditorContentView: View { @State private var usersRolesViewModels: [UUID: UsersRolesViewModel] = [:] @State private var queryInsightsViewModels: [UUID: QueryInsightsViewModel] = [:] @State private var tableHealthViewModels: [UUID: TableHealthViewModel] = [:] - @State private var tableListingModels = TableListingModelStore() @ObservedObject private var treeService = DatabaseTreeMetadataService.shared // Table highlight rules live here, not on the tab; unobserved, Add Rule on a table tab changed nothing on screen. @@ -157,7 +156,7 @@ struct MainEditorContentView: View { queryInsightsViewModels = queryInsightsViewModels.filter { openTabIds.contains($0.key) } tableHealthViewModels = tableHealthViewModels.filter { openTabIds.contains($0.key) } // A listing a table click took over keeps its id, and its model must go with the listing. - tableListingModels.retainTabs(Set(tabManager.tabs.filter { $0.tabType == .tableListing }.map(\.id))) + coordinator.tableListingModels.retainTabs(Set(tabManager.tabs.filter { $0.tabType == .tableListing }.map(\.id))) SchemaProviderRegistry.shared.reclaimUnheldProviders(for: connectionId) } .onChange(of: tabManager.selectedTabId) { _ in @@ -236,7 +235,7 @@ struct MainEditorContentView: View { ) let target = DatabaseTreeObjectGroup(database: scope.database, schema: scope.schema, kind: kind) let tabId = tab.id - let model = tableListingModels.model(forTab: tabId, target: target) { + let model = coordinator.tableListingModels.model(forTab: tabId, target: target) { TableListingViewModel( tabId: tabId, scope: scope, diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift index 0f0b764758..cecbcfaab5 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift @@ -34,6 +34,15 @@ extension MainContentCoordinator { guard !asPreview else { return } /// Asking again for a listing already open brings it up to date, the way Refresh would. A tab /// opened just now loads when its view first appears, and nothing is listening for this yet. + /// One moved to another kind draws that kind's model only after this returns, so the store + /// holds the request for that model instead of letting the outgoing one take it. + if landing != nil { + let kind = ObjectListingKinds.effective(target.kind, declared: connection.type.declaredObjectKinds) + tableListingModels.expectReread( + forTab: tabId, + target: DatabaseTreeObjectGroup(database: target.database, schema: schemaName, kind: kind) + ) + } AppEvents.shared.tabRefreshRequested.send(tabId) } diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 8d3cde5fab..bd7526e555 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -202,6 +202,8 @@ final class MainContentCoordinator: ObservableObject { @Published var userTypeEditors: [UUID: UserTypeEditorModel] = [:] // Held here for the same reason: the diagram stages schema edits that Save and the close gate reach. @Published var erDiagramModels: [UUID: ERDiagramViewModel] = [:] + // Here rather than in the view, so a command can reach a listing's model before the view next draws it. + let tableListingModels = TableListingModelStore() // The cached view model keeps staged work after `usersRolesActions` is nilled; without this a background tab closes silently. internal var tabsWithStagedPrincipals: Set = [] @@ -878,6 +880,7 @@ final class MainContentCoordinator: ObservableObject { createTableDrafts.removeAll() userTypeEditors.removeAll() erDiagramModels.removeAll() + tableListingModels.retainTabs([]) displayFormatsCache.removeAll() tableMetadataCache.removeAll() schemaColumns.removeAll() diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index 793f099084..e96c2d242b 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -10,6 +10,26 @@ import Testing @testable import TablePro +private struct ObjectListRead: Equatable { + let category: SidebarObjectCategory + let rereading: Bool +} + +/// Answers every kind with nothing and records each read, so a case sees which read a model made. +@MainActor +private final class RecordingObjectSource: CatalogObjectListSource { + private(set) var reads: [ObjectListRead] = [] + + func objects( + _ category: SidebarObjectCategory, + in scope: DatabaseScope, + rereading: Bool + ) async -> MetadataFetchOutcome { + reads.append(ObjectListRead(category: category, rereading: rereading)) + return .fetched(category == .table ? .relations([]) : .routines([])) + } +} + /// Show All Tables used to open the listing statement in an editor tab, "Query 1", that nothing ran. @MainActor struct CoordinatorTableListingTests { @@ -212,6 +232,66 @@ struct CoordinatorTableListingTests { #expect(refreshed == [kept]) } + /// What the view hands the store when it draws the tab, with reads that go to `source`. + private func drawnModel( + _ coordinator: MainContentCoordinator, + tab tabId: UUID, + _ target: DatabaseTreeObjectGroup, + source: RecordingObjectSource + ) -> TableListingViewModel { + coordinator.tableListingModels.model(forTab: tabId, target: target) { + TableListingViewModel( + tabId: tabId, + scope: DatabaseScope(connectionId: coordinator.connectionId, database: target.database, schema: target.schema), + kind: target.kind, + loader: TableListingLoader(databaseType: .mysql, slot: .database), + objectSource: source + ) + } + } + + /// The view draws a retargeted tab's new model only after Show Objects returns, so the refresh it + /// sent reached the model being replaced, and the new kind showed the sidebar's list unread. + @Test("Show Objects of another kind on an open tab reads the new kind again, and the old kind's model takes no refresh") + func showObjectsRereadsTheNewKind() async throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + let source = RecordingObjectSource() + coordinator.showObjects(group("shop", .view), asPreview: false) + let id = try #require(tabManager.selectedTabId) + let views = drawnModel(coordinator, tab: id, group("shop", .view), source: source) + await views.loadIfNeeded()?.value + + coordinator.showObjects(group("shop", .function), asPreview: false) + #expect(!views.isRefreshing) + let functions = drawnModel(coordinator, tab: id, group("shop", .function), source: source) + await functions.loadIfNeeded()?.value + + #expect(functions !== views) + #expect(source.reads == [ + ObjectListRead(category: .table, rereading: false), + ObjectListRead(category: .routine, rereading: true), + ]) + } + + @Test("Picking another kind takes the sidebar's list, as a tab opened fresh does") + func pickingAKindTakesTheSidebarsList() async throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + let source = RecordingObjectSource() + coordinator.showObjects(group("shop", .view), asPreview: false) + let id = try #require(tabManager.selectedTabId) + await drawnModel(coordinator, tab: id, group("shop", .view), source: source).loadIfNeeded()?.value + + coordinator.selectListingKind(.function, inTab: id) + await drawnModel(coordinator, tab: id, group("shop", .function), source: source).loadIfNeeded()?.value + + #expect(source.reads == [ + ObjectListRead(category: .table, rereading: false), + ObjectListRead(category: .routine, rereading: false), + ]) + } + @Test("Picking a kind retargets the tab, relabels it and keeps the preview") func pickingAKindKeepsThePreview() throws { let (coordinator, tabManager, _) = makeCoordinator() From 37130ebebfe20c412651e02c6b19e1141e43b8fd Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:57:41 +0700 Subject: [PATCH 050/123] fix(listing): follow the sidebar's list in the Views, Functions, Triggers and Types tabs The tab copied the sidebar service's list once, so a sidebar refresh, a statement that changed the catalog or a drop never reached it. The tab now follows the service's list for its container and kind, keeping the shown rows meanwhile and its filter, sort and selection. A tab Refresh that a newer sidebar read overtook also returned the rows the list held before either read began. It now waits for that read and returns its rows. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/CatalogObjectListSource.swift | 30 +++++++++- .../Query/DatabaseTreeMetadataService.swift | 53 +++++++++------- .../Services/Query/ObjectListingRows.swift | 5 ++ .../ViewModels/TableListingViewModel.swift | 17 ++++++ .../Autocomplete/SQLSchemaProviderTests.swift | 25 +++++++- .../Query/CatalogObjectListSourceTests.swift | 53 ++++++++++++++++ .../TableListingViewModelTests.swift | 60 +++++++++++++++++++ .../Main/CoordinatorTableListingTests.swift | 4 ++ 8 files changed, 223 insertions(+), 24 deletions(-) diff --git a/apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift b/apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift index e24c0ef2fa..d8d1705622 100644 --- a/apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift +++ b/apple/TablePro/Core/Services/Query/CatalogObjectListSource.swift @@ -3,6 +3,7 @@ // TablePro // +import Combine import Foundation /// Where an Objects tab reads every kind but Tables. The sidebar's own lists, so the tab and the @@ -15,6 +16,10 @@ internal protocol CatalogObjectListSource: AnyObject, Sendable { in scope: DatabaseScope, rereading: Bool ) async -> MetadataFetchOutcome + + /// The list the sidebar holds for the category in `scope`, again each time it commits one, so an + /// open tab follows a sidebar refresh, a statement that changed the catalog, or a drop. + func objectListChanges(_ category: SidebarObjectCategory, in scope: DatabaseScope) -> AnyPublisher } extension DatabaseTreeMetadataService: CatalogObjectListSource { @@ -62,15 +67,36 @@ extension DatabaseTreeMetadataService: CatalogObjectListSource { } } + /// Every commit publishes, since the lists compare by identity and a row count or a comment can + /// change under the same names. A reader skips what it already shows. + func objectListChanges(_ category: SidebarObjectCategory, in scope: DatabaseScope) -> AnyPublisher { + let schema = scope.schema.flatMap { $0.isEmpty ? nil : $0 } + let key = ObjectsKey(connectionId: scope.connectionId, database: scope.database, schema: schema) + switch category { + case .table: + return $tablesState.compactMap { $0[key]?.value }.map(CatalogObjectList.relations).eraseToAnyPublisher() + case .routine: + return $routinesState.compactMap { $0[key]?.value }.map(CatalogObjectList.routines).eraseToAnyPublisher() + case .trigger: + return $triggersState.compactMap { $0[key]?.value }.map(CatalogObjectList.triggers).eraseToAnyPublisher() + case .type: + return $typesState.compactMap { $0[key]?.value }.map(CatalogObjectList.types).eraseToAnyPublisher() + } + } + private func listOutcome( rereading: Bool, - reread: () async -> Void, + reread: () async -> Bool, load: () async -> Void, state: () -> MetadataLoadState, wrap: (Value) -> CatalogObjectList ) async -> MetadataFetchOutcome { if rereading { - await reread() + // A newer read overtook this one and owns the list, which holds the rows from before + // either began until that read commits; loading again joins it at its revision. + if await reread() { + await load() + } } else { await load() } diff --git a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift index 2bfd60af3c..39c84a3695 100644 --- a/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift +++ b/apple/TablePro/Core/Services/Query/DatabaseTreeMetadataService.swift @@ -611,39 +611,46 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { /// The schema's trigger list alone beside the tables: the table refresh already reads every detail /// list, the per-table Triggers among them, and reading one twice at once cancels the first read. func refreshObjects(connectionId: UUID, database: String, schema: String?) async { - async let tables: Void = refreshTableObjects(connectionId: connectionId, database: database, schema: schema) - async let routines: Void = refreshRoutineObjects(connectionId: connectionId, database: database, schema: schema) - async let triggers: Void = rereadTriggers( + async let tables = refreshTableObjects(connectionId: connectionId, database: database, schema: schema) + async let routines = refreshRoutineObjects(connectionId: connectionId, database: database, schema: schema) + async let triggers = rereadTriggers( Self.objectsKey(connectionId: connectionId, database: database, schema: schema) ) - async let types: Void = refreshUserDefinedTypeObjects( + async let types = refreshUserDefinedTypeObjects( connectionId: connectionId, database: database, schema: schema ) _ = await (tables, routines, triggers, types) } /// A row refreshes only the fetch its kind comes from. Partitions and a table's detail lists ride - /// with the tables, because their rows are drawn as children of a table. - func refreshTableObjects(connectionId: UUID, database: String, schema: String?) async { + /// with the tables, because their rows are drawn as children of a table. Each says whether a newer + /// read overtook it, for a reader that needs that read's rows rather than the ones the list kept + /// meanwhile. + @discardableResult + func refreshTableObjects(connectionId: UUID, database: String, schema: String?) async -> Bool { let key = Self.objectsKey(connectionId: connectionId, database: database, schema: schema) - async let tables: Void = rereadTables(key) + async let tables = rereadTables(key) async let partitions: Void = refreshPartitions(under: key) async let details: Void = refreshTableDetails(under: key) - _ = await (tables, partitions, details) + let (overtaken, _, _) = await (tables, partitions, details) + return overtaken } - func refreshRoutineObjects(connectionId: UUID, database: String, schema: String?) async { + @discardableResult + func refreshRoutineObjects(connectionId: UUID, database: String, schema: String?) async -> Bool { let key = Self.objectsKey(connectionId: connectionId, database: database, schema: schema) - await reread(key, connectionId: connectionId, in: routineLists, fetch: routineListFetch(key)) + return await reread(key, connectionId: connectionId, in: routineLists, fetch: routineListFetch(key)) } /// A table's Triggers group lists the same triggers one table at a time, so it reads again with /// the schema's list rather than staying stale beside it. - func refreshTriggerObjects(connectionId: UUID, database: String, schema: String?) async { + @discardableResult + func refreshTriggerObjects(connectionId: UUID, database: String, schema: String?) async -> Bool { let key = Self.objectsKey(connectionId: connectionId, database: database, schema: schema) - async let triggers: Void = rereadTriggers(key) + async let triggers = rereadTriggers(key) async let details: Void = refreshTableDetails(under: key, kinds: [.triggers]) - _ = await (triggers, details) + let (overtaken, _) = await (triggers, details) + return overtaken } /// The hierarchical layout reloads a schema through `SchemaService`, which holds no detail list, @@ -652,19 +659,20 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { await refreshTableDetails(under: Self.objectsKey(connectionId: connectionId, database: database, schema: schema)) } - func refreshUserDefinedTypeObjects(connectionId: UUID, database: String, schema: String?) async { - guard browsesUserDefinedTypes(connectionId) else { return } + @discardableResult + func refreshUserDefinedTypeObjects(connectionId: UUID, database: String, schema: String?) async -> Bool { + guard browsesUserDefinedTypes(connectionId) else { return false } let key = Self.objectsKey(connectionId: connectionId, database: database, schema: schema) - await reread(key, connectionId: connectionId, in: typeLists, fetch: typeListFetch(key)) + return await reread(key, connectionId: connectionId, in: typeLists, fetch: typeListFetch(key)) } - private func rereadTables(_ key: ObjectsKey) async { + private func rereadTables(_ key: ObjectsKey) async -> Bool { await reread(key, connectionId: key.connectionId, in: tableLists, fetch: tableListFetch(key)) } - private func rereadTriggers(_ key: ObjectsKey) async { - guard browsesTriggers(key.connectionId) else { return } - await reread(key, connectionId: key.connectionId, in: triggerLists, fetch: triggerListFetch(key)) + private func rereadTriggers(_ key: ObjectsKey) async -> Bool { + guard browsesTriggers(key.connectionId) else { return false } + return await reread(key, connectionId: key.connectionId, in: triggerLists, fetch: triggerListFetch(key)) } /// A list that is not loaded is dropped and read by its next reader rather than now. @@ -811,17 +819,20 @@ final class DatabaseTreeMetadataService: ObservableObject, CatalogChangeTarget { /// Refresh and Retry: supersede before the first suspension, so a fetch still in flight cannot /// commit, and a reread superseded meanwhile stops rather than committing under the newer token. + /// Returns whether it was superseded so. + @discardableResult private func reread( _ key: Key, connectionId: UUID, in list: TreeList, fetch: @Sendable @escaping () async throws -> Value - ) async { + ) async -> Bool { let token = self[keyPath: list.commit].fence.supersede(key) self[keyPath: list.commit].freshness.markChanged(key) let revision = self[keyPath: list.commit].freshness.revision(for: key) await list.dedup.cancel { $0.key == key && $0.revision != revision } await read(key, connectionId: connectionId, in: list, token: token, fetch: fetch) + return !self[keyPath: list.commit].fence.isCurrent(token, for: key) } private func schemaListFetch(_ key: DatabaseKey) -> @Sendable () async throws -> [String] { diff --git a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift index 934936991a..9fd09491eb 100644 --- a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift +++ b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift @@ -54,6 +54,11 @@ extension ObjectListingItem { } extension TableListing { + /// A list the sidebar commits again unchanged has nothing for the grid to redraw. + func showsSameRows(as other: TableListing) -> Bool { + rows.columns == other.rows.columns && rows.rows == other.rows.rows && items == other.items + } + /// Where each object `previous` listed sits in this listing, by row id. Row ids are positions, so /// an object created or dropped above another moves it to another id. Nil when `previous` names no /// objects: its rows are plain values with nothing to follow. diff --git a/apple/TablePro/ViewModels/TableListingViewModel.swift b/apple/TablePro/ViewModels/TableListingViewModel.swift index 13302d46a4..6ef5dc22c2 100644 --- a/apple/TablePro/ViewModels/TableListingViewModel.swift +++ b/apple/TablePro/ViewModels/TableListingViewModel.swift @@ -42,6 +42,7 @@ internal final class TableListingViewModel: ObservableObject { private var loadTask: Task? private var generation = 0 private var refreshSubscription: AnyCancellable? + private var listSubscription: AnyCancellable? private var firstLoadRereads = false init( @@ -70,6 +71,11 @@ internal final class TableListingViewModel: ObservableObject { self?.menuItems(for: rowIDs, clicked: clicked) ?? [] } grid.opensRow = { [weak self] rowID in self?.open(rowID) } + // Tables come from the plugin's listing statement; every other kind is the sidebar's own list. + if kind != .table { + listSubscription = objectSource.objectListChanges(kind.category, in: scope) + .sink { [weak self] list in self?.follow(list) } + } } /// Whether each row names an object, which the name filter and the row commands need. @@ -110,6 +116,7 @@ internal final class TableListingViewModel: ObservableObject { loadTask?.cancel() generation &+= 1 refreshSubscription = nil + listSubscription = nil } private func load(rereading: Bool) -> Task { @@ -169,6 +176,16 @@ internal final class TableListingViewModel: ObservableObject { showRows(replacing: previous) } + /// The sidebar committed this kind's list, after a refresh, a statement or a drop there: rows on + /// screen follow it, so the tab and the tree never disagree. A first load on its way brings its own. + private func follow(_ list: CatalogObjectList) { + guard let shown = state.value else { return } + let listing = ObjectListingRows.listing(kind: target.kind, from: list, scope: scope) + guard !listing.showsSameRows(as: shown) else { return } + state = .loaded(listing) + showRows(replacing: shown) + } + /// The grid keeps its selection by row id, which is a position here, so rows replacing `previous` /// carry it to the same objects: Return and the menu act on what the reader picked. private func showRows(replacing previous: TableListing? = nil) { diff --git a/apple/TableProTests/Core/Autocomplete/SQLSchemaProviderTests.swift b/apple/TableProTests/Core/Autocomplete/SQLSchemaProviderTests.swift index ad9c23b09f..e87e33b941 100644 --- a/apple/TableProTests/Core/Autocomplete/SQLSchemaProviderTests.swift +++ b/apple/TableProTests/Core/Autocomplete/SQLSchemaProviderTests.swift @@ -12,6 +12,23 @@ import TableProPluginKit import TableProTestSupport import Testing +/// One read held on the wire: `reached` opens when the read gets there, `cancelled` when its task is +/// cancelled, and the read returns once `release` opens. +final class HeldDriverRead: Sendable { + let reached = AsyncGate() + let release = AsyncGate() + let cancelled = AsyncGate() + + func hold() async { + await reached.open() + await withTaskCancellationHandler { + await release.wait() + } onCancel: { + Task { await self.cancelled.open() } + } + } +} + final class MockDatabaseDriver: DatabaseDriver, SchemaSwitchable, @unchecked Sendable { let connection: DatabaseConnection var status: ConnectionStatus = .connected @@ -95,9 +112,15 @@ final class MockDatabaseDriver: DatabaseDriver, SchemaSwitchable, @unchecked Sen } var schemaRoutinesToReturn: [String: [RoutineInfo]] = [:] + /// Each `fetchRoutines(schema:)` takes the next hold after reading its rows, so a case can keep two + /// reads on the wire at once. + var routineFetchHolds: [HeldDriverRead] = [] func fetchRoutines(schema: String?) async throws -> [RoutineInfo] { - schema.flatMap { schemaRoutinesToReturn[$0] } ?? [] + let snapshot = schema.flatMap { schemaRoutinesToReturn[$0] } ?? [] + guard !routineFetchHolds.isEmpty else { return snapshot } + await routineFetchHolds.removeFirst().hold() + return snapshot } func fetchSchemas() async throws -> [String] { diff --git a/apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift b/apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift index 70bbf76197..db8cc8e7ee 100644 --- a/apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift +++ b/apple/TableProTests/Core/Services/Query/CatalogObjectListSourceTests.swift @@ -3,7 +3,9 @@ // TableProTests // +import Combine import Foundation +import TableProTestSupport import Testing @testable import TablePro @@ -88,6 +90,57 @@ struct CatalogObjectListSourceTests { await disconnect(connection) } + @Test("A tab follows the sidebar's own list: a read the sidebar commits reaches it") + func changesFollowTheSidebarsList() async { + let (connection, driver) = connect() + let touch = RoutineInfo(name: "touch", kind: .function, schema: "public") + let audit = RoutineInfo(name: "audit", kind: .function, schema: "public") + driver.schemaRoutinesToReturn = ["public": [touch]] + var seen: [CatalogObjectList] = [] + let subscription = service.objectListChanges(.routine, in: scope(connection)).sink { seen.append($0) } + defer { subscription.cancel() } + + _ = await service.objects(.routine, in: scope(connection), rereading: false) + #expect(seen.last == .routines([touch])) + + driver.schemaRoutinesToReturn = ["public": [touch, audit]] + await service.refreshRoutineObjects(connectionId: connection.id, database: connection.database, schema: "public") + + #expect(seen.last == .routines([touch, audit])) + await disconnect(connection) + } + + /// The list keeps its rows while a newer read runs, so taking it as it stood handed the tab the + /// rows from before either read began, as if they were fresh. + @Test("A refresh a newer sidebar read overtakes waits for that read and returns its rows") + func overtakenRefreshTakesTheNewerRead() async { + let (connection, driver) = connect() + let touch = RoutineInfo(name: "touch", kind: .function, schema: "public") + let audit = RoutineInfo(name: "audit", kind: .function, schema: "public") + let purge = RoutineInfo(name: "purge", kind: .function, schema: "public") + driver.schemaRoutinesToReturn = ["public": [touch]] + _ = await service.objects(.routine, in: scope(connection), rereading: false) + let tabRead = HeldDriverRead() + let sidebarRead = HeldDriverRead() + driver.routineFetchHolds = [tabRead, sidebarRead] + + driver.schemaRoutinesToReturn = ["public": [touch, audit]] + let refresh = Task { await service.objects(.routine, in: scope(connection), rereading: true) } + await tabRead.reached.wait() + driver.schemaRoutinesToReturn = ["public": [touch, audit, purge]] + let sidebar = Task { + await service.refreshRoutineObjects(connectionId: connection.id, database: connection.database, schema: "public") + } + await tabRead.cancelled.wait() + await tabRead.release.open() + await sidebarRead.reached.wait() + await sidebarRead.release.open() + + #expect(fetched(await refresh.value) == .routines([touch, audit, purge])) + _ = await sidebar.value + await disconnect(connection) + } + @Test("A read the server refused says why") func refusedReadSaysWhy() async { let (connection, driver) = connect() diff --git a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift index 2c3eef1070..3391106b50 100644 --- a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift +++ b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift @@ -105,6 +105,8 @@ private struct ObjectSourceRequest: Equatable { @MainActor private final class ScriptedObjectSource: CatalogObjectListSource { var reply: MetadataFetchOutcome = .fetched(.routines([])) + // The sidebar committing a list, which an open tab of another kind follows. + let changes = PassthroughSubject() // Taken in order before `reply`, for a read that answers differently the next time. var replies: [MetadataFetchOutcome] = [] private(set) var requests: [ObjectSourceRequest] = [] @@ -130,6 +132,10 @@ private final class ScriptedObjectSource: CatalogObjectListSource { } return reply } + + func objectListChanges(_ category: SidebarObjectCategory, in scope: DatabaseScope) -> AnyPublisher { + changes.eraseToAnyPublisher() + } } @MainActor @@ -539,6 +545,60 @@ struct TableListingViewModelTests { #expect(viewModel.state.erased == .failed("permission denied for schema sales")) } + // MARK: - Following the sidebar + + @Test("Another kind's open tab follows the sidebar's list, keeping its filter, sort and selection") + func otherKindFollowsTheSidebarsList() async throws { + let source = ScriptedObjectSource() + source.reply = .fetched(functions("touch", "audit", "archive_orders")) + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + await viewModel.loadIfNeeded()?.value + let model = viewModel.grid.model + model.setSort(SortState(columns: [SortColumn(columnIndex: 0, direction: .ascending)], source: .user)) + viewModel.filterText = "a" + #expect(gridNames(viewModel) == ["archive_orders", "audit"]) + model.selectCell(GridCoord(row: 1, displayColumn: 0)) + + // A statement created two functions, one of them listed before the selected one. + source.changes.send(functions("purge", "touch", "audit", "archive_orders", "alert")) + + #expect(gridNames(viewModel) == ["alert", "archive_orders", "audit"]) + #expect(viewModel.count == ObjectListingCount(shown: 3, total: 5)) + let selected = try #require(model.selectedRowIDs.first) + #expect(viewModel.state.value?.items[selected]?.name == "audit") + + source.changes.send(functions("touch", "archive_orders")) + + #expect(gridNames(viewModel) == ["archive_orders"]) + #expect(model.selectedRowIDs.isEmpty) + } + + @Test("A list the sidebar commits again unchanged leaves the grid as it is") + func unchangedListLeavesTheGrid() async { + let source = ScriptedObjectSource() + source.reply = .fetched(functions("touch", "audit")) + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + await viewModel.loadIfNeeded()?.value + let revision = viewModel.grid.model.displayRevision + + source.changes.send(functions("touch", "audit")) + + #expect(viewModel.grid.model.displayRevision == revision) + } + + @Test("The sidebar's list leaves a tab with nothing loaded to its own first load") + func followingWaitsForTheFirstLoad() async { + let source = ScriptedObjectSource() + source.reply = .fetched(functions("touch")) + let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) + + source.changes.send(functions("touch", "audit")) + #expect(viewModel.state.erased == .idle) + + await viewModel.loadIfNeeded()?.value + #expect(names(viewModel.state) == ["touch"]) + } + // MARK: - Filter and count @Test("The filter narrows the rows and the count, fetches nothing, and keeps the preview") diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index e96c2d242b..4b0e38debe 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -28,6 +28,10 @@ private final class RecordingObjectSource: CatalogObjectListSource { reads.append(ObjectListRead(category: category, rereading: rereading)) return .fetched(category == .table ? .relations([]) : .routines([])) } + + func objectListChanges(_ category: SidebarObjectCategory, in scope: DatabaseScope) -> AnyPublisher { + Empty().eraseToAnyPublisher() + } } /// Show All Tables used to open the listing statement in an editor tab, "Query 1", that nothing ran. From fb6ffb5757d157eab1cc512969d7869fb39c7fc4 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 08:01:27 +0700 Subject: [PATCH 051/123] fix(listing): read no extra metadata when an Objects tab opens Opening any Objects tab loaded the container's tables, routines, triggers and types for the kind picker. The model already reads the tab's own kind, and Tables reads none of the sidebar's lists, so the view now reads nothing more; the picker offers the groups from the lists the sidebar already holds. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Views/Main/Child/MainEditorContentView.swift | 4 ++-- .../ViewModels/TableListingViewModelTests.swift | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index 99bcd19552..89da36d00a 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -260,12 +260,12 @@ struct MainEditorContentView: View { kindTitle: { $0.title(tableEntityName: tableEntityName) }, onSelectKind: { coordinator.selectListingKind($0, inTab: tabId) } ) + // The model reads the tab's own kind, and Tables reads none of the sidebar's lists. The picker + // offers the groups the sidebar shows, from the lists it already holds, so nothing else is read. .task(id: target) { if (tab.display.listingKind ?? .table) != kind { coordinator.adoptListingKind(kind, inTab: tabId) } - // The picker offers the groups the sidebar shows, so the container's lists are read once here. - await treeService.loadObjects(connectionId: scope.connectionId, database: scope.database, schema: scope.schema) } .id(tab.id) } diff --git a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift index 3391106b50..0fcdd748c2 100644 --- a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift +++ b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift @@ -502,6 +502,20 @@ struct TableListingViewModelTests { #expect(provider.executedQueries.isEmpty) } + // The view reads no list for the picker, so the model's own read is all an open tab costs. + @Test("A Tables listing reads none of the sidebar's lists, on its first load or a refresh") + func tablesReadNoSidebarList() async { + let source = ScriptedObjectSource() + let (viewModel, provider) = makeViewModel(objectSource: source) + provider.answer(with: .names(["orders"])) + + await viewModel.loadIfNeeded()?.value + await viewModel.reload().value + + #expect(source.requests.isEmpty) + #expect(provider.executedQueries.count == 2) + } + @Test("The first load takes the list the sidebar holds, and a refresh reads it again") func firstLoadTakesTheListAndRefreshRereads() async { let source = ScriptedObjectSource() From e74dc37200cea2ffdf96ee86d5b78988d1443ed9 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:04:00 +0700 Subject: [PATCH 052/123] feat(toolbar): add the setting that shows object buttons in the toolbar Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Models/Settings/GeneralSettings.swift | 5 +++++ apple/TableProTests/Models/GeneralSettingsTests.swift | 1 + 2 files changed, 6 insertions(+) diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 78e9361cd4..5dd87ca9ed 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -62,6 +62,7 @@ struct GeneralSettings: Codable, Equatable { var shareAnalytics: Bool var showRecentTables: Bool var showsObjectsOnSelection: Bool + var showsObjectToolbar: Bool var showObjectComments: Bool var showObjectIcons: Bool var showSystemContainers: Bool @@ -79,6 +80,7 @@ struct GeneralSettings: Codable, Equatable { shareAnalytics: true, showRecentTables: false, showsObjectsOnSelection: false, + showsObjectToolbar: false, showObjectComments: true, showObjectIcons: true, showSystemContainers: false, @@ -97,6 +99,7 @@ struct GeneralSettings: Codable, Equatable { shareAnalytics: Bool = true, showRecentTables: Bool = false, showsObjectsOnSelection: Bool = false, + showsObjectToolbar: Bool = false, showObjectComments: Bool = true, showObjectIcons: Bool = true, showSystemContainers: Bool = false, @@ -113,6 +116,7 @@ struct GeneralSettings: Codable, Equatable { self.shareAnalytics = shareAnalytics self.showRecentTables = showRecentTables self.showsObjectsOnSelection = showsObjectsOnSelection + self.showsObjectToolbar = showsObjectToolbar self.showObjectComments = showObjectComments self.showObjectIcons = showObjectIcons self.showSystemContainers = showSystemContainers @@ -135,6 +139,7 @@ struct GeneralSettings: Codable, Equatable { showsObjectsOnSelection = container.decodeSetting( .showsObjectsOnSelection, default: fallback.showsObjectsOnSelection ) + showsObjectToolbar = container.decodeSetting(.showsObjectToolbar, default: fallback.showsObjectToolbar) showObjectComments = container.decodeSetting(.showObjectComments, default: fallback.showObjectComments) showObjectIcons = container.decodeSetting(.showObjectIcons, default: fallback.showObjectIcons) showSystemContainers = container.decodeSetting(.showSystemContainers, default: fallback.showSystemContainers) diff --git a/apple/TableProTests/Models/GeneralSettingsTests.swift b/apple/TableProTests/Models/GeneralSettingsTests.swift index 9abf6fe439..1a4d15710f 100644 --- a/apple/TableProTests/Models/GeneralSettingsTests.swift +++ b/apple/TableProTests/Models/GeneralSettingsTests.swift @@ -66,6 +66,7 @@ struct GeneralSettingsBoolSettingTests { BoolSetting(key: "shareAnalytics", defaultValue: true), BoolSetting(key: "showRecentTables", defaultValue: false), BoolSetting(key: "showsObjectsOnSelection", defaultValue: false), + BoolSetting(key: "showsObjectToolbar", defaultValue: false), BoolSetting(key: "showObjectComments", defaultValue: true), BoolSetting(key: "showObjectIcons", defaultValue: true), BoolSetting(key: "showSystemContainers", defaultValue: false), From cf3226a370957f09cd12f4ef06545fcb0d65bec0 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:09:33 +0700 Subject: [PATCH 053/123] feat(toolbar): decide when each object button is enabled Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Infrastructure/MainWindowToolbar.swift | 11 +++ .../Toolbar/ToolbarContextResolver.swift | 15 +++- apple/TablePro/Models/UI/ToolbarContext.swift | 28 +++++- .../MenuContentModeParityTests.swift | 52 ++++++++++++ .../ToolbarContextResolverTests.swift | 85 +++++++++++++++++++ 5 files changed, 186 insertions(+), 5 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index ba1335db96..32ff089d48 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -434,6 +434,17 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { ] // Xcode's pair. The steps live in the debug tab's own bar and the palette, which keeps a debug tab at eight hit targets. nonisolated static let debugDefaultItemIdentifiers: [NSToolbarItem.Identifier] = [debugContinue, debugStop] + // The Objects group a General setting adds. Its own identifiers, so Query never collides with New Tab in one toolbar. + nonisolated static let objectKindsGroup = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds") + nonisolated static let objectTables = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.tables") + nonisolated static let objectViews = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.views") + nonisolated static let objectFunctions = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.functions") + nonisolated static let objectUsers = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.users") + nonisolated static let objectQuery = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.query") + nonisolated static let objectBackup = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.backup") + nonisolated static let objectKindItemIdentifiers: [NSToolbarItem.Identifier] = [ + objectTables, objectViews, objectFunctions, objectUsers, objectQuery, objectBackup, + ] // MARK: - NSToolbarDelegate diff --git a/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift b/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift index 24cfb06a8b..b2806331f1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift @@ -82,7 +82,7 @@ internal enum ToolbarContextResolver { } // Agent mode mounts no browse content. `MenuContentModeParityTests` holds these to the menu bar's `agentModeSelectors`. - private static let browseContentIdentifiers: Set = [ + private static let browseContentIdentifiers = Set([ MainWindowToolbar.refresh, MainWindowToolbar.saveChanges, MainWindowToolbar.addRow, @@ -96,7 +96,7 @@ internal enum ToolbarContextResolver { MainWindowToolbar.importTables, MainWindowToolbar.navigateBack, MainWindowToolbar.navigateForward, - ] + ]).union(MainWindowToolbar.objectKindItemIdentifiers) // The same commands as the menu bar's `sheetCommandSelectors`: a window with a sheet attached takes no second one. private static let sheetCommandIdentifiers: Set = [ @@ -105,6 +105,7 @@ internal enum ToolbarContextResolver { MainWindowToolbar.exportTables, MainWindowToolbar.importTables, MainWindowToolbar.restorePreviousValues, + MainWindowToolbar.objectBackup, ] // The `default:` is false: an unconditional true left Query History live and inert over a window that never connected. @@ -162,6 +163,16 @@ internal enum ToolbarContextResolver { return context.debugCommands.contains(.stepOut) case MainWindowToolbar.debugStop: return context.canStopDebugging + case MainWindowToolbar.objectTables, MainWindowToolbar.objectViews: + return context.isConnected && context.canListObjects + case MainWindowToolbar.objectFunctions: + return context.isConnected && context.supportsRoutines + case MainWindowToolbar.objectUsers: + return context.isConnected && context.supportsUserManagement + case MainWindowToolbar.objectQuery: + return context.isConnected + case MainWindowToolbar.objectBackup: + return context.isConnected && context.supportsBackup default: return false } diff --git a/apple/TablePro/Models/UI/ToolbarContext.swift b/apple/TablePro/Models/UI/ToolbarContext.swift index c056534fa1..166292576c 100644 --- a/apple/TablePro/Models/UI/ToolbarContext.swift +++ b/apple/TablePro/Models/UI/ToolbarContext.swift @@ -47,6 +47,12 @@ internal struct ToolbarContext: Equatable { internal let canStopDebugging: Bool internal let isPresentingSheet: Bool + // What the connection supports, for the Objects group's buttons. Enablement only, never visibility. + internal let canListObjects: Bool + internal let supportsRoutines: Bool + internal let supportsUserManagement: Bool + internal let supportsBackup: Bool + // Only these stable facts may change the toolbar layout or labels. internal struct VisibilityKey: Equatable { internal let tabKind: TabType? @@ -100,7 +106,11 @@ internal struct ToolbarContext: Equatable { showsDebugItems: Bool = false, debugCommands: Set = [], canStopDebugging: Bool = false, - isPresentingSheet: Bool = false + isPresentingSheet: Bool = false, + canListObjects: Bool = false, + supportsRoutines: Bool = false, + supportsUserManagement: Bool = false, + supportsBackup: Bool = false ) { self.tabKind = tabKind self.resultsMode = resultsMode @@ -126,6 +136,10 @@ internal struct ToolbarContext: Equatable { self.debugCommands = debugCommands self.canStopDebugging = canStopDebugging self.isPresentingSheet = isPresentingSheet + self.canListObjects = canListObjects + self.supportsRoutines = supportsRoutines + self.supportsUserManagement = supportsUserManagement + self.supportsBackup = supportsBackup } // Over a key the caller already computed, so the slow-moving facts are read once per context. @@ -144,7 +158,11 @@ internal struct ToolbarContext: Equatable { canNavigateForward: Bool, debugCommands: Set = [], canStopDebugging: Bool = false, - isPresentingSheet: Bool = false + isPresentingSheet: Bool = false, + canListObjects: Bool = false, + supportsRoutines: Bool = false, + supportsUserManagement: Bool = false, + supportsBackup: Bool = false ) { self.init( tabKind: key.tabKind, @@ -170,7 +188,11 @@ internal struct ToolbarContext: Equatable { showsDebugItems: key.showsDebugItems, debugCommands: debugCommands, canStopDebugging: canStopDebugging, - isPresentingSheet: isPresentingSheet + isPresentingSheet: isPresentingSheet, + canListObjects: canListObjects, + supportsRoutines: supportsRoutines, + supportsUserManagement: supportsUserManagement, + supportsBackup: supportsBackup ) } } diff --git a/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift b/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift index 0c9871d298..febb7ae658 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift @@ -273,6 +273,58 @@ struct MenuContentModeParityTests { return context } + /// Users, Query and Backup in the Objects toolbar group run commands the menu bar already offers, + /// so each answers as its twin does in both modes, with and without a session or a sheet. + @Test("The object buttons answer as their menu-bar twins") + func objectButtonsMatchTheirMenuTwins() { + let twins: [CommandPair] = [ + CommandPair( + selector: #selector(MainSplitViewController.showUsersAndRoles(_:)), + identifier: MainWindowToolbar.objectUsers + ), + CommandPair( + selector: #selector(MainSplitViewController.newEditorTab(_:)), + identifier: MainWindowToolbar.objectQuery + ), + CommandPair( + selector: #selector(MainSplitViewController.backupDatabase(_:)), + identifier: MainWindowToolbar.objectBackup + ), + ] + for contentMode in ConnectionWorkspaceContentMode.allCases { + for connected in [true, false] { + for sheet in [false, true] { + var menu = Self.menuContext(contentMode) + menu.isConnected = connected + menu.isPresentingSheet = sheet + menu.supportsUserManagement = true + menu.supportsBackup = true + let toolbar = ToolbarContext( + tabKind: .query, + contentMode: contentMode, + pane: connected ? .content : .unavailable(.notConnected), + isConnected: connected, + hasSelectedWorkspace: true, + isPresentingSheet: sheet, + canListObjects: true, + supportsRoutines: true, + supportsUserManagement: true, + supportsBackup: true + ) + for twin in twins { + let menuAnswer = MainSplitViewController.isEnabled(twin.selector, context: menu) + let toolbarAnswer = ToolbarContextResolver.isEnabled(twin.identifier, context: toolbar) + let state = "\(contentMode.rawValue), connected \(connected), sheet \(sheet)" + #expect(menuAnswer == toolbarAnswer, "\(twin.name) and \(twin.identifier.rawValue) disagree: \(state)") + if contentMode == .browse, connected, !sheet { + #expect(menuAnswer, "\(twin.name) is dim while browsing a live session") + } + } + } + } + } + } + /// Named rather than left to the equality above, which two disabled answers would also satisfy. @Test("The window's own commands still answer in Agent mode") func theWindowsCommandsAnswerInAgentMode() { diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift index 6c6f06592e..32f866f1ee 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift @@ -466,4 +466,89 @@ struct ToolbarContextResolverTests { ) #expect(ToolbarContextResolver.isEnabled(MainWindowToolbar.saveChanges, context: context) == false) } + + // MARK: - The object buttons + + /// Every fact a button could ask for is true unless the case names it, so the named fact is + /// the only thing that can dim one. + private static func objectsContext( + connected: Bool = true, + contentMode: ConnectionWorkspaceContentMode = .browse, + canListObjects: Bool = true, + supportsRoutines: Bool = true, + supportsUserManagement: Bool = true, + supportsBackup: Bool = true, + isPresentingSheet: Bool = false + ) -> ToolbarContext { + ToolbarContext( + tabKind: .table, + contentMode: contentMode, + pane: connected ? .content : .unavailable(.notConnected), + isConnected: connected, + hasSelectedWorkspace: true, + supportsContainerSwitching: true, + isPresentingSheet: isPresentingSheet, + canListObjects: canListObjects, + supportsRoutines: supportsRoutines, + supportsUserManagement: supportsUserManagement, + supportsBackup: supportsBackup + ) + } + + private static func dimmedObjectButtons(_ context: ToolbarContext) -> Set { + Set(MainWindowToolbar.objectKindItemIdentifiers.filter { identifier in + !ToolbarContextResolver.isEnabled(identifier, context: context) + }) + } + + @Test("Every object button needs a live session") + func objectButtonsNeedASession() { + #expect(Self.dimmedObjectButtons(Self.objectsContext()).isEmpty) + #expect( + Self.dimmedObjectButtons(Self.objectsContext(connected: false)) + == Set(MainWindowToolbar.objectKindItemIdentifiers) + ) + } + + @Test("Each object button dims for its own missing capability and no other") + func objectButtonsFollowTheirCapability() { + #expect( + Self.dimmedObjectButtons(Self.objectsContext(canListObjects: false)) + == [MainWindowToolbar.objectTables, MainWindowToolbar.objectViews] + ) + #expect( + Self.dimmedObjectButtons(Self.objectsContext(supportsRoutines: false)) == [MainWindowToolbar.objectFunctions] + ) + #expect( + Self.dimmedObjectButtons(Self.objectsContext(supportsUserManagement: false)) == [MainWindowToolbar.objectUsers] + ) + #expect(Self.dimmedObjectButtons(Self.objectsContext(supportsBackup: false)) == [MainWindowToolbar.objectBackup]) + } + + /// Agent mode mounts no browse content, and the menu bar dims every twin of these there. + @Test("Agent mode dims the whole object group") + func agentModeDimsTheObjectGroup() { + #expect( + Self.dimmedObjectButtons(Self.objectsContext(contentMode: .agent)) + == Set(MainWindowToolbar.objectKindItemIdentifiers) + ) + } + + /// Backup presents a sheet, and a window with a sheet attached takes no second one. + @Test("A sheet on the window dims Backup and leaves the other buttons") + func aSheetDimsOnlyBackup() { + #expect(Self.dimmedObjectButtons(Self.objectsContext(isPresentingSheet: true)) == [MainWindowToolbar.objectBackup]) + } + + @Test("What the connection supports never reaches the visibility key") + func objectFactsStayOutOfTheVisibilityKey() { + let capable = Self.objectsContext() + let bare = Self.objectsContext( + canListObjects: false, + supportsRoutines: false, + supportsUserManagement: false, + supportsBackup: false + ) + #expect(capable.visibilityKey == bare.visibilityKey) + } } From 86e954ec492f7cf7ceb7646f63a4728e78e51a0c Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:15:47 +0700 Subject: [PATCH 054/123] feat(toolbar): build the Objects group and route its buttons Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Actions.swift | 26 +++ .../MainWindowToolbar+Delegate.swift | 4 + .../MainWindowToolbar+Items.swift | 49 +++++ .../Infrastructure/MainWindowToolbar.swift | 14 +- .../ObjectKindsToolbarTests.swift | 180 ++++++++++++++++++ .../MainWindowToolbarIdentifierTests.swift | 43 +++++ 6 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift index 88b2140121..3da3c89f72 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift @@ -87,6 +87,32 @@ extension MainWindowToolbar { coordinator?.frontRoutineDebugController?.stop() } + // The Objects group. Each button has its own action: the overflow menu validates an entry by its action. + @objc func performShowTables(_ sender: Any?) { + coordinator?.showBrowsedObjects(.table) + } + + @objc func performShowViews(_ sender: Any?) { + coordinator?.showBrowsedObjects(.view) + } + + @objc func performShowFunctions(_ sender: Any?) { + coordinator?.showBrowsedObjects(.function) + } + + // The same command actions the window's menu commands forward to, for the connection this toolbar points at. + @objc func performShowUsers(_ sender: Any?) { + coordinator?.commandActions?.showUsersAndRoles() + } + + @objc func performNewQuery(_ sender: Any?) { + coordinator?.commandActions?.newTab() + } + + @objc func performBackupDatabase(_ sender: Any?) { + coordinator?.commandActions?.backupDatabase() + } + /// The Inspector item on macOS 13, forwarded because the action belongs to the split controller /// and a toolbar item's explicit target has to respond to its own selector to validate. @objc func forwardToggleInspector(_ sender: Any?) { diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift index 004adfc3e4..5fcaad57c1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift @@ -130,6 +130,10 @@ extension MainWindowToolbar { // Answering nil while the module is off is what prunes the controls from a saved arrangement. guard debugItemsEnabled() else { return nil } return makeDebugItem(itemIdentifier) + case Self.objectKindsGroup: + // Answering nil while the setting is off is what prunes the group from a saved arrangement. + guard objectKindsEnabled() else { return nil } + return makeObjectKindsGroup() default: return nil } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift index 4b2be68d61..b149e4d8ce 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift @@ -355,6 +355,55 @@ extension MainWindowToolbar { } } + /// One click to each kind of object, built like the Back/Forward group so AppKit draws it, dims a + /// button that cannot open and folds all six into one overflow entry in a narrow window. Tables, + /// Views and Functions share the sidebar's glyphs for those kinds. + func makeObjectKindsGroup() -> NSToolbarItemGroup { + makeNativeGroup( + id: Self.objectKindsGroup, + label: String(localized: "Objects"), + subitems: [ + menuOnlyItem( + id: Self.objectTables, + label: String(localized: "Tables"), + symbol: SidebarObjectKind.table.iconName, + action: #selector(performShowTables(_:)) + ), + menuOnlyItem( + id: Self.objectViews, + label: String(localized: "Views"), + symbol: SidebarObjectKind.view.iconName, + action: #selector(performShowViews(_:)) + ), + menuOnlyItem( + id: Self.objectFunctions, + label: String(localized: "Functions"), + symbol: SidebarObjectKind.function.iconName, + action: #selector(performShowFunctions(_:)) + ), + menuOnlyItem( + id: Self.objectUsers, + label: String(localized: "Users"), + symbol: "person.2", + action: #selector(performShowUsers(_:)) + ), + menuOnlyItem( + id: Self.objectQuery, + label: String(localized: "Query"), + symbol: "doc.text", + action: #selector(performNewQuery(_:)), + shortcut: .newTab + ), + menuOnlyItem( + id: Self.objectBackup, + label: String(localized: "Backup"), + symbol: "archivebox", + action: #selector(performBackupDatabase(_:)) + ), + ] + ) + } + // MARK: - Helpers /// The label is what the customization palette and the overflow menu show, so it stays short. diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index 32ff089d48..be1b569eef 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -91,6 +91,11 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal var debugItemsRecord = ToolbarDebugItemsRecord() + // Whether Settings puts the Objects group in the toolbar; it is vended only then, so turning it off prunes it. + internal var objectKindsEnabled: @MainActor () -> Bool = { + AppSettingsManager.shared.general.showsObjectToolbar + } + /// `NSMenu.delegate` is weak, and the safe-mode control's menu is built here rather than by the /// menu bar, so this toolbar is what keeps its delegate alive. internal let safeModeMenuDelegate = SafeModeMenuDelegate() @@ -535,7 +540,14 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } internal func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { - debugItemsEnabled() ? Self.allowedItemIdentifiers + Self.debugItemIdentifiers : Self.allowedItemIdentifiers + var allowed = Self.allowedItemIdentifiers + if debugItemsEnabled() { + allowed += Self.debugItemIdentifiers + } + if objectKindsEnabled() { + allowed.append(Self.objectKindsGroup) + } + return allowed } // Replaced under test, where no window hosts the toolbar. diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift new file mode 100644 index 0000000000..bb68437fc0 --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -0,0 +1,180 @@ +// +// ObjectKindsToolbarTests.swift +// TableProTests +// + +import AppKit +import SwiftUI +@testable import TablePro +import Testing + +/// The optional Objects group: six buttons that reach each kind of object in one click. +@MainActor +struct ObjectKindsToolbarTests { + /// A private identifier with autosave off: the test host shares the app's defaults, so a toolbar + /// named like the app's own would carry anything done to it into the next real launch. + private static func owner(objectsOn: Bool = true) -> MainWindowToolbar { + let toolbar = NSToolbar(identifier: "com.TablePro.tests.objectKinds.\(UUID().uuidString)") + toolbar.autosavesConfiguration = false + let owner = MainWindowToolbar(managedToolbar: toolbar) + owner.objectKindsEnabled = { objectsOn } + return owner + } + + private static func group(from owner: MainWindowToolbar) throws -> NSToolbarItemGroup { + try #require( + owner.toolbar( + owner.managedToolbar, + itemForItemIdentifier: MainWindowToolbar.objectKindsGroup, + willBeInsertedIntoToolbar: true + ) as? NSToolbarItemGroup + ) + } + + private static func subitem( + _ identifier: NSToolbarItem.Identifier, + of owner: MainWindowToolbar + ) throws -> NSToolbarItem { + try #require(group(from: owner).subitems.first { $0.itemIdentifier == identifier }) + } + + /// What a click does: the button's own action, sent to the button's own target. + private static func press(_ identifier: NSToolbarItem.Identifier, on owner: MainWindowToolbar) throws { + let item = try subitem(identifier, of: owner) + let action = try #require(item.action) + #expect(NSApp.sendAction(action, to: item.target, from: item), "\(identifier.rawValue) reached no target") + } + + private static func makeActions(for fixture: CoordinatorFixture) -> MainContentCommandActions { + let actions = MainContentCommandActions( + coordinator: fixture.coordinator, + connection: fixture.connection, + selectedTables: .constant([]), + pendingTruncates: .constant([]), + pendingDeletes: .constant([]), + tableOperationOptions: .constant([:]), + trailingPaneState: TrailingPaneState() + ) + fixture.coordinator.commandActions = actions + return actions + } + + // MARK: - The group + + /// A group with real subitems and no view is drawn by AppKit, so it dims a button, answers the + /// display mode and collapses into one overflow entry when the window narrows. + @Test("Each button is a named AppKit glyph routed to the toolbar") + func subitemsAreDrawnByAppKit() throws { + let owner = Self.owner() + let group = try Self.group(from: owner) + + #expect(group.label == String(localized: "Objects")) + #expect(group.controlRepresentation == .automatic) + #expect(group.visibilityPriority == .high) + for item in group.subitems { + let name = item.itemIdentifier.rawValue + #expect(item.view == nil, "\(name) must not be view-backed") + #expect(!item.label.isEmpty, "\(name) needs a label") + #expect(item.image != nil, "\(name) names no symbol that exists") + #expect(item.target === owner, "\(name) must route through the toolbar") + #expect(item.action != nil, "\(name) has no action") + } + } + + @Test("Query advertises its shortcut, and every button its name") + func queryAdvertisesItsShortcut() throws { + let owner = Self.owner() + let query = try Self.subitem(MainWindowToolbar.objectQuery, of: owner) + let tables = try Self.subitem(MainWindowToolbar.objectTables, of: owner) + + #expect(query.toolTip == AppSettingsManager.shared.keyboard.shortcutHint(String(localized: "Query"), for: .newTab)) + #expect(query.toolTip != String(localized: "Query"), "The hint adds the key that runs the command") + #expect(tables.toolTip == String(localized: "Tables")) + } + + /// AppKit validates an overflowed button as a menu item, so each entry has to resolve back to + /// its own button's rule, or a disconnected window's entries stay live and do nothing. + @Test("Each overflow entry validates as its own button") + func overflowEntriesValidateAsTheirButtons() throws { + let owner = Self.owner() + for item in try Self.group(from: owner).subitems { + let entry = try #require(item.menuFormRepresentation) + #expect(owner.itemIdentifier(forMenuFormAction: item.action) == item.itemIdentifier) + #expect(!owner.validateMenuItem(entry), "\(item.itemIdentifier.rawValue) is live with no session") + } + } + + // MARK: - Routing + + @Test("Tables, Views and Functions open the browsed container's objects on their kind", arguments: [ + (MainWindowToolbar.objectTables.rawValue, SidebarObjectKind.table), + (MainWindowToolbar.objectViews.rawValue, .view), + (MainWindowToolbar.objectFunctions.rawValue, .function), + ]) + func listingButtonsOpenTheirKind(identifier: String, kind: SidebarObjectKind) throws { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .mysql)) + let owner = Self.owner() + owner.repoint(to: fixture.coordinator) + + try Self.press(NSToolbarItem.Identifier(identifier), on: owner) + + let tab = try #require(fixture.tabManager.selectedTab) + #expect(tab.tabType == .tableListing) + #expect((tab.display.listingKind ?? .table) == kind) + #expect(!tab.isPreview, "A click on a button keeps the tab") + #expect(tab.tableContext.databaseName == fixture.coordinator.browseDatabaseName) + } + + @Test("A second kind retargets the Objects tab already open") + func aSecondKindRetargetsTheOpenTab() throws { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .mysql)) + let owner = Self.owner() + owner.repoint(to: fixture.coordinator) + + try Self.press(MainWindowToolbar.objectTables, on: owner) + try Self.press(MainWindowToolbar.objectViews, on: owner) + + let listings = fixture.tabManager.tabs.filter { $0.tabType == .tableListing } + #expect(listings.count == 1) + #expect(listings.first?.display.listingKind == .view) + } + + @Test("Query opens a query tab, and Backup asks for the backup sheet") + func queryAndBackupReachTheirCommands() throws { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .postgresql)) + let actions = Self.makeActions(for: fixture) + let owner = Self.owner() + owner.repoint(to: fixture.coordinator) + + try Self.press(MainWindowToolbar.objectQuery, on: owner) + #expect(fixture.tabManager.selectedTab?.tabType == .query) + + try Self.press(MainWindowToolbar.objectBackup, on: owner) + if case .backupDatabase? = fixture.coordinator.activeSheet {} else { + Issue.record("Backup did not ask for the backup sheet") + } + withExtendedLifetime(actions) {} + } + + @Test("Users opens Users & Roles") + func usersReachesItsCommand() throws { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .postgresql)) + let actions = Self.makeActions(for: fixture) + let owner = Self.owner() + owner.repoint(to: fixture.coordinator) + + try Self.press(MainWindowToolbar.objectUsers, on: owner) + + #expect(fixture.tabManager.selectedTab?.tabType == .usersRoles) + withExtendedLifetime(actions) {} + } + + @Test("A button pressed with no connection behind the toolbar does nothing") + func buttonsWithNoConnectionDoNothing() throws { + let owner = Self.owner() + for identifier in MainWindowToolbar.objectKindItemIdentifiers { + try Self.press(identifier, on: owner) + } + #expect(owner.coordinator == nil) + } +} diff --git a/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift b/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift index 084aab333c..43c52d13e7 100644 --- a/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift +++ b/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift @@ -83,6 +83,49 @@ struct MainWindowToolbarIdentifierTests { } } + /// The Objects group is never in the default set, so leaving the setting off changes nobody's + /// saved arrangement, and the delegate's nil answer is what prunes the group once it goes off. + @Test("The delegate builds the Objects group only while its setting is on") + func delegateBuildsTheGroupOnlyWhileTheSettingIsOn() throws { + let owner = MainWindowToolbar() + let vend = { + owner.toolbar( + owner.managedToolbar, + itemForItemIdentifier: MainWindowToolbar.objectKindsGroup, + willBeInsertedIntoToolbar: true + ) + } + owner.objectKindsEnabled = { false } + let defaultsWhileOff = owner.toolbarDefaultItemIdentifiers(owner.managedToolbar) + #expect(vend() == nil) + #expect(!owner.toolbarAllowedItemIdentifiers(owner.managedToolbar).contains(MainWindowToolbar.objectKindsGroup)) + + owner.objectKindsEnabled = { true } + let first = try #require(vend() as? NSToolbarItemGroup) + let second = try #require(vend()) + #expect(first.subitems.map { $0.itemIdentifier } == MainWindowToolbar.objectKindItemIdentifiers) + #expect(first !== second, "A fresh group on every vend, like every other item") + #expect(owner.toolbarAllowedItemIdentifiers(owner.managedToolbar).contains(MainWindowToolbar.objectKindsGroup)) + #expect(owner.toolbarDefaultItemIdentifiers(owner.managedToolbar) == defaultsWhileOff) + #expect(!defaultsWhileOff.contains(MainWindowToolbar.objectKindsGroup)) + #expect(MainWindowToolbar.toolbarIdentifier == "com.TablePro.main.toolbar.v4") + } + + /// A user can have New Tab and the Objects group in one toolbar, and AppKit throws on a second + /// item with an identifier already there. + @Test("The Objects identifiers collide with nothing else the toolbar offers") + func objectKindIdentifiersAreTheirOwn() { + let own = [MainWindowToolbar.objectKindsGroup] + MainWindowToolbar.objectKindItemIdentifiers + let others = Set( + MainWindowToolbar.allowedItemIdentifiers + MainWindowToolbar.debugItemIdentifiers + + [MainWindowToolbar.navigateBack, MainWindowToolbar.navigateForward] + ) + + expectNoDuplicates(in: own, list: "Objects") + #expect(Set(own).isDisjoint(with: others)) + #expect(!own.contains { $0.rawValue.hasSuffix(".dashboard") || $0.rawValue.hasSuffix(".assistant") }) + } + private func expectNoDuplicates(in identifiers: [NSToolbarItem.Identifier], list: String) { let spaces: Set = [.space, .flexibleSpace] var seen: Set = [] From d435e1aeb6ed4153736e621eba988a13818a2e50 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:22:16 +0700 Subject: [PATCH 055/123] feat(toolbar): read what the connection supports for the object buttons Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Context.swift | 8 +++- .../ObjectKindsToolbarTests.swift | 38 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift index cfda0d7407..724c962a51 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift @@ -42,6 +42,8 @@ internal extension MainWindowToolbar { let host = self.host let state = coordinator?.toolbarState let debugger = (host?.contentMode ?? .browse) == .browse ? coordinator?.frontRoutineDebugController : nil + // Only the Objects group reads these, and the listing is a plugin call, so a pass without the group skips them. + let showsObjects = objectKindsEnabled() return ToolbarContext( key: currentVisibilityKey(), pane: host?.currentPane ?? .empty, @@ -59,7 +61,11 @@ internal extension MainWindowToolbar { Set(PluginDebugCommand.hostCommands.filter { controller.canPerform($0) }) } ?? [], canStopDebugging: debugger?.canStop ?? false, - isPresentingSheet: coordinator?.isPresentingSheet ?? false + isPresentingSheet: coordinator?.isPresentingSheet ?? false, + canListObjects: showsObjects && coordinator?.allTablesListing() != nil, + supportsRoutines: showsObjects && databaseType?.supportsRoutines == true, + supportsUserManagement: showsObjects && coordinator?.commandActions?.supportsUserManagement == true, + supportsBackup: showsObjects && coordinator?.commandActions?.supportsBackup == true ) } } diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index bb68437fc0..6790cdba97 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -169,6 +169,44 @@ struct ObjectKindsToolbarTests { withExtendedLifetime(actions) {} } + // MARK: - What the connection supports + + /// The context a toolbar pointed at a connection of this engine answers from. No driver is + /// installed, so the engine's curated capabilities are what the context can see. + private static func context(for type: DatabaseType, objectsOn: Bool) -> ToolbarContext { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: type)) + let actions = makeActions(for: fixture) + let owner = owner(objectsOn: objectsOn) + owner.repoint(to: fixture.coordinator) + let context = owner.currentContext() + withExtendedLifetime(actions) {} + return context + } + + @Test("While the group is on, the context reads what the engine supports") + func contextReadsTheEngineWhileTheGroupIsOn() { + let postgres = Self.context(for: .postgresql, objectsOn: true) + #expect(postgres.supportsRoutines) + #expect(postgres.supportsBackup) + #expect(!postgres.canListObjects, "With no driver the engine builds no listing") + #expect(!postgres.supportsUserManagement, "With no driver there is no capability to read") + + #expect(Self.context(for: .mongodb, objectsOn: true).canListObjects, "MongoDB lists through its own command") + #expect(!Self.context(for: .sqlite, objectsOn: true).supportsRoutines) + } + + /// Nothing but the group reads these, and the listing is a plugin call on every validation pass. + @Test("While the group is off, the context asks the connection nothing for it") + func contextAsksNothingWhileTheGroupIsOff() { + for type in [DatabaseType.postgresql, .mongodb] { + let context = Self.context(for: type, objectsOn: false) + #expect(!context.canListObjects, "\(type.rawValue)") + #expect(!context.supportsRoutines, "\(type.rawValue)") + #expect(!context.supportsUserManagement, "\(type.rawValue)") + #expect(!context.supportsBackup, "\(type.rawValue)") + } + } + @Test("A button pressed with no connection behind the toolbar does nothing") func buttonsWithNoConnectionDoNothing() throws { let owner = Self.owner() From 24b01edeedd4aa092ecbdf6ef3d6c08b24eabd01 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 01:34:12 +0700 Subject: [PATCH 056/123] feat(toolbar): insert the Objects group once when the setting turns on Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 1 + .../MainSplitViewController.swift | 1 + .../Infrastructure/MainWindowToolbar.swift | 51 +++++ .../Core/Storage/AppSettingsManager.swift | 3 + .../Views/Settings/GeneralSettingsView.swift | 3 + .../ObjectKindsToolbarTests.swift | 191 ++++++++++++++++++ 6 files changed, 250 insertions(+) diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index 2076c9aa51..61eb7373c5 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -174,6 +174,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Module on/off (Settings > Extensions) | UserDefaults, device-local, never synced | `AppModuleSettings` | | Routine debugger start options, per connection and field | UserDefaults, device-local | `RoutineDebugOptionStore` | | Whether the toolbar arrangement already carries the debug items | UserDefaults, device-local | `MainWindowToolbar` | +| Whether the toolbar arrangement already carries the Objects group | UserDefaults, device-local | `MainWindowToolbar` | | Trusted external links (loopback only) | UserDefaults | `ExternalConnectionTrustStore` | | Reopen the last session once after Relaunch to Update | UserDefaults, device-local, never synced, cleared by the next launch | `AppRelauncher` | | Highest plugin manifest `serial` accepted, so an older signed manifest is refused | UserDefaults, device-local, never synced | `RegistryManifestVerifier` through `RegistryClient` | diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index ce4e7a5cbc..d8e4a9054e 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -525,6 +525,7 @@ internal final class MainSplitViewController: NSSplitViewController { guard window.toolbar !== owner.managedToolbar else { return } window.toolbar = owner.managedToolbar owner.reconcileDebugItems() + owner.reconcileObjectKindsGroup() /// The item set every window starts from is the full one, because `isHidden` is never /// persisted, so the context is applied the moment the items exist rather than on the first /// change to it. Measured on macOS 27, that moment is this assignment: `NSToolbar.items` is diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index be1b569eef..c569e203da 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -96,6 +96,8 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { AppSettingsManager.shared.general.showsObjectToolbar } + internal var objectKindsRecord = ToolbarObjectKindsRecord() + /// `NSMenu.delegate` is weak, and the safe-mode control's menu is built here rather than by the /// menu bar, so this toolbar is what keeps its delegate alive. internal let safeModeMenuDelegate = SafeModeMenuDelegate() @@ -562,6 +564,16 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } } + // Pushed by the General setting's own write, so no toolbar listens for it while it stays off. + internal static func applyObjectToolbarSettingChange() { + for window in NSApp.windows { + guard let owner = window.toolbar?.delegate as? MainWindowToolbar else { continue } + owner.reconcileObjectKindsGroup() + // A group inserted now takes its enabled state at once rather than on the next window update. + owner.managedToolbar.validateVisibleItems() + } + } + // Run when the module changes and when the toolbar reaches a window, after it restored its saved arrangement: a // change made while no connection window was open would otherwise never reach the arrangement. Inserted or removed // in place, because reassigning the toolbar rebuilds the whole titlebar. @@ -585,6 +597,26 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } } } + + // The debug items' rule for the Objects group: written once per change of the setting, so a group the user took out + // stays out. It goes first in the content area, after the sidebar's strip, or first of all without that divider. + internal func reconcileObjectKindsGroup() { + guard windowController?.view.window != nil || isInWindow() else { return } + let wanted = objectKindsEnabled() + guard objectKindsRecord.isApplied != wanted else { return } + objectKindsRecord.record(wanted) + if wanted { + // AppKit throws on a second item with an identifier the toolbar already holds. + guard !managedToolbar.items.contains(where: { $0.itemIdentifier == Self.objectKindsGroup }) else { return } + let separator = managedToolbar.items.firstIndex { $0.itemIdentifier == .sidebarTrackingSeparator } + managedToolbar.insertItem(withItemIdentifier: Self.objectKindsGroup, at: separator.map { $0 + 1 } ?? 0) + } else { + for index in managedToolbar.items.indices.reversed() + where managedToolbar.items[index].itemIdentifier == Self.objectKindsGroup { + managedToolbar.removeItem(at: index) + } + } + } } // The module state last written into the shared arrangement. Toolbars sharing an identifier copy each other's edits, so @@ -609,3 +641,22 @@ internal struct ToolbarDebugItemsRecord { defaults.set(applied, forKey: Self.key) } } + +// The General setting last written into the shared arrangement, kept for the same reasons as the debug items' record. +internal struct ToolbarObjectKindsRecord { + static let key = "com.TablePro.main.toolbar.v4.objectKinds" + + let defaults: UserDefaults + + init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { + self.defaults = defaults + } + + var isApplied: Bool { + defaults.bool(forKey: Self.key) + } + + func record(_ applied: Bool) { + defaults.set(applied, forKey: Self.key) + } +} diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index d02610e76b..812dbcf293 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -19,6 +19,9 @@ final class AppSettingsManager: ObservableObject { if oldValue.connectionHealthCheck != general.connectionHealthCheck { appEvents.connectionHealthCheckChanged.send(()) } + if oldValue.showsObjectToolbar != general.showsObjectToolbar { + MainWindowToolbar.applyObjectToolbarSettingChange() + } syncTracker.markDirty(.settings, id: AppSettingsCategory.general) } } diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index f556dc6907..1fac2c624f 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -73,6 +73,9 @@ struct GeneralSettingsView: View { Toggle("Show objects when a database, schema or group is selected", isOn: $settings.showsObjectsOnSelection) .help("Clicking a database, schema or object group in the sidebar lists its objects in the main area. Show Objects in the row's menu lists them either way.") + Toggle("Show object buttons in the toolbar", isOn: $settings.showsObjectToolbar) + .help("Adds Tables, Views, Functions, Users, Query and Backup buttons to the connection window's toolbar. Customize Toolbar can move or remove them.") + 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.") diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index 6790cdba97..3a01ea9e5c 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -215,4 +215,195 @@ struct ObjectKindsToolbarTests { } #expect(owner.coordinator == nil) } + + // MARK: - Insert and remove + + /// A restored arrangement: the app's own items, without spaces, on a private identifier that + /// never autosaves. Built with the group allowed, so `extra` can hold it, then switched to the + /// setting the case names. AppKit builds the sidebar tracking separator only over a split view + /// in a window, so this arrangement has none; `separatorPlacesTheGroupInAWindow` covers it. + private static func restoredToolbar( + including extra: [NSToolbarItem.Identifier] = [], + settingOn: Bool, + record: ToolbarObjectKindsRecord + ) -> (owner: MainWindowToolbar, toolbar: NSToolbar) { + let owner = owner(objectsOn: true) + let toolbar = owner.managedToolbar + owner.objectKindsRecord = record + owner.isInWindow = { true } + let placed = [NSToolbarItem.Identifier.toggleSidebar] + extra + + [MainWindowToolbar.connection, MainWindowToolbar.refresh, MainWindowToolbar.actions] + for identifier in placed { + toolbar.insertItem(withItemIdentifier: identifier, at: toolbar.items.count) + } + owner.objectKindsEnabled = { settingOn } + return (owner, toolbar) + } + + private static func identifiers(of toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + toolbar.items.map { $0.itemIdentifier } + } + + private static func groupCount(in toolbar: NSToolbar) -> Int { + identifiers(of: toolbar).filter { $0 == MainWindowToolbar.objectKindsGroup }.count + } + + @Test("Turning the setting on puts the group in once") + func turningOnInsertsTheGroupOnce() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + #expect(!record.isApplied) + let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) + + owner.reconcileObjectKindsGroup() + + #expect(Self.groupCount(in: toolbar) == 1) + #expect(ToolbarObjectKindsRecord(defaults: storage.defaults).isApplied) + + let (laterOwner, laterToolbar) = Self.restoredToolbar(settingOn: true, record: record) + laterOwner.reconcileObjectKindsGroup() + #expect(Self.groupCount(in: laterToolbar) == 0, "The change was already written into the arrangement") + } + + @Test("Turning the setting off takes the group out") + func turningOffRemovesTheGroup() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + record.record(true) + let (owner, toolbar) = Self.restoredToolbar( + including: [MainWindowToolbar.objectKindsGroup], + settingOn: false, + record: record + ) + #expect(Self.groupCount(in: toolbar) == 1) + + owner.reconcileObjectKindsGroup() + + #expect(Self.groupCount(in: toolbar) == 0) + #expect(!record.isApplied) + } + + @Test("A group the user took out with Customize Toolbar stays out") + func aRemovedGroupStaysRemoved() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + record.record(true) + let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) + + owner.reconcileObjectKindsGroup() + + #expect(Self.groupCount(in: toolbar) == 0) + #expect(record.isApplied) + } + + @Test("With the setting off an arrangement is left exactly as it was") + func settingOffLeavesTheArrangementAlone() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + let (owner, toolbar) = Self.restoredToolbar(settingOn: false, record: record) + let before = Self.identifiers(of: toolbar) + + owner.reconcileObjectKindsGroup() + + #expect(Self.identifiers(of: toolbar) == before) + #expect(!record.isApplied) + #expect(storage.defaults.object(forKey: ToolbarObjectKindsRecord.key) == nil, "Nothing is written while off") + } + + /// AppKit throws when a second item with an identifier already in the toolbar is added. + @Test("A group already in the arrangement is not added a second time") + func presentGroupIsNotInsertedAgain() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + let (owner, toolbar) = Self.restoredToolbar( + including: [MainWindowToolbar.objectKindsGroup], + settingOn: true, + record: record + ) + #expect(Self.groupCount(in: toolbar) == 1) + + owner.reconcileObjectKindsGroup() + + #expect(Self.groupCount(in: toolbar) == 1) + #expect(record.isApplied) + } + + /// The connection window's own toolbar, whose split view gives it the sidebar's divider. + @Test("In a connection window the group starts the content area, right after the sidebar's strip") + func separatorPlacesTheGroupInAWindow() throws { + let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_512, height: 861)) + defer { fixture.tearDown() } + let storage = try EphemeralDefaults() + let owner = fixture.toolbarOwner + owner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) + owner.objectKindsEnabled = { true } + + owner.reconcileObjectKindsGroup() + + let identifiers = Self.identifiers(of: owner.managedToolbar) + let separator = try #require(identifiers.firstIndex(of: .sidebarTrackingSeparator)) + #expect(identifiers.dropFirst(separator + 1).first == MainWindowToolbar.objectKindsGroup) + #expect(Self.groupCount(in: owner.managedToolbar) == 1) + } + + @Test("Without the sidebar tracking separator the group goes in at the leading edge") + func insertsAtTheLeadingEdgeWithoutTheSeparator() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) + + owner.reconcileObjectKindsGroup() + + #expect(toolbar.items.first?.itemIdentifier == MainWindowToolbar.objectKindsGroup) + #expect(Self.groupCount(in: toolbar) == 1) + } + + /// A change made while no connection window is open is left for the first window that opens, + /// which restores its arrangement before it reconciles. + @Test("A toolbar outside a window leaves the change for the next one") + func noWindowLeavesTheChangeForTheNextOne() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) + owner.isInWindow = { false } + + owner.reconcileObjectKindsGroup() + #expect(Self.groupCount(in: toolbar) == 0) + #expect(!record.isApplied) + + owner.isInWindow = { true } + owner.reconcileObjectKindsGroup() + #expect(Self.groupCount(in: toolbar) == 1) + #expect(record.isApplied) + } +} + +extension GlobalStateSuites { + /// The setting itself, flipped the way Settings flips it, reaching a connection window that is + /// already open. + @MainActor + struct ObjectKindsSettingTests { + @Test( + "The General setting adds the group to an open window and takes it away", + .appSettings { $0.general.showsObjectToolbar = false } + ) + func settingReachesAnOpenWindow() throws { + let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_512, height: 861)) + defer { fixture.tearDown() } + let storage = try EphemeralDefaults() + fixture.toolbarOwner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) + let toolbar = try #require(fixture.window.toolbar) + let hasGroup = { toolbar.items.contains { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } } + #expect(!hasGroup()) + + AppSettingsManager.shared.general.showsObjectToolbar = true + #expect(hasGroup(), "Turning the setting on reaches the open window") + let identifiers = toolbar.items.map { $0.itemIdentifier } + let separator = try #require(identifiers.firstIndex(of: .sidebarTrackingSeparator)) + #expect(identifiers.dropFirst(separator + 1).first == MainWindowToolbar.objectKindsGroup) + + AppSettingsManager.shared.general.showsObjectToolbar = false + #expect(!hasGroup(), "Turning it off takes the group away") + } + } } From 6698982eaf5aef4c3221c892f3e2e1f0b87ba6a1 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:02:30 +0700 Subject: [PATCH 057/123] feat(toolbar): add the object button strings to the catalog Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Resources/Localizable.xcstrings | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index e106cf5156..3851f57c1a 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -21160,6 +21160,9 @@ } } } + }, + "Adds Tables, Views, Functions, Users, Query and Backup buttons to the connection window's toolbar. Customize Toolbar can move or remove them." : { + }, "Adjust Limit" : { "localizations" : { @@ -30795,6 +30798,9 @@ } } } + }, + "Backup" : { + }, "Backup Database" : { "localizations" : { @@ -166322,6 +166328,9 @@ } } } + }, + "Show object buttons in the toolbar" : { + }, "Show object comments" : { "localizations" : { @@ -211460,6 +211469,9 @@ } } } + }, + "Users" : { + }, "Users & Roles" : { "localizations" : { From 554bb2f289cd521295531b0c890df470431eb76e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:34:04 +0700 Subject: [PATCH 058/123] fix(toolbar): enable Views and Functions when the browsed container holds them Views and Functions open the Objects tab on the sidebar's own lists, not the table listing statement. Gating Views on the listing dimmed it on engines with no listing (Trino, Snowflake, Spanner, Dameng, Cassandra) and lit it on Redis, which has no views. Both buttons now ask ObjectListingKinds which kinds the browsed container offers, the rule the Objects tab's kind picker and the sidebar's groups follow. Tables still needs the listing. The context fields become canListTables, offersViews and offersFunctions, and the resolver and parity tests that pinned Tables and Views dimming together are updated for the split. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Context.swift | 6 +- .../Toolbar/ToolbarContextResolver.swift | 9 +- apple/TablePro/Models/UI/ToolbarContext.swift | 28 ++-- .../MainContentCoordinator+Navigation.swift | 28 +++- .../MenuContentModeParityTests.swift | 5 +- .../ObjectKindsToolbarTests.swift | 131 +++++++++++++++++- .../ToolbarContextResolverTests.swift | 25 ++-- 7 files changed, 195 insertions(+), 37 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift index 724c962a51..8411a70b47 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift @@ -44,6 +44,7 @@ internal extension MainWindowToolbar { let debugger = (host?.contentMode ?? .browse) == .browse ? coordinator?.frontRoutineDebugController : nil // Only the Objects group reads these, and the listing is a plugin call, so a pass without the group skips them. let showsObjects = objectKindsEnabled() + let offered = showsObjects ? coordinator?.browsedObjectKinds() ?? [] : [] return ToolbarContext( key: currentVisibilityKey(), pane: host?.currentPane ?? .empty, @@ -62,8 +63,9 @@ internal extension MainWindowToolbar { } ?? [], canStopDebugging: debugger?.canStop ?? false, isPresentingSheet: coordinator?.isPresentingSheet ?? false, - canListObjects: showsObjects && coordinator?.allTablesListing() != nil, - supportsRoutines: showsObjects && databaseType?.supportsRoutines == true, + canListTables: showsObjects && coordinator?.allTablesListing() != nil, + offersViews: offered.contains(.view), + offersFunctions: offered.contains(.function), supportsUserManagement: showsObjects && coordinator?.commandActions?.supportsUserManagement == true, supportsBackup: showsObjects && coordinator?.commandActions?.supportsBackup == true ) diff --git a/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift b/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift index b2806331f1..68d5bdf2fd 100644 --- a/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift @@ -163,10 +163,13 @@ internal enum ToolbarContextResolver { return context.debugCommands.contains(.stepOut) case MainWindowToolbar.debugStop: return context.canStopDebugging - case MainWindowToolbar.objectTables, MainWindowToolbar.objectViews: - return context.isConnected && context.canListObjects + case MainWindowToolbar.objectTables: + return context.isConnected && context.canListTables + // The sidebar's own lists hold these, so they need no listing statement, only objects to list. + case MainWindowToolbar.objectViews: + return context.isConnected && context.offersViews case MainWindowToolbar.objectFunctions: - return context.isConnected && context.supportsRoutines + return context.isConnected && context.offersFunctions case MainWindowToolbar.objectUsers: return context.isConnected && context.supportsUserManagement case MainWindowToolbar.objectQuery: diff --git a/apple/TablePro/Models/UI/ToolbarContext.swift b/apple/TablePro/Models/UI/ToolbarContext.swift index 166292576c..3133a911df 100644 --- a/apple/TablePro/Models/UI/ToolbarContext.swift +++ b/apple/TablePro/Models/UI/ToolbarContext.swift @@ -47,9 +47,11 @@ internal struct ToolbarContext: Equatable { internal let canStopDebugging: Bool internal let isPresentingSheet: Bool - // What the connection supports, for the Objects group's buttons. Enablement only, never visibility. - internal let canListObjects: Bool - internal let supportsRoutines: Bool + // What the connection supports and the browsed container offers, for the Objects group's buttons. + // Enablement only, never visibility. + internal let canListTables: Bool + internal let offersViews: Bool + internal let offersFunctions: Bool internal let supportsUserManagement: Bool internal let supportsBackup: Bool @@ -107,8 +109,9 @@ internal struct ToolbarContext: Equatable { debugCommands: Set = [], canStopDebugging: Bool = false, isPresentingSheet: Bool = false, - canListObjects: Bool = false, - supportsRoutines: Bool = false, + canListTables: Bool = false, + offersViews: Bool = false, + offersFunctions: Bool = false, supportsUserManagement: Bool = false, supportsBackup: Bool = false ) { @@ -136,8 +139,9 @@ internal struct ToolbarContext: Equatable { self.debugCommands = debugCommands self.canStopDebugging = canStopDebugging self.isPresentingSheet = isPresentingSheet - self.canListObjects = canListObjects - self.supportsRoutines = supportsRoutines + self.canListTables = canListTables + self.offersViews = offersViews + self.offersFunctions = offersFunctions self.supportsUserManagement = supportsUserManagement self.supportsBackup = supportsBackup } @@ -159,8 +163,9 @@ internal struct ToolbarContext: Equatable { debugCommands: Set = [], canStopDebugging: Bool = false, isPresentingSheet: Bool = false, - canListObjects: Bool = false, - supportsRoutines: Bool = false, + canListTables: Bool = false, + offersViews: Bool = false, + offersFunctions: Bool = false, supportsUserManagement: Bool = false, supportsBackup: Bool = false ) { @@ -189,8 +194,9 @@ internal struct ToolbarContext: Equatable { debugCommands: debugCommands, canStopDebugging: canStopDebugging, isPresentingSheet: isPresentingSheet, - canListObjects: canListObjects, - supportsRoutines: supportsRoutines, + canListTables: canListTables, + offersViews: offersViews, + offersFunctions: offersFunctions, supportsUserManagement: supportsUserManagement, supportsBackup: supportsBackup ) diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift index c7a50ada63..8b504d8356 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift @@ -439,13 +439,37 @@ extension MainContentCoordinator { /// The flat list's sections are the browsed container's, so their Show Objects lists that one. func showBrowsedObjects(_ kind: SidebarObjectKind) { - let schemaName = EngineNamespaceSlot(databaseType: connection.type) == .schema ? browseSchemaName : nil + let scope = browsedObjectsScope showObjects( - DatabaseTreeObjectGroup(database: browseDatabaseName, schema: schemaName, kind: kind), + DatabaseTreeObjectGroup(database: scope.database, schema: scope.schema, kind: kind), asPreview: false ) } + /// The container `showBrowsedObjects` opens, which the toolbar's object buttons also read. + var browsedObjectsScope: DatabaseScope { + let schemaName = EngineNamespaceSlot(databaseType: connection.type) == .schema ? browseSchemaName : nil + return DatabaseScope(connectionId: connectionId, database: browseDatabaseName, schema: schemaName) + } + + /// The kinds an Objects tab on the browsed container offers, from the lists the sidebar holds for + /// it, so a toolbar button is live exactly where the sidebar has a group to show. + func browsedObjectKinds() -> [SidebarObjectKind] { + let scope = browsedObjectsScope + let tree = DatabaseTreeMetadataService.shared + let counts = ObjectListingKinds.itemCounts( + tables: tree.tables(connectionId: connectionId, database: scope.database, schema: scope.schema), + routines: tree.routines(connectionId: connectionId, database: scope.database, schema: scope.schema), + triggers: tree.triggers(connectionId: connectionId, database: scope.database, schema: scope.schema), + types: tree.userDefinedTypes(connectionId: connectionId, database: scope.database, schema: scope.schema) + ) + return ObjectListingKinds.available( + itemCounts: counts, + declared: connection.type.declaredObjectKinds, + current: .table + ) + } + /// The schema the sidebar lists, which a cross-database tab can leave the shared driver off. private var browseSchemaName: String? { DatabaseManager.shared.session(for: connectionId)?.browseSchema diff --git a/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift b/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift index febb7ae658..8165b4c927 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/MenuContentModeParityTests.swift @@ -306,8 +306,9 @@ struct MenuContentModeParityTests { isConnected: connected, hasSelectedWorkspace: true, isPresentingSheet: sheet, - canListObjects: true, - supportsRoutines: true, + canListTables: true, + offersViews: true, + offersFunctions: true, supportsUserManagement: true, supportsBackup: true ) diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index 3a01ea9e5c..f3d1a8e151 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -6,6 +6,7 @@ import AppKit import SwiftUI @testable import TablePro +import TableProPluginKit import Testing /// The optional Objects group: six buttons that reach each kind of object in one click. @@ -186,13 +187,15 @@ struct ObjectKindsToolbarTests { @Test("While the group is on, the context reads what the engine supports") func contextReadsTheEngineWhileTheGroupIsOn() { let postgres = Self.context(for: .postgresql, objectsOn: true) - #expect(postgres.supportsRoutines) #expect(postgres.supportsBackup) - #expect(!postgres.canListObjects, "With no driver the engine builds no listing") + #expect(!postgres.canListTables, "With no driver the engine builds no listing") #expect(!postgres.supportsUserManagement, "With no driver there is no capability to read") + #expect(!postgres.offersFunctions, "No routine list is loaded for the browsed schema") - #expect(Self.context(for: .mongodb, objectsOn: true).canListObjects, "MongoDB lists through its own command") - #expect(!Self.context(for: .sqlite, objectsOn: true).supportsRoutines) + let mongo = Self.context(for: .mongodb, objectsOn: true) + #expect(mongo.canListTables, "MongoDB lists through its own command") + #expect(!mongo.offersViews, "A table listing says nothing about views") + #expect(!Self.context(for: .sqlite, objectsOn: true).offersFunctions) } /// Nothing but the group reads these, and the listing is a plugin call on every validation pass. @@ -200,13 +203,129 @@ struct ObjectKindsToolbarTests { func contextAsksNothingWhileTheGroupIsOff() { for type in [DatabaseType.postgresql, .mongodb] { let context = Self.context(for: type, objectsOn: false) - #expect(!context.canListObjects, "\(type.rawValue)") - #expect(!context.supportsRoutines, "\(type.rawValue)") + #expect(!context.canListTables, "\(type.rawValue)") + #expect(!context.offersViews, "\(type.rawValue)") + #expect(!context.offersFunctions, "\(type.rawValue)") #expect(!context.supportsUserManagement, "\(type.rawValue)") #expect(!context.supportsBackup, "\(type.rawValue)") } } + // MARK: - What the browsed container offers + + /// An engine with no table listing that fetches routines and keeps every read on the session's + /// own driver, as PGlite does: the shape Trino and Snowflake take for these buttons. + private static func registerListlessEngine() -> DatabaseType { + let typeId = "ObjectKindsToolbarListless-\(UUID().uuidString)" + let defaults = PluginMetadataSnapshot.CapabilityFlags.defaults + var capabilities = PluginMetadataSnapshot.CapabilityFlags( + supportsSchemaSwitching: true, + supportsImport: defaults.supportsImport, + supportsExport: defaults.supportsExport, + supportsSSH: defaults.supportsSSH, + supportsSSL: defaults.supportsSSL, + supportsCascadeDrop: defaults.supportsCascadeDrop, + supportsForeignKeyDisable: defaults.supportsForeignKeyDisable, + supportsReadOnlyMode: defaults.supportsReadOnlyMode, + supportsQueryProgress: defaults.supportsQueryProgress, + requiresReconnectForDatabaseSwitch: defaults.requiresReconnectForDatabaseSwitch, + supportsDropDatabase: defaults.supportsDropDatabase + ) + capabilities.supportsRoutines = true + capabilities.supportsConnectionPooling = false + let snapshot = PluginMetadataSnapshot( + displayName: typeId, iconName: "cylinder", defaultPort: 1_234, + requiresAuthentication: true, supportsForeignKeys: true, supportsSchemaEditing: true, + isDownloadable: false, primaryUrlScheme: "objectkindslistless", parameterStyle: .questionMark, + navigationModel: .standard, explainVariants: [], pathFieldRole: .database, + supportsHealthMonitor: false, urlSchemes: ["objectkindslistless"], postConnectActions: [], + brandColorHex: "#000000", queryLanguageName: "SQL", editorLanguage: .sql, + connectionMode: .network, supportsDatabaseSwitching: true, + capabilities: capabilities, schema: .defaults, editor: .defaults, connection: .defaults + ) + PluginMetadataRegistry.shared.register(snapshot: snapshot, forTypeId: typeId) + return DatabaseType(rawValue: typeId) + } + + /// A live session browsing `shop.public`, whose lists the sidebar has already read. + private static func browsing( + tables: [TableInfo], + routines: [RoutineInfo], + on engine: DatabaseType + ) async -> DatabaseConnection { + let connection = TestFixtures.makeConnection(database: "shop", type: engine) + let driver = MockDatabaseDriver(connection: connection) + driver.schemaTablesToReturn = ["public": tables] + driver.schemaRoutinesToReturn = ["public": routines] + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + session.browseSchema = "public" + DatabaseManager.shared.injectSession(session, for: connection.id) + let tree = DatabaseTreeMetadataService.shared + await tree.loadTables(connectionId: connection.id, database: "shop", schema: "public") + await tree.loadRoutines(connectionId: connection.id, database: "shop", schema: "public") + return connection + } + + private static func leave(_ connection: DatabaseConnection) async { + await DatabaseTreeMetadataService.shared.handleDisconnect(connectionId: connection.id) + DatabaseManager.shared.removeSession(for: connection.id) + } + + private static func enabledButtons(browsing connection: DatabaseConnection) -> Set { + let fixture = CoordinatorFixture(connection: connection) + fixture.coordinator.toolbarState.connectionState = .connected + let owner = owner() + owner.repoint(to: fixture.coordinator) + let context = withExtendedLifetime(fixture) { owner.currentContext() } + return Set(MainWindowToolbar.objectKindItemIdentifiers.filter { identifier in + ToolbarContextResolver.isEnabled(identifier, context: context) + }) + } + + /// The sidebar offers Show Objects on a Views or Functions group from its own lists, so the + /// buttons do too, on an engine that builds no table listing. + @Test("Views and Functions open from the sidebar's lists on an engine with no table listing") + func viewsAndFunctionsFollowTheSidebarsLists() async { + let engine = Self.registerListlessEngine() + let connection = await Self.browsing( + tables: [ + TestFixtures.makeTableInfo(name: "orders", schema: "public"), + TestFixtures.makeTableInfo(name: "open_orders", type: .view, schema: "public"), + ], + routines: [RoutineInfo(name: "order_total", kind: .function, schema: "public")], + on: engine + ) + + let enabled = Self.enabledButtons(browsing: connection) + + #expect(enabled.contains(MainWindowToolbar.objectViews)) + #expect(enabled.contains(MainWindowToolbar.objectFunctions)) + #expect(!enabled.contains(MainWindowToolbar.objectTables), "Tables still need the engine's listing") + await Self.leave(connection) + PluginMetadataRegistry.shared.unregister(typeId: engine.rawValue) + } + + /// The Objects tab offers a kind only where the container holds some, so a button that opened + /// an empty list of a kind the sidebar never shows stays dim. + @Test("A container with no views or functions dims Views and Functions") + func emptyKindsDimTheirButtons() async { + let engine = Self.registerListlessEngine() + let connection = await Self.browsing( + tables: [TestFixtures.makeTableInfo(name: "orders", schema: "public")], + routines: [RoutineInfo(name: "archive_orders", kind: .procedure, schema: "public")], + on: engine + ) + + let enabled = Self.enabledButtons(browsing: connection) + + #expect(!enabled.contains(MainWindowToolbar.objectViews)) + #expect(!enabled.contains(MainWindowToolbar.objectFunctions), "A procedure is not a function") + #expect(enabled.contains(MainWindowToolbar.objectQuery)) + await Self.leave(connection) + PluginMetadataRegistry.shared.unregister(typeId: engine.rawValue) + } + @Test("A button pressed with no connection behind the toolbar does nothing") func buttonsWithNoConnectionDoNothing() throws { let owner = Self.owner() diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift index 32f866f1ee..f4159ae8f8 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift @@ -474,8 +474,9 @@ struct ToolbarContextResolverTests { private static func objectsContext( connected: Bool = true, contentMode: ConnectionWorkspaceContentMode = .browse, - canListObjects: Bool = true, - supportsRoutines: Bool = true, + canListTables: Bool = true, + offersViews: Bool = true, + offersFunctions: Bool = true, supportsUserManagement: Bool = true, supportsBackup: Bool = true, isPresentingSheet: Bool = false @@ -488,8 +489,9 @@ struct ToolbarContextResolverTests { hasSelectedWorkspace: true, supportsContainerSwitching: true, isPresentingSheet: isPresentingSheet, - canListObjects: canListObjects, - supportsRoutines: supportsRoutines, + canListTables: canListTables, + offersViews: offersViews, + offersFunctions: offersFunctions, supportsUserManagement: supportsUserManagement, supportsBackup: supportsBackup ) @@ -510,14 +512,14 @@ struct ToolbarContextResolverTests { ) } + /// Views and Functions come from the sidebar's own lists, so an engine with no table listing + /// still opens them, and one with a listing but no views does not light Views. @Test("Each object button dims for its own missing capability and no other") func objectButtonsFollowTheirCapability() { + #expect(Self.dimmedObjectButtons(Self.objectsContext(canListTables: false)) == [MainWindowToolbar.objectTables]) + #expect(Self.dimmedObjectButtons(Self.objectsContext(offersViews: false)) == [MainWindowToolbar.objectViews]) #expect( - Self.dimmedObjectButtons(Self.objectsContext(canListObjects: false)) - == [MainWindowToolbar.objectTables, MainWindowToolbar.objectViews] - ) - #expect( - Self.dimmedObjectButtons(Self.objectsContext(supportsRoutines: false)) == [MainWindowToolbar.objectFunctions] + Self.dimmedObjectButtons(Self.objectsContext(offersFunctions: false)) == [MainWindowToolbar.objectFunctions] ) #expect( Self.dimmedObjectButtons(Self.objectsContext(supportsUserManagement: false)) == [MainWindowToolbar.objectUsers] @@ -544,8 +546,9 @@ struct ToolbarContextResolverTests { func objectFactsStayOutOfTheVisibilityKey() { let capable = Self.objectsContext() let bare = Self.objectsContext( - canListObjects: false, - supportsRoutines: false, + canListTables: false, + offersViews: false, + offersFunctions: false, supportsUserManagement: false, supportsBackup: false ) From 11c606115817bc119635d83e5d8db029dfe8c177 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:43:34 +0700 Subject: [PATCH 059/123] fix(toolbar): read the object buttons' facts once per container and session Every window update runs a validation pass, keystrokes included, and each pass built the plugin's whole listing statement for a yes or no. The gate was the setting, so a group removed with Customize Toolbar kept paying. The facts are now read only while the group is in the window's toolbar, and kept until what they were read from moves: the browsed database and schema, the session's driver (a reconnect installs a new one), the command actions, and the container's table and routine lists, so a list the sidebar reads again still reaches Views and Functions. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Context.swift | 75 ++++++++++- .../Infrastructure/MainWindowToolbar.swift | 3 + .../ObjectKindsToolbarTests.swift | 124 ++++++++++++++++-- 3 files changed, 186 insertions(+), 16 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift index 8411a70b47..f3092c2ace 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift @@ -42,9 +42,7 @@ internal extension MainWindowToolbar { let host = self.host let state = coordinator?.toolbarState let debugger = (host?.contentMode ?? .browse) == .browse ? coordinator?.frontRoutineDebugController : nil - // Only the Objects group reads these, and the listing is a plugin call, so a pass without the group skips them. - let showsObjects = objectKindsEnabled() - let offered = showsObjects ? coordinator?.browsedObjectKinds() ?? [] : [] + let objects = objectKindFacts() return ToolbarContext( key: currentVisibilityKey(), pane: host?.currentPane ?? .empty, @@ -63,11 +61,76 @@ internal extension MainWindowToolbar { } ?? [], canStopDebugging: debugger?.canStop ?? false, isPresentingSheet: coordinator?.isPresentingSheet ?? false, - canListTables: showsObjects && coordinator?.allTablesListing() != nil, + canListTables: objects.canListTables, + offersViews: objects.offersViews, + offersFunctions: objects.offersFunctions, + supportsUserManagement: objects.supportsUserManagement, + supportsBackup: objects.supportsBackup + ) + } + + // Every window update runs a validation pass, keystrokes included, and the listing is a plugin call that builds + // the whole statement. So the facts are read only while the group is in this toolbar, where a button shows them, + // and then once per browsed container and session. + func objectKindFacts() -> ObjectKindFacts { + guard let coordinator, managedToolbar.items.contains(where: { $0.itemIdentifier == Self.objectKindsGroup }) + else { return ObjectKindFacts() } + let source = ObjectKindFactsSource(coordinator: coordinator) + if let cached = objectKindFactsCache, cached.source.matches(source) { + return cached.facts + } + let offered = coordinator.browsedObjectKinds() + let facts = ObjectKindFacts( + canListTables: coordinator.allTablesListing() != nil, offersViews: offered.contains(.view), offersFunctions: offered.contains(.function), - supportsUserManagement: showsObjects && coordinator?.commandActions?.supportsUserManagement == true, - supportsBackup: showsObjects && coordinator?.commandActions?.supportsBackup == true + supportsUserManagement: coordinator.commandActions?.supportsUserManagement == true, + supportsBackup: coordinator.commandActions?.supportsBackup == true ) + objectKindFactsCache = ObjectKindFactsCache(source: source, facts: facts) + return facts } } + +// What the Objects group's buttons ask of the connection and the browsed container. +internal struct ObjectKindFacts: Equatable { + var canListTables = false + var offersViews = false + var offersFunctions = false + var supportsUserManagement = false + var supportsBackup = false +} + +// What the facts were read from. A database or schema switch moves the scope, a reconnect installs a new driver, and a +// load or refresh of the container replaces its lists, so each of them reads the facts again. +internal struct ObjectKindFactsSource { + let scope: DatabaseScope + // Weak, so a driver a reconnect released cannot pass for a new one allocated at its address. + weak var driver: (any DatabaseDriver)? + // Users and Backup answer through the command actions, which a window gains once its content appears. + let hasCommandActions: Bool + // Only these two lists decide Views and Functions. A list nothing replaced compares by its storage, not by walking it. + let tables: MetadataLoadState<[TableInfo]> + let routines: MetadataLoadState<[RoutineInfo]> + + @MainActor + init(coordinator: MainContentCoordinator) { + let scope = coordinator.browsedObjectsScope + let tree = DatabaseTreeMetadataService.shared + self.scope = scope + driver = DatabaseManager.shared.driver(for: coordinator.connectionId) + hasCommandActions = coordinator.commandActions != nil + tables = tree.tablesLoadState(connectionId: scope.connectionId, database: scope.database, schema: scope.schema) + routines = tree.routinesLoadState(connectionId: scope.connectionId, database: scope.database, schema: scope.schema) + } + + func matches(_ other: ObjectKindFactsSource) -> Bool { + scope == other.scope && driver === other.driver && hasCommandActions == other.hasCommandActions + && tables == other.tables && routines == other.routines + } +} + +internal struct ObjectKindFactsCache { + let source: ObjectKindFactsSource + let facts: ObjectKindFacts +} diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index c569e203da..903ac477bb 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -98,6 +98,9 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal var objectKindsRecord = ToolbarObjectKindsRecord() + // The Objects group's facts and what they were read from, kept from one validation pass to the next. + internal var objectKindFactsCache: ObjectKindFactsCache? + /// `NSMenu.delegate` is weak, and the safe-mode control's menu is built here rather than by the /// menu bar, so this toolbar is what keeps its delegate alive. internal let safeModeMenuDelegate = SafeModeMenuDelegate() diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index f3d1a8e151..38c70b8957 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -172,37 +172,51 @@ struct ObjectKindsToolbarTests { // MARK: - What the connection supports + /// Where Settings puts the group: what the toolbar's own facts are read for. + private static func insertGroup(into owner: MainWindowToolbar) { + owner.managedToolbar.insertItem(withItemIdentifier: MainWindowToolbar.objectKindsGroup, at: 0) + } + /// The context a toolbar pointed at a connection of this engine answers from. No driver is /// installed, so the engine's curated capabilities are what the context can see. - private static func context(for type: DatabaseType, objectsOn: Bool) -> ToolbarContext { + private static func context( + for type: DatabaseType, + groupInToolbar: Bool = true, + settingOn: Bool = true + ) -> ToolbarContext { let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: type)) let actions = makeActions(for: fixture) - let owner = owner(objectsOn: objectsOn) + let owner = owner() + if groupInToolbar { + insertGroup(into: owner) + } + owner.objectKindsEnabled = { settingOn } owner.repoint(to: fixture.coordinator) let context = owner.currentContext() withExtendedLifetime(actions) {} return context } - @Test("While the group is on, the context reads what the engine supports") - func contextReadsTheEngineWhileTheGroupIsOn() { - let postgres = Self.context(for: .postgresql, objectsOn: true) + @Test("With the group in the toolbar, the context reads what the engine supports") + func contextReadsTheEngineWhileTheGroupIsShown() { + let postgres = Self.context(for: .postgresql) #expect(postgres.supportsBackup) #expect(!postgres.canListTables, "With no driver the engine builds no listing") #expect(!postgres.supportsUserManagement, "With no driver there is no capability to read") #expect(!postgres.offersFunctions, "No routine list is loaded for the browsed schema") - let mongo = Self.context(for: .mongodb, objectsOn: true) + let mongo = Self.context(for: .mongodb) #expect(mongo.canListTables, "MongoDB lists through its own command") #expect(!mongo.offersViews, "A table listing says nothing about views") - #expect(!Self.context(for: .sqlite, objectsOn: true).offersFunctions) + #expect(!Self.context(for: .sqlite).offersFunctions) } /// Nothing but the group reads these, and the listing is a plugin call on every validation pass. - @Test("While the group is off, the context asks the connection nothing for it") - func contextAsksNothingWhileTheGroupIsOff() { + /// The setting is not enough: a group taken out with Customize Toolbar has no button to validate. + @Test("Without the group in the toolbar, the context asks the connection nothing for it", arguments: [true, false]) + func contextAsksNothingWithoutTheGroup(settingOn: Bool) { for type in [DatabaseType.postgresql, .mongodb] { - let context = Self.context(for: type, objectsOn: false) + let context = Self.context(for: type, groupInToolbar: false, settingOn: settingOn) #expect(!context.canListTables, "\(type.rawValue)") #expect(!context.offersViews, "\(type.rawValue)") #expect(!context.offersFunctions, "\(type.rawValue)") @@ -211,6 +225,52 @@ struct ObjectKindsToolbarTests { } } + /// A validation pass runs on every window update, keystrokes included, and the listing is a + /// plugin call that builds the whole statement for a yes or no. + @Test("A pass with nothing changed builds no listing, and a switch or a reconnect builds one again") + func listingIsAskedOncePerContainerAndSession() { + let connection = TestFixtures.makeConnection(database: "shop", type: .postgresql) + let plugin = CountingListingDriver() + var session = ConnectionSession( + connection: connection, + driver: PluginDriverAdapter(connection: connection, pluginDriver: plugin) + ) + session.status = .connected + session.browseSchema = "public" + DatabaseManager.shared.injectSession(session, for: connection.id) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + let fixture = CoordinatorFixture(connection: connection) + let owner = Self.owner() + Self.insertGroup(into: owner) + owner.repoint(to: fixture.coordinator) + + #expect(owner.currentContext().canListTables) + let asked = plugin.listings + #expect(asked > 0) + _ = owner.currentContext() + _ = owner.currentContext() + #expect(plugin.listings == asked, "Nothing moved, so nothing is asked again") + + DatabaseManager.shared.updateSession(connection.id) { $0.browseSchema = "sales" } + _ = owner.currentContext() + _ = owner.currentContext() + #expect(plugin.listings == asked + 1, "A schema switch asks once") + + DatabaseManager.shared.updateSession(connection.id) { $0.browseDatabase = "archive" } + _ = owner.currentContext() + _ = owner.currentContext() + #expect(plugin.listings == asked + 2, "A database switch asks once") + + let reconnected = CountingListingDriver() + DatabaseManager.shared.updateSession(connection.id) { + $0.driver = PluginDriverAdapter(connection: connection, pluginDriver: reconnected) + } + _ = owner.currentContext() + _ = owner.currentContext() + #expect(reconnected.listings == 1, "A reconnect's driver is asked once") + withExtendedLifetime(fixture) {} + } + // MARK: - What the browsed container offers /// An engine with no table listing that fetches routines and keeps every read on the session's @@ -276,6 +336,7 @@ struct ObjectKindsToolbarTests { let fixture = CoordinatorFixture(connection: connection) fixture.coordinator.toolbarState.connectionState = .connected let owner = owner() + insertGroup(into: owner) owner.repoint(to: fixture.coordinator) let context = withExtendedLifetime(fixture) { owner.currentContext() } return Set(MainWindowToolbar.objectKindItemIdentifiers.filter { identifier in @@ -326,6 +387,37 @@ struct ObjectKindsToolbarTests { PluginMetadataRegistry.shared.unregister(typeId: engine.rawValue) } + /// The facts are kept between passes, so a list the sidebar reads again has to reach them. + @Test("A view the container's next read brings lights Views") + func aReloadedListReachesTheButtons() async throws { + let engine = Self.registerListlessEngine() + let connection = await Self.browsing( + tables: [TestFixtures.makeTableInfo(name: "orders", schema: "public")], + routines: [], + on: engine + ) + let fixture = CoordinatorFixture(connection: connection) + fixture.coordinator.toolbarState.connectionState = .connected + let owner = Self.owner() + Self.insertGroup(into: owner) + owner.repoint(to: fixture.coordinator) + #expect(!owner.currentContext().offersViews) + + let driver = try #require(DatabaseManager.shared.driver(for: connection.id) as? MockDatabaseDriver) + driver.schemaTablesToReturn = ["public": [ + TestFixtures.makeTableInfo(name: "orders", schema: "public"), + TestFixtures.makeTableInfo(name: "open_orders", type: .view, schema: "public"), + ]] + let tree = DatabaseTreeMetadataService.shared + tree.markListsStale(connectionId: connection.id) + await tree.loadTables(connectionId: connection.id, database: "shop", schema: "public") + + #expect(owner.currentContext().offersViews) + withExtendedLifetime(fixture) {} + await Self.leave(connection) + PluginMetadataRegistry.shared.unregister(typeId: engine.rawValue) + } + @Test("A button pressed with no connection behind the toolbar does nothing") func buttonsWithNoConnectionDoNothing() throws { let owner = Self.owner() @@ -526,3 +618,15 @@ extension GlobalStateSuites { } } } + +/// Counts the listing statements asked for, which is the plugin call a validation pass would repeat. +private final class CountingListingDriver: PluginDriverStub, @unchecked Sendable { + private(set) var listings = 0 + + func allTablesMetadataSQL(schema: String?) -> String? { + listings += 1 + return "LIST \(schema ?? "-")" + } + + func ping() async throws {} +} From 58d3debf3255c880b9f34d81e33a833f4ea6c53b Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 07:55:39 +0700 Subject: [PATCH 060/123] fix(toolbar): dim the Objects group's buttons as soon as the setting adds it The pass that ran right after inserting the group never reached it: AppKit places an inserted item at the next layout, and a validation pass only validates placed items. The new buttons stayed live in a window with no connection until something laid the window out. The window now lays out before that pass. settingReachesAnOpenWindow now checks that every button arrives dimmed in a window with no connection; it failed with and without the old pass. A new case drives the window toolbar's own validation pass and checks that it writes each subitem's isEnabled: all dim with the session down, and the resolver's answers with it up. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Infrastructure/MainWindowToolbar.swift | 4 +- .../ObjectKindsToolbarTests.swift | 49 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index 903ac477bb..f9f9da5ef8 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -572,7 +572,9 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { for window in NSApp.windows { guard let owner = window.toolbar?.delegate as? MainWindowToolbar else { continue } owner.reconcileObjectKindsGroup() - // A group inserted now takes its enabled state at once rather than on the next window update. + // A group inserted now takes its enabled state at once rather than on the next window update. AppKit places + // an inserted item at the next layout and a pass validates only placed items, so the window lays out first. + window.layoutIfNeeded() owner.managedToolbar.validateVisibleItems() } } diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index 38c70b8957..57bea00009 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -557,6 +557,47 @@ struct ObjectKindsToolbarTests { #expect(Self.groupCount(in: owner.managedToolbar) == 1) } + /// The resolver answering is not enough: AppKit has to ask it for each subitem and write the + /// answer. This is the pass a window update runs, through the window's own toolbar. + @Test("A validation pass writes each button's enabled state") + func aValidationPassWritesEachButton() throws { + let fixture = try OffscreenConnectionWindow( + size: CGSize(width: 1_512, height: 861), + connectedTo: TestFixtures.makeConnection(name: "Objects validation", type: .sqlite) + ) + defer { fixture.tearDown() } + let storage = try EphemeralDefaults() + let owner = fixture.toolbarOwner + owner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) + owner.objectKindsEnabled = { true } + owner.reconcileObjectKindsGroup() + // AppKit places an inserted item at the next layout, and validates only what it has placed. + fixture.window.layoutIfNeeded() + let toolbar = try #require(fixture.window.toolbar) + let group = try #require( + toolbar.items.first { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } as? NSToolbarItemGroup + ) + let drawn = (toolbar.visibleItems ?? []).map { $0.itemIdentifier } + #expect(drawn.contains(MainWindowToolbar.objectKindsGroup), "The group went to the overflow menu") + let state = try #require(owner.coordinator?.toolbarState) + let enabled = { Set(group.subitems.filter { $0.isEnabled }.map { $0.itemIdentifier }) } + + state.connectionState = .disconnected + toolbar.validateVisibleItems() + #expect(enabled().isEmpty, "A dropped session dims every button") + + // SQLite's test session has no listing and no views or functions loaded, so the pass writes both answers. + state.connectionState = .connected + toolbar.validateVisibleItems() + let answered = owner.currentContext() + let expected = Set(MainWindowToolbar.objectKindItemIdentifiers.filter { identifier in + ToolbarContextResolver.isEnabled(identifier, context: answered) + }) + #expect(enabled() == expected) + #expect(enabled().contains(MainWindowToolbar.objectQuery)) + #expect(!enabled().contains(MainWindowToolbar.objectTables)) + } + @Test("Without the sidebar tracking separator the group goes in at the leading edge") func insertsAtTheLeadingEdgeWithoutTheSeparator() throws { let storage = try EphemeralDefaults() @@ -612,6 +653,14 @@ extension GlobalStateSuites { let identifiers = toolbar.items.map { $0.itemIdentifier } let separator = try #require(identifiers.firstIndex(of: .sidebarTrackingSeparator)) #expect(identifiers.dropFirst(separator + 1).first == MainWindowToolbar.objectKindsGroup) + // This window has no connection, so the group arrives dimmed rather than live until the next update. + let group = try #require( + toolbar.items.first { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } as? NSToolbarItemGroup + ) + #expect(!group.subitems.isEmpty) + for subitem in group.subitems { + #expect(!subitem.isEnabled, "\(subitem.itemIdentifier.rawValue) is live with no connection") + } AppSettingsManager.shared.general.showsObjectToolbar = false #expect(!hasGroup(), "Turning it off takes the group away") From 723bab057afdbc5ae8c790a84788c78220605f57 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 08:11:54 +0700 Subject: [PATCH 061/123] fix(sidebar): name no Objects target for a table's detail rows Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Views/Sidebar/DatabaseTreeSelection.swift | 4 ++-- .../Views/Sidebar/DatabaseTreeSelectionTests.swift | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift index 806ae4689c..a87c7d0d6f 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift @@ -84,8 +84,8 @@ internal enum DatabaseTreeSelection { case .containerObjectKindSection(let group): return group case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, - .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, .redisKeysSection, - .redisNode: + .table, .partition, .tableDetailGroup, .tableDetail, .routine, .trigger, .userType, .status, + .objectKindSection, .redisKeysSection, .redisNode: return nil } } diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift index 34c71f23e5..c067f71744 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeSelectionTests.swift @@ -128,4 +128,16 @@ struct DatabaseTreeObjectsTargetTests { #expect(target([.recentSection]) == nil) #expect(target([.schema(database: "shop", schema: "a"), .schema(database: "shop", schema: "b")]) == nil) } + + @Test("A table's detail group or detail row lists nothing") + func tableDetailRowsListNothing() { + let table = DatabaseTreeTableRef( + database: "shop", schema: nil, table: TableInfo(name: "orders", type: .table, rowCount: nil) + ) + let group = DatabaseTreeTableDetailGroupRef(table: table, kind: .indexes) + let detail = DatabaseTreeTableDetailRef(table: table, item: .column(TestFixtures.makeColumnInfo(name: "total"))) + + #expect(target([.tableDetailGroup(group)]) == nil) + #expect(target([.tableDetail(detail)]) == nil) + } } From be1463c2ea72e1cabc1409d1bae40b4af35d9623 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 08:21:16 +0700 Subject: [PATCH 062/123] feat(settings): add a one-step navigator layout preset Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Settings/NavigatorLayoutPreset.swift | 42 +++++ .../Views/Settings/GeneralSettingsView.swift | 30 ++++ .../Models/NavigatorLayoutPresetTests.swift | 150 ++++++++++++++++++ 3 files changed, 222 insertions(+) create mode 100644 apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift create mode 100644 apple/TableProTests/Models/NavigatorLayoutPresetTests.swift diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift new file mode 100644 index 0000000000..c1ea392e7c --- /dev/null +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -0,0 +1,42 @@ +// +// NavigatorLayoutPreset.swift +// TablePro +// + +import Foundation + +/// The Layout buttons in Settings > General: table details, the Objects tab on selection, the +/// Objects toolbar buttons, the connections list and Tree as the default sidebar layout, on or off +/// in one step. +/// +/// It edits the same values the separate controls edit and leaves the write to the caller. Settings +/// passes its General settings binding, so the change lands on `AppSettingsManager.general` in one +/// write and the toolbar and the connections column react as they do to each toggle. +internal enum NavigatorLayoutPreset { + internal static func apply(to settings: inout GeneralSettings, defaultLayout: inout SidebarLayout) { + settings.showTableDetails = true + settings.showsObjectsOnSelection = true + settings.showsObjectToolbar = true + settings.showsConnectionNavigator = true + defaultLayout = .tree + } + + internal static func restore(to settings: inout GeneralSettings, defaultLayout: inout SidebarLayout) { + let standard = GeneralSettings.default + settings.showTableDetails = standard.showTableDetails + settings.showsObjectsOnSelection = standard.showsObjectsOnSelection + settings.showsObjectToolbar = standard.showsObjectToolbar + settings.showsConnectionNavigator = standard.showsConnectionNavigator + defaultLayout = .flat + } + + /// The default layout reaches only connections opened later, so each open one is switched the way + /// the View menu switches it. An engine with no database tree is skipped, as the menu skips it. + @MainActor + internal static func switchOpenConnections(to layout: SidebarLayout) { + for session in DatabaseManager.shared.activeSessions.values + where PluginManager.shared.supportsDatabaseTree(for: session.connection.type) { + SharedSidebarState.forConnection(session.connection.id).sidebarLayout = layout + } + } +} diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 1fac2c624f..574c1c822d 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -60,6 +60,25 @@ struct GeneralSettingsView: View { .help("Scrolling keeps one row of tabs, the way every macOS tab bar does. Rows wraps them so nothing is off screen.") } + Section { + HStack { + Button(String(localized: "Use Navigator Layout")) { + useLayoutPreset(navigator: true) + } + Button(String(localized: "Use Standard Layout")) { + useLayoutPreset(navigator: false) + } + } + } header: { + Text("Layout") + } footer: { + Text(String(localized: """ + Navigator Layout turns on table details, the Objects tab on selection, the Objects toolbar \ + buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout \ + turns them off again. Open connections switch layout too. + """)) + } + 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.") @@ -164,6 +183,17 @@ struct GeneralSettingsView: View { if initialLanguage == nil { initialLanguage = settings.language } } } + + // Writes through the General settings binding and the same stored default the layout picker uses, + // so every control below shows the result and each setting's own observers fire. + private func useLayoutPreset(navigator: Bool) { + if navigator { + NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &defaultSidebarLayout) + } else { + NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &defaultSidebarLayout) + } + NavigatorLayoutPreset.switchOpenConnections(to: defaultSidebarLayout) + } } #Preview { diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift new file mode 100644 index 0000000000..e0ad4131d8 --- /dev/null +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -0,0 +1,150 @@ +// +// NavigatorLayoutPresetTests.swift +// TableProTests +// + +import AppKit +import Combine +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +struct NavigatorLayoutPresetTests { + private static func navigatorLayout(from settings: GeneralSettings) -> GeneralSettings { + var expected = settings + expected.showTableDetails = true + expected.showsObjectsOnSelection = true + expected.showsObjectToolbar = true + expected.showsConnectionNavigator = true + return expected + } + + @Test("Use Navigator Layout turns on all four features and makes Tree the default layout") + func applyTurnsEverythingOn() { + var settings = GeneralSettings.default + var layout = SidebarLayout.flat + + NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &layout) + + #expect(settings.showTableDetails) + #expect(settings.showsObjectsOnSelection) + #expect(settings.showsObjectToolbar) + #expect(settings.showsConnectionNavigator) + #expect(layout == .tree) + } + + @Test("Use Standard Layout puts all five back to their defaults") + func restorePutsTheDefaultsBack() { + var settings = Self.navigatorLayout(from: .default) + var layout = SidebarLayout.tree + + NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &layout) + + #expect(settings.showTableDetails == GeneralSettings.default.showTableDetails) + #expect(settings.showsObjectsOnSelection == GeneralSettings.default.showsObjectsOnSelection) + #expect(settings.showsObjectToolbar == GeneralSettings.default.showsObjectToolbar) + #expect(settings.showsConnectionNavigator == GeneralSettings.default.showsConnectionNavigator) + #expect(settings == GeneralSettings.default) + #expect(layout == .flat) + } + + @Test("Using the navigator layout a second time changes nothing") + func applyingTwiceIsHarmless() { + var settings = GeneralSettings.default + var layout = SidebarLayout.flat + NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &layout) + let once = settings + + NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &layout) + + #expect(settings == once) + #expect(layout == .tree) + } + + @Test("Neither button touches any other General setting") + func otherSettingsStayPut() { + var settings = GeneralSettings.default + settings.showRecentTables = true + settings.showWorkspaceRail = false + settings.showPartitions = false + settings.queryTimeoutSeconds = 90 + let before = settings + var layout = SidebarLayout.flat + + NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &layout) + #expect(settings == Self.navigatorLayout(from: before)) + + NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &layout) + #expect(settings == before) + } + + /// The View menu switches one connection through its shared sidebar state; the preset does the + /// same for each open one, and skips an engine that has no tree to switch to. + @MainActor + @Test("Open connections that can show a tree switch layout, and the others keep theirs") + func openConnectionsSwitchLayout() { + let networked = TestFixtures.makeConnection(name: "Networked", type: .mysql) + let file = TestFixtures.makeConnection(name: "File", type: .sqlite) + let connections = [networked, file] + for connection in connections { + DatabaseManager.shared.injectSession(ConnectionSession(connection: connection), for: connection.id) + } + defer { + for connection in connections { + DatabaseManager.shared.removeSession(for: connection.id) + SharedSidebarState.removeConnection(connection.id) + SidebarPersistenceKey.removeAll(connectionId: connection.id) + } + } + let fileLayout = SharedSidebarState.forConnection(file.id).sidebarLayout + + NavigatorLayoutPreset.switchOpenConnections(to: .tree) + + #expect(SharedSidebarState.forConnection(networked.id).sidebarLayout == .tree) + #expect(SharedSidebarState.forConnection(file.id).sidebarLayout == fileLayout) + + NavigatorLayoutPreset.switchOpenConnections(to: .flat) + + #expect(SharedSidebarState.forConnection(networked.id).sidebarLayout == .flat) + } +} + +extension GlobalStateSuites { + /// The preset written the way Settings writes it, through the General settings value in one + /// step, reaching what each toggle reaches when flipped by hand. + @MainActor + struct NavigatorLayoutPresetSettingTests { + @Test( + "Through the settings manager, the preset reaches the toolbar and the connections column", + .appSettings { + $0.general.showTableDetails = false + $0.general.showsObjectsOnSelection = false + $0.general.showsObjectToolbar = false + $0.general.showsConnectionNavigator = false + } + ) + func presetReachesAnOpenWindow() throws { + let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_512, height: 861)) + defer { fixture.tearDown() } + let storage = try EphemeralDefaults() + fixture.toolbarOwner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) + let toolbar = try #require(fixture.window.toolbar) + let hasGroup = { toolbar.items.contains { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } } + var railChanges = 0 + let subscription = AppEvents.shared.workspaceRailVisibilityChanged.sink { railChanges += 1 } + defer { subscription.cancel() } + var layout = SidebarLayout.flat + + NavigatorLayoutPreset.apply(to: &AppSettingsManager.shared.general, defaultLayout: &layout) + + #expect(hasGroup(), "The Objects buttons reach the open window") + #expect(railChanges == 1, "The connections column is told to swap in the navigator") + + NavigatorLayoutPreset.restore(to: &AppSettingsManager.shared.general, defaultLayout: &layout) + + #expect(!hasGroup(), "The Objects buttons leave the open window") + #expect(railChanges == 2, "The connections column is told to swap the navigator out") + } + } +} From 39377e7a0864a578588406bd645059c29904716d Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 08:21:59 +0700 Subject: [PATCH 063/123] chore(l10n): add the layout preset strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Resources/Localizable.xcstrings | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 3851f57c1a..2cab2c3aa6 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -113723,6 +113723,9 @@ } } } + }, + "Navigator Layout turns on table details, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Nearest" : { "extractionState" : "stale", @@ -210736,6 +210739,9 @@ }, "Use License Key…" : { + }, + "Use Navigator Layout" : { + }, "Use Required for Amazon Keyspaces and other hosted Cassandra deployments." : { "localizations" : { @@ -210876,6 +210882,9 @@ } } } + }, + "Use Standard Layout" : { + }, "Use System Color" : { From 2148856db4fb8a16a80438f8388a1b24452502ba Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 13:47:17 +0700 Subject: [PATCH 064/123] fix(objects): keep the name filter on the model a kind switch hands in Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Views/Sidebar/NativeSearchField.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apple/TablePro/Views/Sidebar/NativeSearchField.swift b/apple/TablePro/Views/Sidebar/NativeSearchField.swift index 6e51937171..b560310673 100644 --- a/apple/TablePro/Views/Sidebar/NativeSearchField.swift +++ b/apple/TablePro/Views/Sidebar/NativeSearchField.swift @@ -92,6 +92,8 @@ struct NativeSearchField: NSViewRepresentable { } field.placeholderString = placeholder field.isEnabled = context.environment.isEnabled + // A parent can hand this field another model's text, as the Objects tab does when its kind changes. + context.coordinator.text = $text context.coordinator.onMoveUp = onMoveUp context.coordinator.onMoveDown = onMoveDown context.coordinator.onSubmit = onSubmit From 781ef8057e3f2af9a7536025569d026a014d16c3 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 13:47:17 +0700 Subject: [PATCH 065/123] fix(objects): list only tables under Tables, with worded column headers Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Services/Query/ObjectListingRows.swift | 31 +++++++++++++++++++ .../Services/Query/TableListingLoader.swift | 9 ++++-- .../Query/ObjectListingRowsTests.swift | 29 +++++++++++++++++ .../TableListingViewModelTests.swift | 2 +- 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift index 9fd09491eb..6ecfa62e6d 100644 --- a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift +++ b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift @@ -105,6 +105,37 @@ internal struct ObjectListingColumns: Equatable { return items } + /// The Tables kind lists tables only. Views, sequences and the other relations each have a kind of + /// their own, as they have a group in the sidebar, and a listing without a kind column keeps every row. + func tableRows(of rows: [[PluginCellValue]]) -> [[PluginCellValue]] { + guard let kind else { return rows } + return rows.filter { row in + let word = row.indices.contains(kind) ? row[kind].asText : nil + return SidebarObjectKind.resolve(tableType: Self.relationType(word)) == .table + } + } + + /// The plugins alias their listing columns for SQL, not for reading, so a known alias reads as words. + /// An alias this does not know keeps the plugin's spelling. + static func displayTitle(for column: String) -> String { + switch column.lowercased() { + case "schema", "schema_name": String(localized: "Schema") + case "name": String(localized: "Name") + case "kind": String(localized: "Type") + case "charset": String(localized: "Charset") + case "collation": String(localized: "Collation") + case "estimated_rows": String(localized: "Rows") + case "total_size": String(localized: "Total Size") + case "data_size": String(localized: "Data Size") + case "index_size": String(localized: "Index Size") + case "engine": String(localized: "Engine") + case "create_time": String(localized: "Created") + case "update_time": String(localized: "Updated") + case "comment": String(localized: "Comment") + default: column + } + } + /// An unknown word, such as a ClickHouse engine name, reads as a table: only a view must not /// open as an editable grid. static func relationType(_ kind: String?) -> TableInfo.TableType { diff --git a/apple/TablePro/Core/Services/Query/TableListingLoader.swift b/apple/TablePro/Core/Services/Query/TableListingLoader.swift index 77efd8f868..2b948b133b 100644 --- a/apple/TablePro/Core/Services/Query/TableListingLoader.swift +++ b/apple/TablePro/Core/Services/Query/TableListingLoader.swift @@ -37,8 +37,13 @@ internal struct TableListingLoader: Sendable { } return try await driver.executeCatalogRead(query: statement) } - let rows = TableRows.from(queryRows: result.rows, columns: result.columns, columnTypes: result.columnTypes) - let items = ObjectListingColumns(columns: result.columns)?.items( + let listingColumns = ObjectListingColumns(columns: result.columns) + let rows = TableRows.from( + queryRows: listingColumns?.tableRows(of: result.rows) ?? result.rows, + columns: listingColumns == nil ? result.columns : result.columns.map(ObjectListingColumns.displayTitle(for:)), + columnTypes: result.columnTypes + ) + let items = listingColumns?.items( in: rows, containerSchema: scope.schema, readsSchemaColumn: slot == .schema diff --git a/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift b/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift index 74b3e5794c..4713b86a63 100644 --- a/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift +++ b/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift @@ -130,6 +130,35 @@ struct ObjectListingRowsTests { #expect(items[.existing(0)] == .relation(name: "orders", schema: nil, type: .table)) } + @Test("A Tables listing keeps tables and leaves views and sequences to their own kinds") + func tablesListingKeepsOnlyTables() throws { + let columns = try #require(ObjectListingColumns(columns: ["schema", "name", "kind"])) + let rows: [[PluginCellValue]] = [ + [.text("shop"), .text("orders"), .text("BASE TABLE")], + [.text("shop"), .text("v_orders"), .text("VIEW")], + [.text("shop"), .text("order_ids"), .text("SEQUENCE")], + [.text("shop"), .text("events"), .text("MergeTree")], + ] + + #expect(columns.tableRows(of: rows).map { $0[1].asText } == ["orders", "events"]) + } + + @Test("A listing without a kind column keeps every row") + func listingWithoutKindKeepsEveryRow() throws { + let columns = try #require(ObjectListingColumns(columns: ["name"])) + let rows: [[PluginCellValue]] = [[.text("orders")], [.text("v_orders")]] + + #expect(columns.tableRows(of: rows).count == 2) + } + + @Test("A known listing alias reads as words and an unknown one keeps the plugin's spelling") + func listingAliasesReadAsWords() { + #expect(ObjectListingColumns.displayTitle(for: "estimated_rows") == "Rows") + #expect(ObjectListingColumns.displayTitle(for: "SCHEMA_NAME") == "Schema") + #expect(ObjectListingColumns.displayTitle(for: "update_time") == "Updated") + #expect(ObjectListingColumns.displayTitle(for: "total_rows") == "total_rows") + } + static let kindWords: [(String?, TableInfo.TableType)] = [ ("VIEW", .view), ("view", .view), ("SYSTEM VIEW", .view), ("MATERIALIZED VIEW", .materializedView), ("FOREIGN TABLE", .foreignTable), ("SEQUENCE", .sequence), ("BASE TABLE", .table), ("MergeTree", .table), (nil, .table), diff --git a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift index 0fcdd748c2..5c54101bd0 100644 --- a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift +++ b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift @@ -190,7 +190,7 @@ struct TableListingViewModelTests { await viewModel.reload().value #expect(names(viewModel.state) == ["customers", "orders"]) - #expect(viewModel.state.value?.rows.columns == ["name"]) + #expect(viewModel.state.value?.rows.columns == ["Name"]) #expect(viewModel.state.value?.isIncomplete == false) #expect(viewModel.state.value?.notice == nil) #expect(provider.requestedScopes == [scope]) From d58473a00192076ee423d3ad4bcbdb73f3452fb9 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 13:47:17 +0700 Subject: [PATCH 066/123] feat(toolbar): draw the front tab's object kind in the accent color Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Items.swift | 71 +++++++++++++++++-- .../ObjectKindsToolbarTests.swift | 34 +++++++++ 2 files changed, 101 insertions(+), 4 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift index b149e4d8ce..fa401ca5d2 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift @@ -367,25 +367,53 @@ extension MainWindowToolbar { id: Self.objectTables, label: String(localized: "Tables"), symbol: SidebarObjectKind.table.iconName, - action: #selector(performShowTables(_:)) + action: #selector(performShowTables(_:)), + glyphProvider: { [weak self] in + Self.objectKindGlyph( + symbol: SidebarObjectKind.table.iconName, + label: String(localized: "Tables"), + isSelected: self?.selectedObjectKindItem() == Self.objectTables + ) + } ), menuOnlyItem( id: Self.objectViews, label: String(localized: "Views"), symbol: SidebarObjectKind.view.iconName, - action: #selector(performShowViews(_:)) + action: #selector(performShowViews(_:)), + glyphProvider: { [weak self] in + Self.objectKindGlyph( + symbol: SidebarObjectKind.view.iconName, + label: String(localized: "Views"), + isSelected: self?.selectedObjectKindItem() == Self.objectViews + ) + } ), menuOnlyItem( id: Self.objectFunctions, label: String(localized: "Functions"), symbol: SidebarObjectKind.function.iconName, - action: #selector(performShowFunctions(_:)) + action: #selector(performShowFunctions(_:)), + glyphProvider: { [weak self] in + Self.objectKindGlyph( + symbol: SidebarObjectKind.function.iconName, + label: String(localized: "Functions"), + isSelected: self?.selectedObjectKindItem() == Self.objectFunctions + ) + } ), menuOnlyItem( id: Self.objectUsers, label: String(localized: "Users"), symbol: "person.2", - action: #selector(performShowUsers(_:)) + action: #selector(performShowUsers(_:)), + glyphProvider: { [weak self] in + Self.objectKindGlyph( + symbol: "person.2", + label: String(localized: "Users"), + isSelected: self?.selectedObjectKindItem() == Self.objectUsers + ) + } ), menuOnlyItem( id: Self.objectQuery, @@ -404,6 +432,41 @@ extension MainWindowToolbar { ) } + /// The button for what the front tab shows. Query and Backup start something new, so neither stays selected. + static func selectedObjectKindItem(tabType: TabType?, listingKind: SidebarObjectKind?) -> NSToolbarItem.Identifier? { + switch tabType { + case .tableListing: + switch listingKind ?? .table { + case .table: return objectTables + case .view: return objectViews + case .function: return objectFunctions + default: return nil + } + case .usersRoles: + return objectUsers + default: + return nil + } + } + + func selectedObjectKindItem() -> NSToolbarItem.Identifier? { + let tab = coordinator?.tabManager.selectedTab + return Self.selectedObjectKindItem(tabType: tab?.tabType, listingKind: tab?.display.listingKind) + } + + /// The selected kind draws its glyph in the accent color, the way Xcode's navigator bar marks the navigator on + /// screen. Measured on macOS 27, a toolbar item group draws no selected state for the buttons it holds, whatever + /// its selection mode. + static func objectKindGlyph(symbol: String, label: String, isSelected: Bool) -> ToolbarGlyph { + ToolbarGlyph(key: isSelected ? "selected" : "plain") { + let image = NSImage(systemSymbolName: symbol, accessibilityDescription: label) + guard isSelected else { return image } + let tinted = image?.withSymbolConfiguration(NSImage.SymbolConfiguration(paletteColors: [.controlAccentColor])) + tinted?.isTemplate = false + return tinted + } + } + // MARK: - Helpers /// The label is what the customization palette and the overflow menu show, so it stays short. diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index 57bea00009..11d95af249 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -105,6 +105,40 @@ struct ObjectKindsToolbarTests { } } + // MARK: - Selection + + @Test("The button for the front tab's kind draws in the accent color and the others stay template glyphs") + func frontKindDrawsInAccent() throws { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .mysql)) + let owner = Self.owner() + owner.repoint(to: fixture.coordinator) + let group = try Self.group(from: owner) + + try Self.press(MainWindowToolbar.objectViews, on: owner) + group.subitems.forEach { $0.validate() } + + func image(_ identifier: NSToolbarItem.Identifier) -> NSImage? { + group.subitems.first { $0.itemIdentifier == identifier }?.image + } + #expect(owner.selectedObjectKindItem() == MainWindowToolbar.objectViews) + #expect(image(MainWindowToolbar.objectViews)?.isTemplate == false) + #expect(image(MainWindowToolbar.objectTables)?.isTemplate == true) + #expect(image(MainWindowToolbar.objectFunctions)?.isTemplate == true) + } + + @Test("The selected button is the kind the front tab shows, and none for a tab no button opens") + func selectionFollowsTheFrontTab() { + let select = MainWindowToolbar.selectedObjectKindItem + #expect(select(.tableListing, nil) == MainWindowToolbar.objectTables) + #expect(select(.tableListing, .table) == MainWindowToolbar.objectTables) + #expect(select(.tableListing, .view) == MainWindowToolbar.objectViews) + #expect(select(.tableListing, .function) == MainWindowToolbar.objectFunctions) + #expect(select(.tableListing, .procedure) == nil) + #expect(select(.usersRoles, nil) == MainWindowToolbar.objectUsers) + #expect(select(.query, nil) == nil) + #expect(select(nil, nil) == nil) + } + // MARK: - Routing @Test("Tables, Views and Functions open the browsed container's objects on their kind", arguments: [ From a18e8d00b00595a3768be67be83d02e254236a4e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 13:47:17 +0700 Subject: [PATCH 067/123] fix(navigator): widen the connections column and name its rows for VoiceOver Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionNavigator/ConnectionNavigatorRow.swift | 8 ++++++++ .../ConnectionNavigatorViewController.swift | 11 +++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift index fc66dd6a65..2db9f24810 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRow.swift @@ -60,4 +60,12 @@ internal enum ConnectionNavigatorRow: Equatable { case .connection: return [] } } + + /// What type-select matches and VoiceOver reads for the row. + internal var name: String { + switch self { + case .group(let group): return group.name + case .connection(let connection): return connection.connection.name + } + } } diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift index 46f1ae51df..8923591435 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorViewController.swift @@ -75,7 +75,8 @@ internal final class ConnectionNavigatorCellView: SidebarHostingCellView String? { - switch (item as? ConnectionNavigatorOutlineItem)?.row { - case .group(let group): return group.name - case .connection(let connection): return connection.connection.name - case nil: return nil - } + (item as? ConnectionNavigatorOutlineItem)?.row.name } } From 2b7f8ce9e4d013bc1f6e3c718f99dfc148dce347 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 13:47:17 +0700 Subject: [PATCH 068/123] style(sidebar): draw the Tables and Favorites switcher at regular size Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Views/Sidebar/SidebarScopeControl.swift | 8 +++----- .../Views/Sidebar/SidebarScopeControlTests.swift | 4 +--- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/apple/TablePro/Views/Sidebar/SidebarScopeControl.swift b/apple/TablePro/Views/Sidebar/SidebarScopeControl.swift index 5a42170410..2e93bfd614 100644 --- a/apple/TablePro/Views/Sidebar/SidebarScopeControl.swift +++ b/apple/TablePro/Views/Sidebar/SidebarScopeControl.swift @@ -22,10 +22,9 @@ import AppKit /// Simplified Chinese 100pt. /// /// On macOS 27 it takes the tabs role AppKit gives "tab-based navigation and content selection", -/// at small size. Measured there, a regular control in a sidebar draws a glass capsule whatever -/// its style or role; small with the tabs role draws a flat track with a neutral raised thumb. -/// Small without the role would fill the thumb with the accent color, which marks a value choice, -/// so earlier releases keep the regular control. +/// at regular size. Measured there, a regular control in a sidebar draws a glass capsule, the shape +/// and height of the editor tab strip beside it in the same row; small draws a flat track a size +/// below every other tab row in the window. Earlier releases keep the regular control too. @MainActor internal final class SidebarScopeControl: NSSegmentedControl { internal static let tabs: [SidebarTab] = [.tables, .favorites] @@ -39,7 +38,6 @@ internal final class SidebarScopeControl: NSSegmentedControl { #if SDK_MACOS_27 if #available(macOS 27.0, *) { role = .tabs - controlSize = .small } #endif for (index, tab) in Self.tabs.enumerated() { diff --git a/apple/TableProTests/Views/Sidebar/SidebarScopeControlTests.swift b/apple/TableProTests/Views/Sidebar/SidebarScopeControlTests.swift index 0eee73249a..65244d8141 100644 --- a/apple/TableProTests/Views/Sidebar/SidebarScopeControlTests.swift +++ b/apple/TableProTests/Views/Sidebar/SidebarScopeControlTests.swift @@ -22,14 +22,12 @@ struct SidebarScopeControlTests { #expect(control.label(forSegment: 1) == String(localized: "Favorites")) } - @Test("macOS 27 draws it as small tabs, earlier releases as a regular control") + @Test("macOS 27 draws it as regular tabs, earlier releases as a regular control") func tabsRoleOnMacOS27() { let control = SidebarScopeControl() #if SDK_MACOS_27 if #available(macOS 27.0, *) { #expect(control.role == .tabs) - #expect(control.controlSize == .small) - return } #endif #expect(control.controlSize == .regular) From 0ba6f7284edae89d93a2ebf961bbf0ad6b78d5cb Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 13:47:17 +0700 Subject: [PATCH 069/123] feat(sidebar): list favorite tables at the top of the tree Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Settings/GeneralSettings.swift | 5 + .../Settings/NavigatorLayoutPreset.swift | 8 +- .../ViewModels/SidebarViewModel.swift | 13 ++ .../Views/Settings/GeneralSettingsView.swift | 9 +- .../Views/Sidebar/DatabaseTreeCellView.swift | 5 +- .../Views/Sidebar/DatabaseTreeNode.swift | 25 ++- ...baseTreeOutlineCoordinator+Expansion.swift | 13 +- ...DatabaseTreeOutlineCoordinator+Nodes.swift | 9 +- .../DatabaseTreeOutlineCoordinator.swift | 38 +++- .../Sidebar/DatabaseTreeOutlineView.swift | 1 + .../Views/Sidebar/DatabaseTreeRowView.swift | 4 +- .../Views/Sidebar/DatabaseTreeSelection.swift | 9 +- .../Sidebar/DatabaseTreeTypeSelect.swift | 5 +- .../Views/Sidebar/DatabaseTreeView.swift | 3 +- .../Sidebar/Menu/DatabaseTreeMenuSpec.swift | 4 +- .../Views/Sidebar/SidebarPersistenceKey.swift | 4 + .../Views/Sidebar/SidebarTreeView.swift | 3 +- .../TablePro/Views/Sidebar/SidebarView.swift | 3 +- .../Models/NavigatorLayoutPresetTests.swift | 7 +- .../DatabaseTreeFavoritesSectionTests.swift | 189 ++++++++++++++++++ 20 files changed, 322 insertions(+), 35 deletions(-) create mode 100644 apple/TableProTests/Views/Sidebar/DatabaseTreeFavoritesSectionTests.swift diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 5dd87ca9ed..232ba676af 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -61,6 +61,7 @@ struct GeneralSettings: Codable, Equatable { var queryTimeoutSeconds: Int var shareAnalytics: Bool var showRecentTables: Bool + var showsFavoritesSection: Bool var showsObjectsOnSelection: Bool var showsObjectToolbar: Bool var showObjectComments: Bool @@ -79,6 +80,7 @@ struct GeneralSettings: Codable, Equatable { queryTimeoutSeconds: 60, shareAnalytics: true, showRecentTables: false, + showsFavoritesSection: false, showsObjectsOnSelection: false, showsObjectToolbar: false, showObjectComments: true, @@ -98,6 +100,7 @@ struct GeneralSettings: Codable, Equatable { queryTimeoutSeconds: Int = 60, shareAnalytics: Bool = true, showRecentTables: Bool = false, + showsFavoritesSection: Bool = false, showsObjectsOnSelection: Bool = false, showsObjectToolbar: Bool = false, showObjectComments: Bool = true, @@ -115,6 +118,7 @@ struct GeneralSettings: Codable, Equatable { self.queryTimeoutSeconds = queryTimeoutSeconds self.shareAnalytics = shareAnalytics self.showRecentTables = showRecentTables + self.showsFavoritesSection = showsFavoritesSection self.showsObjectsOnSelection = showsObjectsOnSelection self.showsObjectToolbar = showsObjectToolbar self.showObjectComments = showObjectComments @@ -136,6 +140,7 @@ struct GeneralSettings: Codable, Equatable { queryTimeoutSeconds = container.decodeSetting(.queryTimeoutSeconds, default: fallback.queryTimeoutSeconds) shareAnalytics = container.decodeSetting(.shareAnalytics, default: fallback.shareAnalytics) showRecentTables = container.decodeSetting(.showRecentTables, default: fallback.showRecentTables) + showsFavoritesSection = container.decodeSetting(.showsFavoritesSection, default: fallback.showsFavoritesSection) showsObjectsOnSelection = container.decodeSetting( .showsObjectsOnSelection, default: fallback.showsObjectsOnSelection ) diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index c1ea392e7c..a1b6358096 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -5,9 +5,9 @@ import Foundation -/// The Layout buttons in Settings > General: table details, the Objects tab on selection, the -/// Objects toolbar buttons, the connections list and Tree as the default sidebar layout, on or off -/// in one step. +/// The Layout buttons in Settings > General: table details, favorite tables at the top of the tree, +/// the Objects tab on selection, the Objects toolbar buttons, the connections list and Tree as the +/// default sidebar layout, on or off in one step. /// /// It edits the same values the separate controls edit and leaves the write to the caller. Settings /// passes its General settings binding, so the change lands on `AppSettingsManager.general` in one @@ -15,6 +15,7 @@ import Foundation internal enum NavigatorLayoutPreset { internal static func apply(to settings: inout GeneralSettings, defaultLayout: inout SidebarLayout) { settings.showTableDetails = true + settings.showsFavoritesSection = true settings.showsObjectsOnSelection = true settings.showsObjectToolbar = true settings.showsConnectionNavigator = true @@ -24,6 +25,7 @@ internal enum NavigatorLayoutPreset { internal static func restore(to settings: inout GeneralSettings, defaultLayout: inout SidebarLayout) { let standard = GeneralSettings.default settings.showTableDetails = standard.showTableDetails + settings.showsFavoritesSection = standard.showsFavoritesSection settings.showsObjectsOnSelection = standard.showsObjectsOnSelection settings.showsObjectToolbar = standard.showsObjectToolbar settings.showsConnectionNavigator = standard.showsConnectionNavigator diff --git a/apple/TablePro/ViewModels/SidebarViewModel.swift b/apple/TablePro/ViewModels/SidebarViewModel.swift index 08ecd41429..67e1dbbdd7 100644 --- a/apple/TablePro/ViewModels/SidebarViewModel.swift +++ b/apple/TablePro/ViewModels/SidebarViewModel.swift @@ -165,6 +165,14 @@ final class SidebarViewModel: ObservableObject { ) } } + @Published var isFavoritesExpanded: Bool { + didSet { + defaults.set( + isFavoritesExpanded, + forKey: SidebarPersistenceKey.favoritesExpanded(connectionId: connectionId) + ) + } + } @Published var isFoldersExpanded: Bool { didSet { defaults.set( @@ -263,6 +271,11 @@ final class SidebarViewModel: ObservableObject { defaultValue: true, defaults: defaults ) + self.isFavoritesExpanded = Self.loadExpansion( + perConnectionKey: SidebarPersistenceKey.favoritesExpanded(connectionId: connectionId), + defaultValue: true, + defaults: defaults + ) self.isFoldersExpanded = Self.loadExpansion( perConnectionKey: SidebarPersistenceKey.foldersExpanded(connectionId: connectionId), defaultValue: true, diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 574c1c822d..8c7f861dea 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -73,9 +73,9 @@ struct GeneralSettingsView: View { Text("Layout") } footer: { Text(String(localized: """ - Navigator Layout turns on table details, the Objects tab on selection, the Objects toolbar \ - buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout \ - turns them off again. Open connections switch layout too. + Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects \ + tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the \ + default sidebar layout. Standard Layout turns them off again. Open connections switch layout too. """)) } @@ -89,6 +89,9 @@ struct GeneralSettingsView: View { 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 favorite tables at the top of the tree", isOn: $settings.showsFavoritesSection) + .help("Adds a Favorites section above Recent with the tables you starred in the database you are browsing. Each table also stays in its own place.") + Toggle("Show objects when a database, schema or group is selected", isOn: $settings.showsObjectsOnSelection) .help("Clicking a database, schema or object group in the sidebar lists its objects in the main area. Show Objects in the row's menu lists them either way.") diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift index 7c53376369..9387d48087 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift @@ -32,7 +32,7 @@ final class DatabaseTreeCellView: RenamableSidebarCellView private static func symbolName(for node: DatabaseTreeNode) -> String { switch node.kind { - case .table(let ref), .recentTable(let ref), .temporaryTable(let ref): + case .table(let ref), .recentTable(let ref), .favoriteTable(let ref), .temporaryTable(let ref): return TableRowLogic.iconName(for: ref.table.type) case .partition: return SidebarPartitionRow.iconName @@ -40,7 +40,8 @@ final class DatabaseTreeCellView: RenamableSidebarCellView return metadata.isSystemDatabase ? "gearshape" : "cylinder" case .schema, .tableFolder: return "folder" - case .routine, .trigger, .userType, .status, .recentSection, .temporarySection, .foldersSection, + case .routine, .trigger, .userType, .status, .recentSection, .favoritesSection, .temporarySection, + .foldersSection, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: return "tablecells" diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift index bc858db308..92afb7d37e 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift @@ -78,6 +78,9 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { enum Kind { case recentSection case recentTable(DatabaseTreeTableRef) + /// The browsed database's favorite tables, above Recent. Each table also keeps its own row. + case favoritesSection + case favoriteTable(DatabaseTreeTableRef) case temporarySection case temporaryTable(DatabaseTreeTableRef) /// Flat shape: the section the browsed schema's folders sit in, above the object kinds. @@ -123,7 +126,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { var isExpandable: Bool { switch kind { - case .recentSection, .temporarySection, .foldersSection, .tableFolder, .database, .schema, + case .recentSection, .favoritesSection, .temporarySection, .foldersSection, .tableFolder, .database, .schema, .objectKindSection, .containerObjectKindSection, .tableDetailGroup, .hierarchicalSchemaSection, .redisKeysSection: return true @@ -134,7 +137,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { case .redisNode(let node): guard case .namespace = node else { return false } return true - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetail: + case .recentTable, .favoriteTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetail: return false } } @@ -164,7 +167,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return !showsTableDetails case .tableDetailGroup: return false - case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .database, .schema, .partition, .tableDetail, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: @@ -190,6 +193,11 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return nil } + var favoriteTableRef: DatabaseTreeTableRef? { + if case .favoriteTable(let ref) = kind { return ref } + return nil + } + var temporaryTableRef: DatabaseTreeTableRef? { if case .temporaryTable(let ref) = kind { return ref } return nil @@ -203,10 +211,11 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { /// children, so it stays an ordinary container row the way a folder does in Xcode's navigator. var isGroupRow: Bool { switch kind { - case .recentSection, .temporarySection, .foldersSection, .objectKindSection, .redisKeysSection: + case .recentSection, .favoritesSection, .temporarySection, .foldersSection, .objectKindSection, + .redisKeysSection: return true case .database, .schema, .containerObjectKindSection, .tableFolder, - .hierarchicalSchemaSection, .recentTable, .temporaryTable, .table, .partition, + .hierarchicalSchemaSection, .recentTable, .favoriteTable, .temporaryTable, .table, .partition, .routine, .trigger, .userType, .status, .redisNode, .tableDetailGroup, .tableDetail: return false } @@ -216,7 +225,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { switch kind { case .database, .schema: return true - case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: @@ -230,7 +239,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return .database(metadata.name, isSystem: metadata.isSystemDatabase) case .schema(let database, let schema): return .schema(database: database, schema: schema, isSystem: systemSchemas.contains(schema)) - case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: @@ -244,6 +253,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { } static let recentSectionId = "recent-section" + static let favoritesSectionId = "favorites-section" /// The flat shape's root, which has no row of its own; its status row hangs off this id. static let flatRootId = "flat-root" static let foldersSectionId = "folders-section" @@ -302,6 +312,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { } static func recentTableId(_ ref: DatabaseTreeTableRef) -> String { "recent\u{1}table\u{1}\(ref.id)" } + static func favoriteTableId(_ ref: DatabaseTreeTableRef) -> String { "favorite\u{1}table\u{1}\(ref.id)" } static let temporarySectionId = "temporary-section" static func temporaryTableId(_ ref: DatabaseTreeTableRef) -> String { "temporary\u{1}table\u{1}\(ref.id)" } static func routineId(_ ref: DatabaseTreeRoutineRef) -> String { "routine\u{1}\(ref.id)" } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift index ffa7cc450b..0f2b2188d8 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift @@ -19,6 +19,8 @@ extension DatabaseTreeOutlineCoordinator { switch rootNode.kind { case .recentSection: setExpanded(rootNode, searching || (viewModel?.isRecentsExpanded ?? true)) + case .favoritesSection: + setExpanded(rootNode, searching || (viewModel?.isFavoritesExpanded ?? true)) case .temporarySection: setExpanded(rootNode, searching || (viewModel?.isTemporaryExpanded ?? true)) default: @@ -154,7 +156,7 @@ extension DatabaseTreeOutlineCoordinator { case .table, .partition, .tableDetailGroup: triggerLoad(for: node) readOpenDetailRows(under: node) - case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .database, .schema, .tableDetail, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: continue @@ -226,7 +228,7 @@ extension DatabaseTreeOutlineCoordinator { restoreFolderExpansion(under: node) case .objectKindSection, .containerObjectKindSection, .tableFolder, .table, .partition, .tableDetailGroup: restoreTableExpansion(under: node) - case .recentSection, .recentTable, .temporarySection, .temporaryTable, .database, .routine, .trigger, + case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .database, .routine, .trigger, .userType, .status, .redisKeysSection, .redisNode, .tableDetail: break } @@ -245,6 +247,8 @@ extension DatabaseTreeOutlineCoordinator { switch node.kind { case .recentSection: viewModel?.isRecentsExpanded = expanded + case .favoritesSection: + viewModel?.isFavoritesExpanded = expanded case .temporarySection: viewModel?.isTemporaryExpanded = expanded case .foldersSection: @@ -291,7 +295,8 @@ extension DatabaseTreeOutlineCoordinator { } else { windowState?.expandedTreeTableDetailGroups.remove(group.expansionKey) } - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .redisNode, .tableDetail: + case .recentTable, .favoriteTable, .temporaryTable, .routine, .trigger, .userType, .status, .redisNode, + .tableDetail: break } } @@ -325,7 +330,7 @@ extension DatabaseTreeOutlineCoordinator { || !hierarchicalSearchSkipsRead(schema) else { return } loadHierarchicalSchemaObjects(schema) - case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .redisKeysSection, .redisNode, .tableDetail: break diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift index 9cd545f5a8..219a83237b 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift @@ -48,6 +48,10 @@ extension DatabaseTreeOutlineCoordinator { return recentTableRefs().map { self.node(id: DatabaseTreeNode.recentTableId($0), kind: .recentTable($0)) } + case .favoritesSection: + return favoriteTableRefs().map { + self.node(id: DatabaseTreeNode.favoriteTableId($0), kind: .favoriteTable($0)) + } case .temporarySection: return temporaryTableRefs().map { self.node(id: DatabaseTreeNode.temporaryTableId($0), kind: .temporaryTable($0)) @@ -81,7 +85,7 @@ extension DatabaseTreeOutlineCoordinator { return redisChildren(of: redisNode) case .tableDetailGroup(let group): return tableDetailNodes(in: group) - case .recentTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetail: + case .recentTable, .favoriteTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetail: return [] } } @@ -460,6 +464,9 @@ extension DatabaseTreeOutlineCoordinator { private func sessionSectionNodes() -> [DatabaseTreeNode] { var nodes: [DatabaseTreeNode] = [] + if !favoriteTableRefs().isEmpty { + nodes.append(node(id: DatabaseTreeNode.favoritesSectionId, kind: .favoritesSection)) + } if !recentTableRefs().isEmpty { nodes.append(node(id: DatabaseTreeNode.recentSectionId, kind: .recentSection)) } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 825f7bedf2..277a6cb0e2 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -10,6 +10,7 @@ import os import SwiftUI import TableProPluginKit import TableProSQLGrammar +import TableProUtilities @MainActor final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { @@ -36,6 +37,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { private var pendingTruncates: Set = [] private var pendingDeletes: Set = [] internal var showRecentTables = true + internal var showsFavoritesSection = false internal var showSystemContainers = false internal var showsPartitions = true /// Off, no row draws a detail list, so the loaded ones go and nothing reads them again: the @@ -139,7 +141,12 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { MainActor.assumeIsolated { guard let self else { return } self.reloadFavorites() - self.refreshVisibleRows() + // The Favorites section gains or loses a row, which a reconfigure in place cannot show. + if self.showsFavoritesSection { + self.refresh() + } else { + self.refreshVisibleRows() + } } } favoritesObservers.withLockUnchecked { $0.append(tableObserver) } @@ -224,6 +231,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { || pendingTruncates != view.pendingTruncates || pendingDeletes != view.pendingDeletes || showRecentTables != view.showRecentTables + || showsFavoritesSection != view.showsFavoritesSection || showSystemContainers != view.showSystemContainers || showsPartitions != view.showsPartitions || showsTableDetails != view.showsTableDetails @@ -236,6 +244,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { pendingTruncates = view.pendingTruncates pendingDeletes = view.pendingDeletes showRecentTables = view.showRecentTables + showsFavoritesSection = view.showsFavoritesSection showSystemContainers = view.showSystemContainers showsPartitions = view.showsPartitions showsTableDetails = view.showsTableDetails @@ -389,6 +398,33 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { ) } + /// The browsed database's favorite tables by schema and name. A table whose list is loaded takes its + /// listed `TableInfo`, so a favorite view opens as a view; one not read yet stands as a table. + internal func favoriteTableRefs() -> [DatabaseTreeTableRef] { + guard showsFavoritesSection else { return [] } + let database = browsingDatabase + let search = SidebarSearch(searchText) + return favoriteTables + .filter { $0.database == database } + .sorted { ($0.schema ?? "", $0.name) < ($1.schema ?? "", $1.name) } + .compactMap { entry -> DatabaseTreeTableRef? in + if !search.isEmpty { + guard search.matchesObject(named: entry.name, database: database, schema: entry.schema) else { + return nil + } + } + // The tree reads per container; the flat list reads the session's own database. + let listed = database.flatMap { database in + service.tables(connectionId: connectionId, database: database, schema: entry.schema) + .first { $0.name == entry.name } + } ?? schemaService.tables(for: connectionId).first { table in + table.name == entry.name && table.schema?.nilIfEmpty == entry.schema + } + let table = listed ?? TableInfo(name: entry.name, type: .table, rowCount: nil, schema: entry.schema) + return DatabaseTreeTableRef(database: database, schema: entry.schema, table: table) + } + } + internal func isFavorite(_ ref: DatabaseTreeTableRef) -> Bool { favoriteTables.contains(favoriteEntry(for: ref)) } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift index 80452a3a23..155416750a 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift @@ -33,6 +33,7 @@ struct DatabaseTreeOutlineView: NSViewRepresentable { let showsPartitions: Bool let showsTableDetails: Bool let rowSizePreference: SidebarRowSizePreference + var showsFavoritesSection = false /// The size the rows are actually drawn at, which is the system's unless the user overrode it. var resolvedRowSize: SidebarRowSize { diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift index d013dc19ed..93b6e636a6 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift @@ -89,8 +89,10 @@ struct DatabaseTreeRowView: View { switch node.kind { case .recentSection: sectionHeader(String(localized: "Recent")) - case .recentTable(let ref): + case .recentTable(let ref), .favoriteTable(let ref): tableRow(ref) + case .favoritesSection: + sectionHeader(String(localized: "Favorites")) case .temporarySection: sectionHeader(String(localized: "Temporary")) case .temporaryTable(let ref): diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift index a87c7d0d6f..cc8475d715 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift @@ -15,10 +15,11 @@ import Foundation internal enum DatabaseTreeSelection { internal static func isSelectable(_ kind: DatabaseTreeNode.Kind) -> Bool { switch kind { - case .status, .recentSection, .temporarySection, .foldersSection, .objectKindSection, .redisKeysSection: + case .status, .recentSection, .favoritesSection, .temporarySection, .foldersSection, .objectKindSection, + .redisKeysSection: return false case .database, .schema, .hierarchicalSchemaSection, .table, .partition, .routine, .trigger, .userType, - .recentTable, .temporaryTable, .containerObjectKindSection, .tableFolder, .redisNode, + .recentTable, .favoriteTable, .temporaryTable, .containerObjectKindSection, .tableFolder, .redisNode, .tableDetailGroup, .tableDetail: return true } @@ -33,7 +34,7 @@ internal enum DatabaseTreeSelection { // A temporary table opens but takes no Table menu command: those run on a pooled connection, where its name // reaches the database's own table of that name, if any. private static func commandableRef(of node: DatabaseTreeNode) -> DatabaseTreeTableRef? { - node.tableRef ?? node.recentTableRef + node.tableRef ?? node.recentTableRef ?? node.favoriteTableRef } /// What the Table menu acts on, and what a queued Truncate or Drop is keyed by. The tree @@ -83,7 +84,7 @@ internal enum DatabaseTreeSelection { return DatabaseTreeObjectGroup(database: hierarchicalDatabase, schema: schema, kind: .table) case .containerObjectKindSection(let group): return group - case .recentSection, .recentTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .tableDetailGroup, .tableDetail, .routine, .trigger, .userType, .status, .objectKindSection, .redisKeysSection, .redisNode: return nil diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift index 2c786e0304..11d4e63c89 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift @@ -52,13 +52,14 @@ internal enum DatabaseTreeTypeSelect { tableEntityName: String? = nil ) -> String? { switch kind { - case .recentSection, .temporarySection, .foldersSection, .status, .objectKindSection, .redisKeysSection: + case .recentSection, .favoritesSection, .temporarySection, .foldersSection, .status, .objectKindSection, + .redisKeysSection: return nil case .tableFolder(let ref): return ref.folder.name case .containerObjectKindSection(let group): return group.kind.title(tableEntityName: tableEntityName) - case .recentTable(let ref), .temporaryTable(let ref), .table(let ref): + case .recentTable(let ref), .favoriteTable(let ref), .temporaryTable(let ref), .table(let ref): return ref.table.name case .partition(let ref): return ref.partition.name diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift index a0906ab5b4..f3c03b99df 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift @@ -192,7 +192,8 @@ struct DatabaseTreeView: View { showSystemContainers: showsSystemContainers, showsPartitions: settingsManager.general.showPartitions, showsTableDetails: settingsManager.general.showTableDetails, - rowSizePreference: settingsManager.general.sidebarRowSize + rowSizePreference: settingsManager.general.sidebarRowSize, + showsFavoritesSection: settingsManager.general.showsFavoritesSection ) } diff --git a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift index 0a33e8bfed..7f00637e83 100644 --- a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift @@ -23,7 +23,7 @@ internal enum DatabaseTreeMenuSpec { .command(String(localized: "Clear Recent Tables"), .clearRecents) ]) ] - case .table(let ref): + case .table(let ref), .favoriteTable(let ref): return tableSections(ref, context: context) case .temporaryTable(let ref): return temporaryTableSections(ref) @@ -70,7 +70,7 @@ internal enum DatabaseTreeMenuSpec { return [DatabaseTreeMenuSection([.command(String(localized: "Refresh"), .refreshRedisKeys)])] // A group stands for no object. An empty menu still opens as an empty frame, so it gets the // sidebar's own menu, as a status row does. - case .status, .recentSection, .temporarySection, .tableDetailGroup: + case .status, .recentSection, .favoritesSection, .temporarySection, .tableDetailGroup: return backgroundSections(context) } } diff --git a/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift b/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift index 98ac303f63..cf9ccc8ebf 100644 --- a/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift +++ b/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift @@ -16,6 +16,10 @@ enum SidebarPersistenceKey { "sidebar.\(connectionId.uuidString).recents.expanded" } + static func favoritesExpanded(connectionId: UUID) -> String { + "sidebar.\(connectionId.uuidString).favorites.expanded" + } + static func foldersExpanded(connectionId: UUID) -> String { "sidebar.\(connectionId.uuidString).folders.expanded" } diff --git a/apple/TablePro/Views/Sidebar/SidebarTreeView.swift b/apple/TablePro/Views/Sidebar/SidebarTreeView.swift index aef81b2b5b..e3c4977465 100644 --- a/apple/TablePro/Views/Sidebar/SidebarTreeView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarTreeView.swift @@ -112,7 +112,8 @@ struct SidebarTreeView: View { showSystemContainers: settingsManager.general.showSystemContainers, showsPartitions: settingsManager.general.showPartitions, showsTableDetails: settingsManager.general.showTableDetails, - rowSizePreference: settingsManager.general.sidebarRowSize + rowSizePreference: settingsManager.general.sidebarRowSize, + showsFavoritesSection: settingsManager.general.showsFavoritesSection ) } diff --git a/apple/TablePro/Views/Sidebar/SidebarView.swift b/apple/TablePro/Views/Sidebar/SidebarView.swift index ab75b0127a..16f05b8ea1 100644 --- a/apple/TablePro/Views/Sidebar/SidebarView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarView.swift @@ -484,7 +484,8 @@ struct SidebarView: View { showSystemContainers: settingsManager.general.showSystemContainers, showsPartitions: settingsManager.general.showPartitions, showsTableDetails: settingsManager.general.showTableDetails, - rowSizePreference: settingsManager.general.sidebarRowSize + rowSizePreference: settingsManager.general.sidebarRowSize, + showsFavoritesSection: settingsManager.general.showsFavoritesSection ) } diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index e0ad4131d8..5c71c86c39 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -14,13 +14,14 @@ struct NavigatorLayoutPresetTests { private static func navigatorLayout(from settings: GeneralSettings) -> GeneralSettings { var expected = settings expected.showTableDetails = true + expected.showsFavoritesSection = true expected.showsObjectsOnSelection = true expected.showsObjectToolbar = true expected.showsConnectionNavigator = true return expected } - @Test("Use Navigator Layout turns on all four features and makes Tree the default layout") + @Test("Use Navigator Layout turns on all five features and makes Tree the default layout") func applyTurnsEverythingOn() { var settings = GeneralSettings.default var layout = SidebarLayout.flat @@ -28,13 +29,14 @@ struct NavigatorLayoutPresetTests { NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &layout) #expect(settings.showTableDetails) + #expect(settings.showsFavoritesSection) #expect(settings.showsObjectsOnSelection) #expect(settings.showsObjectToolbar) #expect(settings.showsConnectionNavigator) #expect(layout == .tree) } - @Test("Use Standard Layout puts all five back to their defaults") + @Test("Use Standard Layout puts all six back to their defaults") func restorePutsTheDefaultsBack() { var settings = Self.navigatorLayout(from: .default) var layout = SidebarLayout.tree @@ -42,6 +44,7 @@ struct NavigatorLayoutPresetTests { NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &layout) #expect(settings.showTableDetails == GeneralSettings.default.showTableDetails) + #expect(settings.showsFavoritesSection == GeneralSettings.default.showsFavoritesSection) #expect(settings.showsObjectsOnSelection == GeneralSettings.default.showsObjectsOnSelection) #expect(settings.showsObjectToolbar == GeneralSettings.default.showsObjectToolbar) #expect(settings.showsConnectionNavigator == GeneralSettings.default.showsConnectionNavigator) diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeFavoritesSectionTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeFavoritesSectionTests.swift new file mode 100644 index 0000000000..c7b2257402 --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeFavoritesSectionTests.swift @@ -0,0 +1,189 @@ +// +// DatabaseTreeFavoritesSectionTests.swift +// TableProTests +// + +import AppKit +import Foundation +import SwiftUI +@testable import TablePro +import TableProPluginKit +import TableProSyncTransport +import TableProTestSupport +import Testing + +// The Favorites section: the browsed database's starred tables above Recent, each a second row for a +// table the tree already lists. +@MainActor +struct DatabaseTreeFavoritesSectionTests { + private struct Fixture { + let connection: DatabaseConnection + let coordinator: DatabaseTreeOutlineCoordinator + let favorites: FavoriteTablesStorage + let outlineView: NSOutlineView + let scrollView: NSScrollView + let viewModel: SidebarViewModel + let defaults: [EphemeralDefaults] + } + + private func makeFixture(showsFavoritesSection: Bool = true) async throws -> Fixture { + let connection = TestFixtures.makeConnection(database: "shop", type: .mysql) + let driver = MockDatabaseDriver(connection: connection) + driver.tablesToReturn = [ + TestFixtures.makeTableInfo(name: "customers"), + TestFixtures.makeTableInfo(name: "orders"), + TestFixtures.makeTableInfo(name: "v_orders", type: .view), + ] + await SchemaService.shared.load(connectionId: connection.id, driver: driver, connection: connection) + + let favoritesDefaults = try EphemeralDefaults() + let syncDefaults = try EphemeralDefaults() + let favorites = FavoriteTablesStorage( + userDefaults: favoritesDefaults.defaults, + syncTracker: SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: syncDefaults.defaults)) + ) + + let outlineView = NSOutlineView() + let scrollView = SidebarOutlineScaffold.makeScrollView( + outlineView: outlineView, + configuration: SidebarOutlineScaffold.Configuration( + columnIdentifier: "FavoritesColumn", + allowsMultipleSelection: true, + rowSizePreference: .medium + ) + ) + scrollView.frame = NSRect(x: 0, y: 0, width: 280, height: 800) + let sidebarState = SharedSidebarState.forConnection(connection.id) + sidebarState.sidebarLayout = .flat + let viewModel = SidebarViewModel( + selectedTables: .constant([]), + pendingTruncates: .constant([]), + pendingDeletes: .constant([]), + tableOperationOptions: .constant([:]), + databaseType: .mysql, + connectionId: connection.id + ) + let coordinator = DatabaseTreeOutlineCoordinator(favoriteTablesStorage: favorites) + coordinator.connectionId = connection.id + coordinator.databaseType = .mysql + coordinator.sidebarState = sidebarState + coordinator.windowState = WindowSidebarState() + coordinator.viewModel = viewModel + coordinator.activeDatabase = "shop" + coordinator.showsFavoritesSection = showsFavoritesSection + outlineView.dataSource = coordinator + outlineView.delegate = coordinator + coordinator.attach(outlineView: outlineView) + coordinator.refresh() + return Fixture( + connection: connection, + coordinator: coordinator, + favorites: favorites, + outlineView: outlineView, + scrollView: scrollView, + viewModel: viewModel, + defaults: [favoritesDefaults, syncDefaults] + ) + } + + private func tearDown(_ fixture: Fixture) async { + await SchemaService.shared.invalidate(connectionId: fixture.connection.id) + SharedSidebarState.removeConnection(fixture.connection.id) + _ = fixture.scrollView + _ = fixture.viewModel + } + + private func favoritesSection(_ fixture: Fixture) -> DatabaseTreeNode? { + fixture.coordinator.resolvedChildren(of: nil).first { node in + guard case .favoritesSection = node.kind else { return false } + return true + } + } + + private func star(_ name: String, database: String? = "shop", in fixture: Fixture) { + fixture.favorites.toggle(name: name, schema: nil, database: database, connectionId: fixture.connection.id) + } + + // The coordinator hears the change through the storage's notification, on the main queue. + private func waitForSection(_ fixture: Fixture, present: Bool) async throws { + try await waitUntil { (favoritesSection(fixture) != nil) == present } + } + + @Test("A starred table gets a Favorites section at the top of the tree, before Recent and the object groups") + func starredTableAddsTheSection() async throws { + let fixture = try await makeFixture() + #expect(favoritesSection(fixture) == nil) + + star("orders", in: fixture) + try await waitForSection(fixture, present: true) + + let section = try #require(favoritesSection(fixture)) + #expect(fixture.coordinator.resolvedChildren(of: nil).first?.id == section.id) + let rows = fixture.coordinator.resolvedChildren(of: section) + #expect(rows.map { $0.favoriteTableRef?.table.name } == ["orders"]) + #expect(rows.first?.id == DatabaseTreeNode.favoriteTableId(try #require(rows.first?.favoriteTableRef))) + await tearDown(fixture) + } + + @Test("The section lists the browsed database's favorites only, by name, and a listed view stays a view") + func sectionListsTheBrowsedDatabase() async throws { + let fixture = try await makeFixture() + star("v_orders", in: fixture) + star("customers", in: fixture) + star("events", database: "analytics", in: fixture) + try await waitUntil { + fixture.coordinator.favoriteTableRefs().count == 2 + } + + let section = try #require(favoritesSection(fixture)) + let refs = fixture.coordinator.resolvedChildren(of: section).compactMap(\.favoriteTableRef) + + #expect(refs.map(\.table.name) == ["customers", "v_orders"]) + #expect(refs.last?.table.type == .view) + #expect(refs.allSatisfy { $0.database == "shop" }) + await tearDown(fixture) + } + + @Test("With the option off, starring a table adds no section") + func optionOffShowsNoSection() async throws { + let fixture = try await makeFixture(showsFavoritesSection: false) + + star("orders", in: fixture) + fixture.coordinator.refresh() + + #expect(favoritesSection(fixture) == nil) + await tearDown(fixture) + } + + @Test("Removing the last favorite removes the section") + func unstarringTheLastRemovesTheSection() async throws { + let fixture = try await makeFixture() + star("orders", in: fixture) + try await waitForSection(fixture, present: true) + + star("orders", in: fixture) + + try await waitForSection(fixture, present: false) + await tearDown(fixture) + } + + @Test("A favorite row is selectable and opens its table; the section heading is neither") + func favoriteRowSelectsLikeATable() { + let ref = DatabaseTreeTableRef( + database: "shop", + schema: nil, + table: TableInfo(name: "orders", type: .table, rowCount: nil, schema: nil) + ) + let row = DatabaseTreeNode(id: DatabaseTreeNode.favoriteTableId(ref), kind: .favoriteTable(ref)) + let section = DatabaseTreeNode(id: DatabaseTreeNode.favoritesSectionId, kind: .favoritesSection) + + #expect(DatabaseTreeSelection.isSelectable(row.kind)) + #expect(!DatabaseTreeSelection.isSelectable(section.kind)) + #expect(DatabaseTreeSelection.tableRef(of: row) == ref) + #expect(DatabaseTreeSelection.tableRef(of: section) == nil) + #expect(section.isGroupRow) + #expect(!row.isExpandable) + #expect(row.id != DatabaseTreeNode.tableId(ref)) + #expect(row.id != DatabaseTreeNode.recentTableId(ref)) + } +} From c9f4f9abc6151e2aaaf883b69b61af9d23ffead5 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 13:47:17 +0700 Subject: [PATCH 070/123] chore(l10n): add the favorites section and listing header strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Resources/Localizable.xcstrings | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 2cab2c3aa6..f9c312f246 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -21000,6 +21000,9 @@ "Address the database server can reach this Mac at" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Adds a Favorites section above Recent with the tables you starred in the database you are browsing. Each table also stays in its own place." : { + }, "Adds a narrow strip on the window's leading edge listing every connection and database you have open, so one click switches to it." : { "localizations" : { @@ -58628,6 +58631,9 @@ } } } + }, + "Data Size" : { + }, "Data type" : { @@ -94533,6 +94539,9 @@ } } } + }, + "Index Size" : { + }, "Index type reported by the engine" : { "extractionState" : "manual", @@ -113723,6 +113732,9 @@ } } } + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { @@ -165923,6 +165935,9 @@ } } } + }, + "Show favorite tables at the top of the tree" : { + }, "Show Favorites" : { "localizations" : { @@ -204719,6 +204734,9 @@ } } } + }, + "Total Size" : { + }, "Total size in bytes" : { "localizations" : { From 66fff9a1a5b4985c7765bbd3e157c81e65368abc Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:54:12 +0700 Subject: [PATCH 071/123] feat(toolbar): select the front tab's kind and color the Objects buttons The six Objects buttons are top-level items now, not one group. Measured on macOS 27, a toolbar draws its selected item on a rounded highlight, and a label under each icon, only for a top-level item. The delegate names Tables, Views, Functions and Users as selectable, and every validation pass selects the one the front tab shows, which AppKit also reports to VoiceOver as the toolbar's selected child. Query and Backup never stay selected. Each button draws its glyph in a system hue of its own, resolved in the toolbar's appearance, while every other item keeps its template glyph. The buttons are borderless, since AppKit drops the bezel of a selectable item. The insert record moves to a new key, so an arrangement that held the former group gets the buttons once. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 2 +- .../MainSplitViewController.swift | 2 +- .../MainWindowToolbar+Actions.swift | 2 +- .../MainWindowToolbar+Context.swift | 7 +- .../MainWindowToolbar+Delegate.swift | 7 +- .../MainWindowToolbar+Items.swift | 176 ++++----- .../MainWindowToolbar+Validation.swift | 2 + .../Infrastructure/MainWindowToolbar.swift | 82 +++-- apple/TablePro/Models/UI/ToolbarContext.swift | 2 +- .../ObjectKindsToolbarTests.swift | 339 ++++++++++++------ .../Models/NavigatorLayoutPresetTests.swift | 7 +- .../MainWindowToolbarIdentifierTests.swift | 55 +-- 12 files changed, 410 insertions(+), 273 deletions(-) diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index 61eb7373c5..cc9404af76 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -174,7 +174,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Module on/off (Settings > Extensions) | UserDefaults, device-local, never synced | `AppModuleSettings` | | Routine debugger start options, per connection and field | UserDefaults, device-local | `RoutineDebugOptionStore` | | Whether the toolbar arrangement already carries the debug items | UserDefaults, device-local | `MainWindowToolbar` | -| Whether the toolbar arrangement already carries the Objects group | UserDefaults, device-local | `MainWindowToolbar` | +| Whether the toolbar arrangement already carries the Objects buttons | UserDefaults, device-local | `MainWindowToolbar` | | Trusted external links (loopback only) | UserDefaults | `ExternalConnectionTrustStore` | | Reopen the last session once after Relaunch to Update | UserDefaults, device-local, never synced, cleared by the next launch | `AppRelauncher` | | Highest plugin manifest `serial` accepted, so an older signed manifest is refused | UserDefaults, device-local, never synced | `RegistryManifestVerifier` through `RegistryClient` | diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index d8e4a9054e..77a4d08120 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -525,7 +525,7 @@ internal final class MainSplitViewController: NSSplitViewController { guard window.toolbar !== owner.managedToolbar else { return } window.toolbar = owner.managedToolbar owner.reconcileDebugItems() - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() /// The item set every window starts from is the full one, because `isHidden` is never /// persisted, so the context is applied the moment the items exist rather than on the first /// change to it. Measured on macOS 27, that moment is this assignment: `NSToolbar.items` is diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift index 3da3c89f72..d29a36881f 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Actions.swift @@ -87,7 +87,7 @@ extension MainWindowToolbar { coordinator?.frontRoutineDebugController?.stop() } - // The Objects group. Each button has its own action: the overflow menu validates an entry by its action. + // The Objects buttons. Each has its own action: the overflow menu validates an entry by its action. @objc func performShowTables(_ sender: Any?) { coordinator?.showBrowsedObjects(.table) } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift index f3092c2ace..9589fcd937 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift @@ -70,10 +70,11 @@ internal extension MainWindowToolbar { } // Every window update runs a validation pass, keystrokes included, and the listing is a plugin call that builds - // the whole statement. So the facts are read only while the group is in this toolbar, where a button shows them, + // the whole statement. So the facts are read only while an Objects button is in this toolbar, where it shows them, // and then once per browsed container and session. func objectKindFacts() -> ObjectKindFacts { - guard let coordinator, managedToolbar.items.contains(where: { $0.itemIdentifier == Self.objectKindsGroup }) + let objectKinds = Set(Self.objectKindItemIdentifiers) + guard let coordinator, managedToolbar.items.contains(where: { objectKinds.contains($0.itemIdentifier) }) else { return ObjectKindFacts() } let source = ObjectKindFactsSource(coordinator: coordinator) if let cached = objectKindFactsCache, cached.source.matches(source) { @@ -92,7 +93,7 @@ internal extension MainWindowToolbar { } } -// What the Objects group's buttons ask of the connection and the browsed container. +// What the Objects buttons ask of the connection and the browsed container. internal struct ObjectKindFacts: Equatable { var canListTables = false var offersViews = false diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift index 5fcaad57c1..d5b5230095 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Delegate.swift @@ -130,10 +130,11 @@ extension MainWindowToolbar { // Answering nil while the module is off is what prunes the controls from a saved arrangement. guard debugItemsEnabled() else { return nil } return makeDebugItem(itemIdentifier) - case Self.objectKindsGroup: - // Answering nil while the setting is off is what prunes the group from a saved arrangement. + case Self.objectTables, Self.objectViews, Self.objectFunctions, Self.objectUsers, Self.objectQuery, + Self.objectBackup: + // Answering nil while the setting is off is what prunes the buttons from a saved arrangement. guard objectKindsEnabled() else { return nil } - return makeObjectKindsGroup() + return makeObjectKindItem(itemIdentifier) default: return nil } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift index fa401ca5d2..7aa3d7cee1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift @@ -355,81 +355,85 @@ extension MainWindowToolbar { } } - /// One click to each kind of object, built like the Back/Forward group so AppKit draws it, dims a - /// button that cannot open and folds all six into one overflow entry in a narrow window. Tables, - /// Views and Functions share the sidebar's glyphs for those kinds. - func makeObjectKindsGroup() -> NSToolbarItemGroup { - makeNativeGroup( - id: Self.objectKindsGroup, - label: String(localized: "Objects"), - subitems: [ - menuOnlyItem( - id: Self.objectTables, - label: String(localized: "Tables"), - symbol: SidebarObjectKind.table.iconName, - action: #selector(performShowTables(_:)), - glyphProvider: { [weak self] in - Self.objectKindGlyph( - symbol: SidebarObjectKind.table.iconName, - label: String(localized: "Tables"), - isSelected: self?.selectedObjectKindItem() == Self.objectTables - ) - } - ), - menuOnlyItem( - id: Self.objectViews, - label: String(localized: "Views"), - symbol: SidebarObjectKind.view.iconName, - action: #selector(performShowViews(_:)), - glyphProvider: { [weak self] in - Self.objectKindGlyph( - symbol: SidebarObjectKind.view.iconName, - label: String(localized: "Views"), - isSelected: self?.selectedObjectKindItem() == Self.objectViews - ) - } - ), - menuOnlyItem( - id: Self.objectFunctions, - label: String(localized: "Functions"), - symbol: SidebarObjectKind.function.iconName, - action: #selector(performShowFunctions(_:)), - glyphProvider: { [weak self] in - Self.objectKindGlyph( - symbol: SidebarObjectKind.function.iconName, - label: String(localized: "Functions"), - isSelected: self?.selectedObjectKindItem() == Self.objectFunctions - ) - } - ), - menuOnlyItem( - id: Self.objectUsers, - label: String(localized: "Users"), - symbol: "person.2", - action: #selector(performShowUsers(_:)), - glyphProvider: { [weak self] in - Self.objectKindGlyph( - symbol: "person.2", - label: String(localized: "Users"), - isSelected: self?.selectedObjectKindItem() == Self.objectUsers - ) - } - ), - menuOnlyItem( - id: Self.objectQuery, - label: String(localized: "Query"), - symbol: "doc.text", - action: #selector(performNewQuery(_:)), - shortcut: .newTab - ), - menuOnlyItem( - id: Self.objectBackup, - label: String(localized: "Backup"), - symbol: "archivebox", - action: #selector(performBackupDatabase(_:)) - ), - ] + /// One click to each kind of object. Tables, Views and Functions share the sidebar's glyphs for those kinds. + static var objectKindButtons: [ObjectKindButton] { + [ + ObjectKindButton( + identifier: objectTables, + label: String(localized: "Tables"), + symbol: SidebarObjectKind.table.iconName, + tint: .systemBlue, + action: #selector(MainWindowToolbar.performShowTables(_:)) + ), + ObjectKindButton( + identifier: objectViews, + label: String(localized: "Views"), + symbol: SidebarObjectKind.view.iconName, + tint: .systemTeal, + action: #selector(MainWindowToolbar.performShowViews(_:)) + ), + ObjectKindButton( + identifier: objectFunctions, + label: String(localized: "Functions"), + symbol: SidebarObjectKind.function.iconName, + tint: .systemPurple, + action: #selector(MainWindowToolbar.performShowFunctions(_:)) + ), + ObjectKindButton( + identifier: objectUsers, + label: String(localized: "Users"), + symbol: "person.2", + tint: .systemOrange, + action: #selector(MainWindowToolbar.performShowUsers(_:)) + ), + ObjectKindButton( + identifier: objectQuery, + label: String(localized: "Query"), + symbol: "doc.text", + tint: .systemGreen, + action: #selector(MainWindowToolbar.performNewQuery(_:)), + shortcut: .newTab + ), + ObjectKindButton( + identifier: objectBackup, + label: String(localized: "Backup"), + symbol: "archivebox", + tint: .systemBrown, + action: #selector(MainWindowToolbar.performBackupDatabase(_:)) + ), + ] + } + + /// The hue a button draws its glyph in, and nil for every item outside the Objects run, which stays a template. + static func objectKindTint(for identifier: NSToolbarItem.Identifier) -> NSColor? { + objectKindButtons.first { $0.identifier == identifier }?.tint + } + + /// Built like every other command, so each button keeps its own action, tooltip and overflow entry and AppKit dims + /// it. Borderless because AppKit draws a selectable item without its bezel, and Query and Backup have to match. + func makeObjectKindItem(_ identifier: NSToolbarItem.Identifier) -> NSToolbarItem? { + guard let button = Self.objectKindButtons.first(where: { $0.identifier == identifier }) else { return nil } + let item = menuOnlyItem( + id: identifier, + label: button.label, + symbol: button.symbol, + action: button.action, + shortcut: button.shortcut, + glyphProvider: { Self.objectKindGlyph(button) } ) + item.isBordered = false + return item + } + + /// A system hue per kind, so the run reads at a glance. The color resolves when the glyph draws, in the toolbar's own + /// appearance, so it follows light and dark; an inactive window greys it as it greys every glyph. + static func objectKindGlyph(_ button: ObjectKindButton) -> ToolbarGlyph { + ToolbarGlyph(key: button.symbol) { + let image = NSImage(systemSymbolName: button.symbol, accessibilityDescription: button.label)? + .withSymbolConfiguration(NSImage.SymbolConfiguration(hierarchicalColor: button.tint)) + image?.isTemplate = false + return image + } } /// The button for what the front tab shows. Query and Backup start something new, so neither stays selected. @@ -454,19 +458,6 @@ extension MainWindowToolbar { return Self.selectedObjectKindItem(tabType: tab?.tabType, listingKind: tab?.display.listingKind) } - /// The selected kind draws its glyph in the accent color, the way Xcode's navigator bar marks the navigator on - /// screen. Measured on macOS 27, a toolbar item group draws no selected state for the buttons it holds, whatever - /// its selection mode. - static func objectKindGlyph(symbol: String, label: String, isSelected: Bool) -> ToolbarGlyph { - ToolbarGlyph(key: isSelected ? "selected" : "plain") { - let image = NSImage(systemSymbolName: symbol, accessibilityDescription: label) - guard isSelected else { return image } - let tinted = image?.withSymbolConfiguration(NSImage.SymbolConfiguration(paletteColors: [.controlAccentColor])) - tinted?.isTemplate = false - return tinted - } - } - // MARK: - Helpers /// The label is what the customization palette and the overflow menu show, so it stays short. @@ -545,3 +536,14 @@ extension MainWindowToolbar { item.visibilityPriority = .high } } + +/// One button of the Objects run: what it draws and what it sends. +@MainActor +internal struct ObjectKindButton { + let identifier: NSToolbarItem.Identifier + let label: String + let symbol: String + let tint: NSColor + let action: Selector + var shortcut: ShortcutAction? +} diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Validation.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Validation.swift index dbfc4798ee..8d01474565 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Validation.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Validation.swift @@ -41,6 +41,8 @@ internal final class ContextValidatedToolbar: NSToolbar { return } owner.withinValidationPass { super.validateVisibleItems() } + // The selected Objects button rides the pass every window update runs, as each item's enabled state does. + owner.refreshObjectKindSelection() } } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index f9f9da5ef8..3338757ece 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -91,14 +91,14 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal var debugItemsRecord = ToolbarDebugItemsRecord() - // Whether Settings puts the Objects group in the toolbar; it is vended only then, so turning it off prunes it. + // Whether Settings puts the Objects buttons in the toolbar; they are vended only then, so turning it off prunes them. internal var objectKindsEnabled: @MainActor () -> Bool = { AppSettingsManager.shared.general.showsObjectToolbar } internal var objectKindsRecord = ToolbarObjectKindsRecord() - // The Objects group's facts and what they were read from, kept from one validation pass to the next. + // The Objects buttons' facts and what they were read from, kept from one validation pass to the next. internal var objectKindFactsCache: ObjectKindFactsCache? /// `NSMenu.delegate` is weak, and the safe-mode control's menu is built here rather than by the @@ -244,6 +244,7 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { tabStateObservation = coordinator.tabManager.onMainActorChange { [weak self] in guard let self, self.isObserving(generation, coordinatorIdentifier) else { return } self.refreshContext() + self.refreshObjectKindSelection() } rewindAvailabilityObservation = coordinator.services.queryHistoryManager.rewindAvailability .onMainActorChange { [weak self] in @@ -444,8 +445,11 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { ] // Xcode's pair. The steps live in the debug tab's own bar and the palette, which keeps a debug tab at eight hit targets. nonisolated static let debugDefaultItemIdentifiers: [NSToolbarItem.Identifier] = [debugContinue, debugStop] - // The Objects group a General setting adds. Its own identifiers, so Query never collides with New Tab in one toolbar. - nonisolated static let objectKindsGroup = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds") + // The Objects buttons a General setting adds. Their own identifiers, so Query never collides with New Tab in one + // toolbar. Top-level items, not one group: measured on macOS 27, a toolbar draws the selected item and a label under + // each icon only for a top-level item. A group of items draws its own label alone and no selection, whatever its + // selection mode, and the segmented group that does draw a selection has no label per segment. An arrangement saved + // with the former group identifier drops it, since no delegate vends it now. nonisolated static let objectTables = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.tables") nonisolated static let objectViews = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.views") nonisolated static let objectFunctions = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds.functions") @@ -455,6 +459,10 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { nonisolated static let objectKindItemIdentifiers: [NSToolbarItem.Identifier] = [ objectTables, objectViews, objectFunctions, objectUsers, objectQuery, objectBackup, ] + // The buttons that name what the front tab shows. Query and Backup start something new, so neither stays selected. + nonisolated static let selectableObjectKindItemIdentifiers: [NSToolbarItem.Identifier] = [ + objectTables, objectViews, objectFunctions, objectUsers, + ] // MARK: - NSToolbarDelegate @@ -550,11 +558,17 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { allowed += Self.debugItemIdentifiers } if objectKindsEnabled() { - allowed.append(Self.objectKindsGroup) + allowed += Self.objectKindItemIdentifiers } return allowed } + // Always the four, so the answer holds however early AppKit asks. An identifier with no item in the toolbar draws + // nothing, and `refreshObjectKindSelection()` selects one only while the setting is on. + internal func toolbarSelectableItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + Self.selectableObjectKindItemIdentifiers + } + // Replaced under test, where no window hosts the toolbar. internal var isInWindow: @MainActor () -> Bool = { false } @@ -571,57 +585,47 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal static func applyObjectToolbarSettingChange() { for window in NSApp.windows { guard let owner = window.toolbar?.delegate as? MainWindowToolbar else { continue } - owner.reconcileObjectKindsGroup() - // A group inserted now takes its enabled state at once rather than on the next window update. AppKit places + owner.reconcileObjectKindItems() + // Buttons inserted now take their enabled state at once rather than on the next window update. AppKit places // an inserted item at the next layout and a pass validates only placed items, so the window lays out first. window.layoutIfNeeded() owner.managedToolbar.validateVisibleItems() } } - // Run when the module changes and when the toolbar reaches a window, after it restored its saved arrangement: a - // change made while no connection window was open would otherwise never reach the arrangement. Inserted or removed - // in place, because reassigning the toolbar rebuilds the whole titlebar. - internal func reconcileDebugItems() { - guard windowController?.view.window != nil || isInWindow() else { return } - let wanted = debugItemsEnabled() - guard debugItemsRecord.isApplied != wanted else { return } - debugItemsRecord.record(wanted) - let debugIdentifiers = Set(Self.debugItemIdentifiers) - if wanted { - let present = managedToolbar.items.contains { debugIdentifiers.contains($0.itemIdentifier) } - if !present, let index = managedToolbar.items.firstIndex(where: { $0.itemIdentifier == Self.actions }) { - for (offset, identifier) in Self.debugDefaultItemIdentifiers.enumerated() { - managedToolbar.insertItem(withItemIdentifier: identifier, at: index + offset) - } - } - } else { - for index in managedToolbar.items.indices.reversed() - where debugIdentifiers.contains(managedToolbar.items[index].itemIdentifier) { - managedToolbar.removeItem(at: index) - } - } - } - - // The debug items' rule for the Objects group: written once per change of the setting, so a group the user took out - // stays out. It goes first in the content area, after the sidebar's strip, or first of all without that divider. - internal func reconcileObjectKindsGroup() { + // The debug items' rule for the Objects buttons: written once per change of the setting, so a button the user took + // out stays out. They go first in the content area, after the sidebar's strip, or first of all without that divider. + internal func reconcileObjectKindItems() { guard windowController?.view.window != nil || isInWindow() else { return } let wanted = objectKindsEnabled() guard objectKindsRecord.isApplied != wanted else { return } objectKindsRecord.record(wanted) + let objectKinds = Set(Self.objectKindItemIdentifiers) if wanted { // AppKit throws on a second item with an identifier the toolbar already holds. - guard !managedToolbar.items.contains(where: { $0.itemIdentifier == Self.objectKindsGroup }) else { return } + let present = Set(managedToolbar.items.map { $0.itemIdentifier }) let separator = managedToolbar.items.firstIndex { $0.itemIdentifier == .sidebarTrackingSeparator } - managedToolbar.insertItem(withItemIdentifier: Self.objectKindsGroup, at: separator.map { $0 + 1 } ?? 0) + var index = separator.map { $0 + 1 } ?? 0 + for identifier in Self.objectKindItemIdentifiers where !present.contains(identifier) { + managedToolbar.insertItem(withItemIdentifier: identifier, at: index) + index += 1 + } } else { for index in managedToolbar.items.indices.reversed() - where managedToolbar.items[index].itemIdentifier == Self.objectKindsGroup { + where objectKinds.contains(managedToolbar.items[index].itemIdentifier) { managedToolbar.removeItem(at: index) } } } + + // AppKit draws the toolbar's selected item on a rounded highlight and reports it to VoiceOver as the toolbar's + // selected child. AppKit also selects a selectable button when it is clicked, so the front tab decides here, and a + // click whose tab did not follow is put right on the next pass. Written only when it moves. + internal func refreshObjectKindSelection() { + let selected = objectKindsEnabled() ? selectedObjectKindItem() : nil + guard managedToolbar.selectedItemIdentifier != selected else { return } + managedToolbar.selectedItemIdentifier = selected + } } // The module state last written into the shared arrangement. Toolbars sharing an identifier copy each other's edits, so @@ -648,8 +652,10 @@ internal struct ToolbarDebugItemsRecord { } // The General setting last written into the shared arrangement, kept for the same reasons as the debug items' record. +// Not the former group's key: an arrangement that recorded the group lost it when the group stopped being vended, so it +// takes the buttons once. internal struct ToolbarObjectKindsRecord { - static let key = "com.TablePro.main.toolbar.v4.objectKinds" + static let key = "com.TablePro.main.toolbar.v4.objectKindItems" let defaults: UserDefaults diff --git a/apple/TablePro/Models/UI/ToolbarContext.swift b/apple/TablePro/Models/UI/ToolbarContext.swift index 3133a911df..013f47aacc 100644 --- a/apple/TablePro/Models/UI/ToolbarContext.swift +++ b/apple/TablePro/Models/UI/ToolbarContext.swift @@ -47,7 +47,7 @@ internal struct ToolbarContext: Equatable { internal let canStopDebugging: Bool internal let isPresentingSheet: Bool - // What the connection supports and the browsed container offers, for the Objects group's buttons. + // What the connection supports and the browsed container offers, for the Objects buttons. // Enablement only, never visibility. internal let canListTables: Bool internal let offersViews: Bool diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index 11d95af249..4964448504 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -9,7 +9,7 @@ import SwiftUI import TableProPluginKit import Testing -/// The optional Objects group: six buttons that reach each kind of object in one click. +/// The optional Objects buttons: six top-level items that reach each kind of object in one click. @MainActor struct ObjectKindsToolbarTests { /// A private identifier with autosave off: the test host shares the app's defaults, so a toolbar @@ -22,26 +22,23 @@ struct ObjectKindsToolbarTests { return owner } - private static func group(from owner: MainWindowToolbar) throws -> NSToolbarItemGroup { + /// The item the delegate vends, as Customize Toolbar and a restored arrangement ask for it. + private static func item( + _ identifier: NSToolbarItem.Identifier, + of owner: MainWindowToolbar + ) throws -> NSToolbarItem { try #require( - owner.toolbar( - owner.managedToolbar, - itemForItemIdentifier: MainWindowToolbar.objectKindsGroup, - willBeInsertedIntoToolbar: true - ) as? NSToolbarItemGroup + owner.toolbar(owner.managedToolbar, itemForItemIdentifier: identifier, willBeInsertedIntoToolbar: true) ) } - private static func subitem( - _ identifier: NSToolbarItem.Identifier, - of owner: MainWindowToolbar - ) throws -> NSToolbarItem { - try #require(group(from: owner).subitems.first { $0.itemIdentifier == identifier }) + private static func items(of owner: MainWindowToolbar) throws -> [NSToolbarItem] { + try MainWindowToolbar.objectKindItemIdentifiers.map { try item($0, of: owner) } } /// What a click does: the button's own action, sent to the button's own target. private static func press(_ identifier: NSToolbarItem.Identifier, on owner: MainWindowToolbar) throws { - let item = try subitem(identifier, of: owner) + let item = try item(identifier, of: owner) let action = try #require(item.action) #expect(NSApp.sendAction(action, to: item.target, from: item), "\(identifier.rawValue) reached no target") } @@ -60,33 +57,32 @@ struct ObjectKindsToolbarTests { return actions } - // MARK: - The group + // MARK: - The buttons - /// A group with real subitems and no view is drawn by AppKit, so it dims a button, answers the - /// display mode and collapses into one overflow entry when the window narrows. - @Test("Each button is a named AppKit glyph routed to the toolbar") - func subitemsAreDrawnByAppKit() throws { + /// An image item with no view is drawn by AppKit, so it dims, answers the display mode with a + /// label under its icon, shows the toolbar's selection and goes to the overflow menu on its own. + @Test("Each button is a named, borderless AppKit glyph routed to the toolbar") + func buttonsAreDrawnByAppKit() throws { let owner = Self.owner() - let group = try Self.group(from: owner) - #expect(group.label == String(localized: "Objects")) - #expect(group.controlRepresentation == .automatic) - #expect(group.visibilityPriority == .high) - for item in group.subitems { + for item in try Self.items(of: owner) { let name = item.itemIdentifier.rawValue + #expect(!(item is NSToolbarItemGroup), "\(name) must be a top-level item, or no label or selection draws") #expect(item.view == nil, "\(name) must not be view-backed") #expect(!item.label.isEmpty, "\(name) needs a label") #expect(item.image != nil, "\(name) names no symbol that exists") #expect(item.target === owner, "\(name) must route through the toolbar") #expect(item.action != nil, "\(name) has no action") + #expect(item.visibilityPriority == .high, "\(name) leaves the titlebar before the commands") + #expect(!item.isBordered, "\(name) must match the selectable buttons, which AppKit draws without a bezel") } } @Test("Query advertises its shortcut, and every button its name") func queryAdvertisesItsShortcut() throws { let owner = Self.owner() - let query = try Self.subitem(MainWindowToolbar.objectQuery, of: owner) - let tables = try Self.subitem(MainWindowToolbar.objectTables, of: owner) + let query = try Self.item(MainWindowToolbar.objectQuery, of: owner) + let tables = try Self.item(MainWindowToolbar.objectTables, of: owner) #expect(query.toolTip == AppSettingsManager.shared.keyboard.shortcutHint(String(localized: "Query"), for: .newTab)) #expect(query.toolTip != String(localized: "Query"), "The hint adds the key that runs the command") @@ -98,7 +94,7 @@ struct ObjectKindsToolbarTests { @Test("Each overflow entry validates as its own button") func overflowEntriesValidateAsTheirButtons() throws { let owner = Self.owner() - for item in try Self.group(from: owner).subitems { + for item in try Self.items(of: owner) { let entry = try #require(item.menuFormRepresentation) #expect(owner.itemIdentifier(forMenuFormAction: item.action) == item.itemIdentifier) #expect(!owner.validateMenuItem(entry), "\(item.itemIdentifier.rawValue) is live with no session") @@ -107,23 +103,54 @@ struct ObjectKindsToolbarTests { // MARK: - Selection - @Test("The button for the front tab's kind draws in the accent color and the others stay template glyphs") - func frontKindDrawsInAccent() throws { - let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .mysql)) + /// AppKit draws the toolbar's selected item on a rounded highlight and reports it to VoiceOver as + /// the toolbar's selected child, so the selected identifier is the whole visual state. + @Test("The toolbar selects the button for the front tab's kind, and none once a query tab is in front") + func theFrontKindIsSelected() throws { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .postgresql)) + let actions = Self.makeActions(for: fixture) let owner = Self.owner() owner.repoint(to: fixture.coordinator) - let group = try Self.group(from: owner) + + // Users first: with a tab already open, Users & Roles opens through the window manager, which this fixture lacks. + try Self.press(MainWindowToolbar.objectUsers, on: owner) + owner.refreshObjectKindSelection() + #expect(owner.managedToolbar.selectedItemIdentifier == MainWindowToolbar.objectUsers) try Self.press(MainWindowToolbar.objectViews, on: owner) - group.subitems.forEach { $0.validate() } + owner.refreshObjectKindSelection() + #expect(owner.managedToolbar.selectedItemIdentifier == MainWindowToolbar.objectViews) - func image(_ identifier: NSToolbarItem.Identifier) -> NSImage? { - group.subitems.first { $0.itemIdentifier == identifier }?.image - } - #expect(owner.selectedObjectKindItem() == MainWindowToolbar.objectViews) - #expect(image(MainWindowToolbar.objectViews)?.isTemplate == false) - #expect(image(MainWindowToolbar.objectTables)?.isTemplate == true) - #expect(image(MainWindowToolbar.objectFunctions)?.isTemplate == true) + try Self.press(MainWindowToolbar.objectQuery, on: owner) + owner.refreshObjectKindSelection() + #expect(owner.managedToolbar.selectedItemIdentifier == nil, "Query starts something new, so nothing stays selected") + withExtendedLifetime(actions) {} + } + + @Test("With the setting off the toolbar selects nothing") + func settingOffSelectsNothing() throws { + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .mysql)) + let owner = Self.owner(objectsOn: false) + owner.repoint(to: fixture.coordinator) + + fixture.coordinator.showBrowsedObjects(.table) + owner.refreshObjectKindSelection() + + #expect(owner.selectedObjectKindItem() == MainWindowToolbar.objectTables) + #expect(owner.managedToolbar.selectedItemIdentifier == nil) + } + + @Test("Only the four kinds a tab can show are selectable") + func onlyTheKindsAreSelectable() { + let owner = Self.owner() + let selectable = owner.toolbarSelectableItemIdentifiers(owner.managedToolbar) + + #expect(selectable == [ + MainWindowToolbar.objectTables, MainWindowToolbar.objectViews, + MainWindowToolbar.objectFunctions, MainWindowToolbar.objectUsers, + ]) + #expect(!selectable.contains(MainWindowToolbar.objectQuery)) + #expect(!selectable.contains(MainWindowToolbar.objectBackup)) } @Test("The selected button is the kind the front tab shows, and none for a tab no button opens") @@ -139,6 +166,41 @@ struct ObjectKindsToolbarTests { #expect(select(nil, nil) == nil) } + // MARK: - Colors + + /// Each kind wears a system hue, so the run reads at a glance; every other control keeps the + /// system's monochrome template glyph. + @Test("Only the Objects buttons draw in color") + func onlyTheObjectButtonsDrawInColor() throws { + let owner = Self.owner() + let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) + let vended = owner.toolbarAllowedItemIdentifiers(owner.managedToolbar) + .filter { !$0.rawValue.hasPrefix("NSToolbar") } + .compactMap { owner.toolbar(owner.managedToolbar, itemForItemIdentifier: $0, willBeInsertedIntoToolbar: true) } + .flatMap { item -> [NSToolbarItem] in [item] + ((item as? NSToolbarItemGroup)?.subitems ?? []) } + + #expect(objectKinds.isSubset(of: Set(vended.map { $0.itemIdentifier }))) + for item in vended { + guard let image = item.image else { continue } + let name = item.itemIdentifier.rawValue + if objectKinds.contains(item.itemIdentifier) { + #expect(!image.isTemplate, "\(name) should draw in its hue") + #expect(MainWindowToolbar.objectKindTint(for: item.itemIdentifier) != nil, "\(name) has no hue") + } else { + #expect(image.isTemplate, "\(name) should stay a monochrome template") + #expect(MainWindowToolbar.objectKindTint(for: item.itemIdentifier) == nil, "\(name) should have no hue") + } + } + } + + @Test("Each kind has a hue of its own") + func eachKindHasItsOwnHue() { + let tints = MainWindowToolbar.objectKindItemIdentifiers.compactMap { MainWindowToolbar.objectKindTint(for: $0) } + + #expect(tints.count == MainWindowToolbar.objectKindItemIdentifiers.count) + #expect(Set(tints).count == tints.count) + } + // MARK: - Routing @Test("Tables, Views and Functions open the browsed container's objects on their kind", arguments: [ @@ -206,23 +268,25 @@ struct ObjectKindsToolbarTests { // MARK: - What the connection supports - /// Where Settings puts the group: what the toolbar's own facts are read for. - private static func insertGroup(into owner: MainWindowToolbar) { - owner.managedToolbar.insertItem(withItemIdentifier: MainWindowToolbar.objectKindsGroup, at: 0) + /// Where Settings puts the buttons: what the toolbar's own facts are read for. + private static func insertButtons(into owner: MainWindowToolbar) { + for (index, identifier) in MainWindowToolbar.objectKindItemIdentifiers.enumerated() { + owner.managedToolbar.insertItem(withItemIdentifier: identifier, at: index) + } } /// The context a toolbar pointed at a connection of this engine answers from. No driver is /// installed, so the engine's curated capabilities are what the context can see. private static func context( for type: DatabaseType, - groupInToolbar: Bool = true, + buttonsInToolbar: Bool = true, settingOn: Bool = true ) -> ToolbarContext { let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: type)) let actions = makeActions(for: fixture) let owner = owner() - if groupInToolbar { - insertGroup(into: owner) + if buttonsInToolbar { + insertButtons(into: owner) } owner.objectKindsEnabled = { settingOn } owner.repoint(to: fixture.coordinator) @@ -231,8 +295,8 @@ struct ObjectKindsToolbarTests { return context } - @Test("With the group in the toolbar, the context reads what the engine supports") - func contextReadsTheEngineWhileTheGroupIsShown() { + @Test("With the buttons in the toolbar, the context reads what the engine supports") + func contextReadsTheEngineWhileTheButtonsAreShown() { let postgres = Self.context(for: .postgresql) #expect(postgres.supportsBackup) #expect(!postgres.canListTables, "With no driver the engine builds no listing") @@ -245,12 +309,12 @@ struct ObjectKindsToolbarTests { #expect(!Self.context(for: .sqlite).offersFunctions) } - /// Nothing but the group reads these, and the listing is a plugin call on every validation pass. - /// The setting is not enough: a group taken out with Customize Toolbar has no button to validate. - @Test("Without the group in the toolbar, the context asks the connection nothing for it", arguments: [true, false]) - func contextAsksNothingWithoutTheGroup(settingOn: Bool) { + /// Nothing but the buttons read these, and the listing is a plugin call on every validation pass. + /// The setting is not enough: buttons taken out with Customize Toolbar have nothing to validate. + @Test("Without the buttons in the toolbar, the context asks the connection nothing for them", arguments: [true, false]) + func contextAsksNothingWithoutTheButtons(settingOn: Bool) { for type in [DatabaseType.postgresql, .mongodb] { - let context = Self.context(for: type, groupInToolbar: false, settingOn: settingOn) + let context = Self.context(for: type, buttonsInToolbar: false, settingOn: settingOn) #expect(!context.canListTables, "\(type.rawValue)") #expect(!context.offersViews, "\(type.rawValue)") #expect(!context.offersFunctions, "\(type.rawValue)") @@ -275,7 +339,7 @@ struct ObjectKindsToolbarTests { defer { DatabaseManager.shared.removeSession(for: connection.id) } let fixture = CoordinatorFixture(connection: connection) let owner = Self.owner() - Self.insertGroup(into: owner) + Self.insertButtons(into: owner) owner.repoint(to: fixture.coordinator) #expect(owner.currentContext().canListTables) @@ -370,7 +434,7 @@ struct ObjectKindsToolbarTests { let fixture = CoordinatorFixture(connection: connection) fixture.coordinator.toolbarState.connectionState = .connected let owner = owner() - insertGroup(into: owner) + insertButtons(into: owner) owner.repoint(to: fixture.coordinator) let context = withExtendedLifetime(fixture) { owner.currentContext() } return Set(MainWindowToolbar.objectKindItemIdentifiers.filter { identifier in @@ -433,7 +497,7 @@ struct ObjectKindsToolbarTests { let fixture = CoordinatorFixture(connection: connection) fixture.coordinator.toolbarState.connectionState = .connected let owner = Self.owner() - Self.insertGroup(into: owner) + Self.insertButtons(into: owner) owner.repoint(to: fixture.coordinator) #expect(!owner.currentContext().offersViews) @@ -464,9 +528,9 @@ struct ObjectKindsToolbarTests { // MARK: - Insert and remove /// A restored arrangement: the app's own items, without spaces, on a private identifier that - /// never autosaves. Built with the group allowed, so `extra` can hold it, then switched to the + /// never autosaves. Built with the buttons allowed, so `extra` can hold them, then switched to the /// setting the case names. AppKit builds the sidebar tracking separator only over a split view - /// in a window, so this arrangement has none; `separatorPlacesTheGroupInAWindow` covers it. + /// in a window, so this arrangement has none; `separatorPlacesTheButtonsInAWindow` covers it. private static func restoredToolbar( including extra: [NSToolbarItem.Identifier] = [], settingOn: Bool, @@ -489,55 +553,75 @@ struct ObjectKindsToolbarTests { toolbar.items.map { $0.itemIdentifier } } - private static func groupCount(in toolbar: NSToolbar) -> Int { - identifiers(of: toolbar).filter { $0 == MainWindowToolbar.objectKindsGroup }.count + private static func buttons(in toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) + return identifiers(of: toolbar).filter { objectKinds.contains($0) } } - @Test("Turning the setting on puts the group in once") - func turningOnInsertsTheGroupOnce() throws { + @Test("Turning the setting on puts the six buttons in once, in order") + func turningOnInsertsTheButtonsOnce() throws { let storage = try EphemeralDefaults() let record = ToolbarObjectKindsRecord(defaults: storage.defaults) #expect(!record.isApplied) let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() - #expect(Self.groupCount(in: toolbar) == 1) + #expect(Self.buttons(in: toolbar) == MainWindowToolbar.objectKindItemIdentifiers) #expect(ToolbarObjectKindsRecord(defaults: storage.defaults).isApplied) let (laterOwner, laterToolbar) = Self.restoredToolbar(settingOn: true, record: record) - laterOwner.reconcileObjectKindsGroup() - #expect(Self.groupCount(in: laterToolbar) == 0, "The change was already written into the arrangement") + laterOwner.reconcileObjectKindItems() + #expect(Self.buttons(in: laterToolbar).isEmpty, "The change was already written into the arrangement") } - @Test("Turning the setting off takes the group out") - func turningOffRemovesTheGroup() throws { + /// An arrangement saved with the former group recorded it under the former key, so the buttons + /// still arrive once in place of the group the delegate no longer vends. + @Test("The record is not the former group's, so an arrangement that held the group gets the buttons") + func theRecordIsTheButtonsOwn() throws { + let storage = try EphemeralDefaults() + storage.defaults.set(true, forKey: "com.TablePro.main.toolbar.v4.objectKinds") + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + #expect(!record.isApplied) + let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) + + owner.reconcileObjectKindItems() + + #expect(Self.buttons(in: toolbar) == MainWindowToolbar.objectKindItemIdentifiers) + } + + @Test("Turning the setting off takes every button out") + func turningOffRemovesTheButtons() throws { let storage = try EphemeralDefaults() let record = ToolbarObjectKindsRecord(defaults: storage.defaults) record.record(true) let (owner, toolbar) = Self.restoredToolbar( - including: [MainWindowToolbar.objectKindsGroup], + including: MainWindowToolbar.objectKindItemIdentifiers, settingOn: false, record: record ) - #expect(Self.groupCount(in: toolbar) == 1) + #expect(Self.buttons(in: toolbar).count == 6) - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() - #expect(Self.groupCount(in: toolbar) == 0) + #expect(Self.buttons(in: toolbar).isEmpty) #expect(!record.isApplied) } - @Test("A group the user took out with Customize Toolbar stays out") - func aRemovedGroupStaysRemoved() throws { + @Test("Buttons the user took out with Customize Toolbar stay out") + func removedButtonsStayRemoved() throws { let storage = try EphemeralDefaults() let record = ToolbarObjectKindsRecord(defaults: storage.defaults) record.record(true) - let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) + let (owner, toolbar) = Self.restoredToolbar( + including: [MainWindowToolbar.objectTables, MainWindowToolbar.objectQuery], + settingOn: true, + record: record + ) - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() - #expect(Self.groupCount(in: toolbar) == 0) + #expect(Self.buttons(in: toolbar) == [MainWindowToolbar.objectTables, MainWindowToolbar.objectQuery]) #expect(record.isApplied) } @@ -548,7 +632,7 @@ struct ObjectKindsToolbarTests { let (owner, toolbar) = Self.restoredToolbar(settingOn: false, record: record) let before = Self.identifiers(of: toolbar) - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() #expect(Self.identifiers(of: toolbar) == before) #expect(!record.isApplied) @@ -556,26 +640,29 @@ struct ObjectKindsToolbarTests { } /// AppKit throws when a second item with an identifier already in the toolbar is added. - @Test("A group already in the arrangement is not added a second time") - func presentGroupIsNotInsertedAgain() throws { + @Test("A button already in the arrangement is not added a second time", arguments: [ + [MainWindowToolbar.objectViews.rawValue], + MainWindowToolbar.objectKindItemIdentifiers.map(\.rawValue), + ]) + func presentButtonsAreNotInsertedAgain(present: [String]) throws { let storage = try EphemeralDefaults() let record = ToolbarObjectKindsRecord(defaults: storage.defaults) let (owner, toolbar) = Self.restoredToolbar( - including: [MainWindowToolbar.objectKindsGroup], + including: present.map { NSToolbarItem.Identifier($0) }, settingOn: true, record: record ) - #expect(Self.groupCount(in: toolbar) == 1) - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() - #expect(Self.groupCount(in: toolbar) == 1) + #expect(Set(Self.buttons(in: toolbar)) == Set(MainWindowToolbar.objectKindItemIdentifiers)) + #expect(Self.buttons(in: toolbar).count == MainWindowToolbar.objectKindItemIdentifiers.count) #expect(record.isApplied) } /// The connection window's own toolbar, whose split view gives it the sidebar's divider. - @Test("In a connection window the group starts the content area, right after the sidebar's strip") - func separatorPlacesTheGroupInAWindow() throws { + @Test("In a connection window the buttons start the content area, right after the sidebar's strip") + func separatorPlacesTheButtonsInAWindow() throws { let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_512, height: 861)) defer { fixture.tearDown() } let storage = try EphemeralDefaults() @@ -583,12 +670,12 @@ struct ObjectKindsToolbarTests { owner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) owner.objectKindsEnabled = { true } - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() let identifiers = Self.identifiers(of: owner.managedToolbar) let separator = try #require(identifiers.firstIndex(of: .sidebarTrackingSeparator)) - #expect(identifiers.dropFirst(separator + 1).first == MainWindowToolbar.objectKindsGroup) - #expect(Self.groupCount(in: owner.managedToolbar) == 1) + #expect(Array(identifiers.dropFirst(separator + 1).prefix(6)) == MainWindowToolbar.objectKindItemIdentifiers) + #expect(Self.buttons(in: owner.managedToolbar) == MainWindowToolbar.objectKindItemIdentifiers) } /// The resolver answering is not enough: AppKit has to ask it for each subitem and write the @@ -604,17 +691,17 @@ struct ObjectKindsToolbarTests { let owner = fixture.toolbarOwner owner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) owner.objectKindsEnabled = { true } - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() // AppKit places an inserted item at the next layout, and validates only what it has placed. fixture.window.layoutIfNeeded() let toolbar = try #require(fixture.window.toolbar) - let group = try #require( - toolbar.items.first { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } as? NSToolbarItemGroup - ) - let drawn = (toolbar.visibleItems ?? []).map { $0.itemIdentifier } - #expect(drawn.contains(MainWindowToolbar.objectKindsGroup), "The group went to the overflow menu") + let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) + let buttons = toolbar.items.filter { objectKinds.contains($0.itemIdentifier) } + #expect(buttons.count == objectKinds.count) + let drawn = Set((toolbar.visibleItems ?? []).map { $0.itemIdentifier }) + #expect(objectKinds.isSubset(of: drawn), "A button went to the overflow menu") let state = try #require(owner.coordinator?.toolbarState) - let enabled = { Set(group.subitems.filter { $0.isEnabled }.map { $0.itemIdentifier }) } + let enabled = { Set(buttons.filter { $0.isEnabled }.map { $0.itemIdentifier }) } state.connectionState = .disconnected toolbar.validateVisibleItems() @@ -632,16 +719,41 @@ struct ObjectKindsToolbarTests { #expect(!enabled().contains(MainWindowToolbar.objectTables)) } - @Test("Without the sidebar tracking separator the group goes in at the leading edge") + @Test("Without the sidebar tracking separator the buttons go in at the leading edge") func insertsAtTheLeadingEdgeWithoutTheSeparator() throws { let storage = try EphemeralDefaults() let record = ToolbarObjectKindsRecord(defaults: storage.defaults) let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) - owner.reconcileObjectKindsGroup() + owner.reconcileObjectKindItems() - #expect(toolbar.items.first?.itemIdentifier == MainWindowToolbar.objectKindsGroup) - #expect(Self.groupCount(in: toolbar) == 1) + #expect(Array(Self.identifiers(of: toolbar).prefix(6)) == MainWindowToolbar.objectKindItemIdentifiers) + } + + /// The pass a window update runs is what keeps the selection on the front tab's kind. + @Test("A validation pass selects the front tab's kind") + func aValidationPassSelectsTheFrontKind() throws { + let fixture = try OffscreenConnectionWindow( + size: CGSize(width: 1_512, height: 861), + connectedTo: TestFixtures.makeConnection(name: "Objects selection", database: "shop", type: .mysql) + ) + defer { fixture.tearDown() } + let storage = try EphemeralDefaults() + let owner = fixture.toolbarOwner + owner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) + owner.objectKindsEnabled = { true } + owner.reconcileObjectKindItems() + fixture.window.layoutIfNeeded() + let toolbar = try #require(fixture.window.toolbar) + let coordinator = try #require(owner.coordinator) + + coordinator.showBrowsedObjects(.function) + toolbar.validateVisibleItems() + #expect(toolbar.selectedItemIdentifier == MainWindowToolbar.objectFunctions) + + coordinator.showBrowsedObjects(.table) + toolbar.validateVisibleItems() + #expect(toolbar.selectedItemIdentifier == MainWindowToolbar.objectTables) } /// A change made while no connection window is open is left for the first window that opens, @@ -653,13 +765,13 @@ struct ObjectKindsToolbarTests { let (owner, toolbar) = Self.restoredToolbar(settingOn: true, record: record) owner.isInWindow = { false } - owner.reconcileObjectKindsGroup() - #expect(Self.groupCount(in: toolbar) == 0) + owner.reconcileObjectKindItems() + #expect(Self.buttons(in: toolbar).isEmpty) #expect(!record.isApplied) owner.isInWindow = { true } - owner.reconcileObjectKindsGroup() - #expect(Self.groupCount(in: toolbar) == 1) + owner.reconcileObjectKindItems() + #expect(Self.buttons(in: toolbar) == MainWindowToolbar.objectKindItemIdentifiers) #expect(record.isApplied) } } @@ -670,7 +782,7 @@ extension GlobalStateSuites { @MainActor struct ObjectKindsSettingTests { @Test( - "The General setting adds the group to an open window and takes it away", + "The General setting adds the buttons to an open window and takes them away", .appSettings { $0.general.showsObjectToolbar = false } ) func settingReachesAnOpenWindow() throws { @@ -679,25 +791,22 @@ extension GlobalStateSuites { let storage = try EphemeralDefaults() fixture.toolbarOwner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) let toolbar = try #require(fixture.window.toolbar) - let hasGroup = { toolbar.items.contains { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } } - #expect(!hasGroup()) + let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) + let buttons = { toolbar.items.filter { objectKinds.contains($0.itemIdentifier) } } + #expect(buttons().isEmpty) AppSettingsManager.shared.general.showsObjectToolbar = true - #expect(hasGroup(), "Turning the setting on reaches the open window") + #expect(buttons().count == objectKinds.count, "Turning the setting on reaches the open window") let identifiers = toolbar.items.map { $0.itemIdentifier } let separator = try #require(identifiers.firstIndex(of: .sidebarTrackingSeparator)) - #expect(identifiers.dropFirst(separator + 1).first == MainWindowToolbar.objectKindsGroup) - // This window has no connection, so the group arrives dimmed rather than live until the next update. - let group = try #require( - toolbar.items.first { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } as? NSToolbarItemGroup - ) - #expect(!group.subitems.isEmpty) - for subitem in group.subitems { - #expect(!subitem.isEnabled, "\(subitem.itemIdentifier.rawValue) is live with no connection") + #expect(Array(identifiers.dropFirst(separator + 1).prefix(6)) == MainWindowToolbar.objectKindItemIdentifiers) + // This window has no connection, so the buttons arrive dimmed rather than live until the next update. + for button in buttons() { + #expect(!button.isEnabled, "\(button.itemIdentifier.rawValue) is live with no connection") } AppSettingsManager.shared.general.showsObjectToolbar = false - #expect(!hasGroup(), "Turning it off takes the group away") + #expect(buttons().isEmpty, "Turning it off takes the buttons away") } } } diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index 5c71c86c39..cd41a7cef6 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -133,7 +133,8 @@ extension GlobalStateSuites { let storage = try EphemeralDefaults() fixture.toolbarOwner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) let toolbar = try #require(fixture.window.toolbar) - let hasGroup = { toolbar.items.contains { $0.itemIdentifier == MainWindowToolbar.objectKindsGroup } } + let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) + let hasButtons = { toolbar.items.contains { objectKinds.contains($0.itemIdentifier) } } var railChanges = 0 let subscription = AppEvents.shared.workspaceRailVisibilityChanged.sink { railChanges += 1 } defer { subscription.cancel() } @@ -141,12 +142,12 @@ extension GlobalStateSuites { NavigatorLayoutPreset.apply(to: &AppSettingsManager.shared.general, defaultLayout: &layout) - #expect(hasGroup(), "The Objects buttons reach the open window") + #expect(hasButtons(), "The Objects buttons reach the open window") #expect(railChanges == 1, "The connections column is told to swap in the navigator") NavigatorLayoutPreset.restore(to: &AppSettingsManager.shared.general, defaultLayout: &layout) - #expect(!hasGroup(), "The Objects buttons leave the open window") + #expect(!hasButtons(), "The Objects buttons leave the open window") #expect(railChanges == 2, "The connections column is told to swap the navigator out") } } diff --git a/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift b/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift index 43c52d13e7..1515a06687 100644 --- a/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift +++ b/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift @@ -83,39 +83,54 @@ struct MainWindowToolbarIdentifierTests { } } - /// The Objects group is never in the default set, so leaving the setting off changes nobody's - /// saved arrangement, and the delegate's nil answer is what prunes the group once it goes off. - @Test("The delegate builds the Objects group only while its setting is on") - func delegateBuildsTheGroupOnlyWhileTheSettingIsOn() throws { + /// The Objects buttons are never in the default set, so leaving the setting off changes nobody's + /// saved arrangement, and the delegate's nil answer is what prunes them once it goes off. + @Test("The delegate builds the Objects buttons only while their setting is on") + func delegateBuildsTheButtonsOnlyWhileTheSettingIsOn() throws { let owner = MainWindowToolbar() - let vend = { - owner.toolbar( - owner.managedToolbar, - itemForItemIdentifier: MainWindowToolbar.objectKindsGroup, - willBeInsertedIntoToolbar: true - ) + let vend = { (identifier: NSToolbarItem.Identifier) in + owner.toolbar(owner.managedToolbar, itemForItemIdentifier: identifier, willBeInsertedIntoToolbar: true) } + let objectKinds = MainWindowToolbar.objectKindItemIdentifiers owner.objectKindsEnabled = { false } let defaultsWhileOff = owner.toolbarDefaultItemIdentifiers(owner.managedToolbar) - #expect(vend() == nil) - #expect(!owner.toolbarAllowedItemIdentifiers(owner.managedToolbar).contains(MainWindowToolbar.objectKindsGroup)) + let allowedWhileOff = owner.toolbarAllowedItemIdentifiers(owner.managedToolbar) + for identifier in objectKinds { + #expect(vend(identifier) == nil, "\(identifier.rawValue) is vended with the setting off") + #expect(!allowedWhileOff.contains(identifier)) + } owner.objectKindsEnabled = { true } - let first = try #require(vend() as? NSToolbarItemGroup) - let second = try #require(vend()) - #expect(first.subitems.map { $0.itemIdentifier } == MainWindowToolbar.objectKindItemIdentifiers) - #expect(first !== second, "A fresh group on every vend, like every other item") - #expect(owner.toolbarAllowedItemIdentifiers(owner.managedToolbar).contains(MainWindowToolbar.objectKindsGroup)) + for identifier in objectKinds { + let first = try #require(vend(identifier)) + let second = try #require(vend(identifier)) + #expect(first.itemIdentifier == identifier) + #expect(first !== second, "A fresh item on every vend, like every other item") + } + let allowed = owner.toolbarAllowedItemIdentifiers(owner.managedToolbar) + #expect(Array(allowed.suffix(objectKinds.count)) == objectKinds) #expect(owner.toolbarDefaultItemIdentifiers(owner.managedToolbar) == defaultsWhileOff) - #expect(!defaultsWhileOff.contains(MainWindowToolbar.objectKindsGroup)) + #expect(Set(defaultsWhileOff).isDisjoint(with: objectKinds)) #expect(MainWindowToolbar.toolbarIdentifier == "com.TablePro.main.toolbar.v4") } - /// A user can have New Tab and the Objects group in one toolbar, and AppKit throws on a second + /// The buttons replaced a group of the same six. An arrangement that saved the group drops it + /// because nothing vends that identifier any more. + @Test("The former Objects group identifier is no longer vended") + func theFormerGroupIsNotVended() { + let owner = MainWindowToolbar() + owner.objectKindsEnabled = { true } + let former = NSToolbarItem.Identifier("com.TablePro.toolbar.objectKinds") + + #expect(owner.toolbar(owner.managedToolbar, itemForItemIdentifier: former, willBeInsertedIntoToolbar: true) == nil) + #expect(!owner.toolbarAllowedItemIdentifiers(owner.managedToolbar).contains(former)) + } + + /// A user can have New Tab and the Objects buttons in one toolbar, and AppKit throws on a second /// item with an identifier already there. @Test("The Objects identifiers collide with nothing else the toolbar offers") func objectKindIdentifiersAreTheirOwn() { - let own = [MainWindowToolbar.objectKindsGroup] + MainWindowToolbar.objectKindItemIdentifiers + let own = MainWindowToolbar.objectKindItemIdentifiers let others = Set( MainWindowToolbar.allowedItemIdentifiers + MainWindowToolbar.debugItemIdentifiers + [MainWindowToolbar.navigateBack, MainWindowToolbar.navigateForward] From 74c759b958698db1a6e7fb39bafa47303364a7d1 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:54:18 +0700 Subject: [PATCH 072/123] feat(toolbar): show labels under the toolbar icons in the Navigator Layout Use Navigator Layout turns the connection windows' toolbar to Icon and Text, and Use Standard Layout puts Icon Only back. The layout writes a General setting, showsToolbarLabels, with no toggle of its own: the toolbar's menu is where a person picks a mode. A record beside the arrangement makes each change of the setting reach the display mode once, so a mode picked later from that menu stays across windows and launches. AppKit autosaves the mode under the v4 identifier and copies it to every toolbar sharing it, so windows opened later follow, and a change made with no window open lands when the next one opens. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 1 + .../MainSplitViewController.swift | 1 + .../Infrastructure/MainWindowToolbar.swift | 74 +++++++++++ .../Core/Storage/AppSettingsManager.swift | 3 + .../Models/Settings/GeneralSettings.swift | 6 + .../Settings/NavigatorLayoutPreset.swift | 6 +- .../Views/Settings/GeneralSettingsView.swift | 5 +- .../Infrastructure/ToolbarLabelsTests.swift | 117 ++++++++++++++++++ .../Models/GeneralSettingsTests.swift | 1 + .../Models/NavigatorLayoutPresetTests.swift | 12 +- 10 files changed, 220 insertions(+), 6 deletions(-) create mode 100644 apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index cc9404af76..f268dfbadb 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -175,6 +175,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Routine debugger start options, per connection and field | UserDefaults, device-local | `RoutineDebugOptionStore` | | Whether the toolbar arrangement already carries the debug items | UserDefaults, device-local | `MainWindowToolbar` | | Whether the toolbar arrangement already carries the Objects buttons | UserDefaults, device-local | `MainWindowToolbar` | +| Whether the toolbar display mode already carries the Navigator Layout's labels | UserDefaults, device-local | `MainWindowToolbar` | | Trusted external links (loopback only) | UserDefaults | `ExternalConnectionTrustStore` | | Reopen the last session once after Relaunch to Update | UserDefaults, device-local, never synced, cleared by the next launch | `AppRelauncher` | | Highest plugin manifest `serial` accepted, so an older signed manifest is refused | UserDefaults, device-local, never synced | `RegistryManifestVerifier` through `RegistryClient` | diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index 77a4d08120..13f48d5296 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -526,6 +526,7 @@ internal final class MainSplitViewController: NSSplitViewController { window.toolbar = owner.managedToolbar owner.reconcileDebugItems() owner.reconcileObjectKindItems() + owner.reconcileDisplayMode() /// The item set every window starts from is the full one, because `isHidden` is never /// persisted, so the context is applied the moment the items exist rather than on the first /// change to it. Measured on macOS 27, that moment is this assignment: `NSToolbar.items` is diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index 3338757ece..f43fcf5aaf 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -101,6 +101,13 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { // The Objects buttons' facts and what they were read from, kept from one validation pass to the next. internal var objectKindFactsCache: ObjectKindFactsCache? + // Whether the Navigator Layout asks for labels under the icons. + internal var labelsEnabled: @MainActor () -> Bool = { + AppSettingsManager.shared.general.showsToolbarLabels + } + + internal var labelsRecord = ToolbarLabelsRecord() + /// `NSMenu.delegate` is weak, and the safe-mode control's menu is built here rather than by the /// menu bar, so this toolbar is what keeps its delegate alive. internal let safeModeMenuDelegate = SafeModeMenuDelegate() @@ -593,6 +600,53 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } } + // Pushed by the General setting's own write, like the Objects buttons. + internal static func applyToolbarLabelsSettingChange() { + for window in NSApp.windows { + (window.toolbar?.delegate as? MainWindowToolbar)?.reconcileDisplayMode() + } + } + + nonisolated internal static func displayMode(showsLabels: Bool) -> NSToolbar.DisplayMode { + showsLabels ? .iconAndLabel : .iconOnly + } + + // The layout's labels are written into the display mode once per change of the setting, so a mode the user picks + // later from the toolbar's own menu stays. AppKit autosaves the mode and copies it to every toolbar sharing the + // identifier, which is how windows opened later get it. Run when the toolbar reaches a window too, after it restored + // its saved mode, so a change made while no connection window was open still lands. + internal func reconcileDisplayMode() { + guard windowController?.view.window != nil || isInWindow() else { return } + let wanted = labelsEnabled() + guard labelsRecord.isApplied != wanted else { return } + labelsRecord.record(wanted) + managedToolbar.displayMode = Self.displayMode(showsLabels: wanted) + } + + // Run when the module changes and when the toolbar reaches a window, after it restored its saved arrangement: a + // change made while no connection window was open would otherwise never reach the arrangement. Inserted or removed + // in place, because reassigning the toolbar rebuilds the whole titlebar. + internal func reconcileDebugItems() { + guard windowController?.view.window != nil || isInWindow() else { return } + let wanted = debugItemsEnabled() + guard debugItemsRecord.isApplied != wanted else { return } + debugItemsRecord.record(wanted) + let debugIdentifiers = Set(Self.debugItemIdentifiers) + if wanted { + let present = managedToolbar.items.contains { debugIdentifiers.contains($0.itemIdentifier) } + if !present, let index = managedToolbar.items.firstIndex(where: { $0.itemIdentifier == Self.actions }) { + for (offset, identifier) in Self.debugDefaultItemIdentifiers.enumerated() { + managedToolbar.insertItem(withItemIdentifier: identifier, at: index + offset) + } + } + } else { + for index in managedToolbar.items.indices.reversed() + where debugIdentifiers.contains(managedToolbar.items[index].itemIdentifier) { + managedToolbar.removeItem(at: index) + } + } + } + // The debug items' rule for the Objects buttons: written once per change of the setting, so a button the user took // out stays out. They go first in the content area, after the sidebar's strip, or first of all without that divider. internal func reconcileObjectKindItems() { @@ -671,3 +725,23 @@ internal struct ToolbarObjectKindsRecord { defaults.set(applied, forKey: Self.key) } } + +// The Navigator Layout's labels last written into the shared display mode, kept for the same reasons as the debug items' +// record: a mode the user picks afterwards from the toolbar's menu outlives the next launch. +internal struct ToolbarLabelsRecord { + static let key = "com.TablePro.main.toolbar.v4.labels" + + let defaults: UserDefaults + + init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { + self.defaults = defaults + } + + var isApplied: Bool { + defaults.bool(forKey: Self.key) + } + + func record(_ applied: Bool) { + defaults.set(applied, forKey: Self.key) + } +} diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 812dbcf293..c23efc4e52 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -22,6 +22,9 @@ final class AppSettingsManager: ObservableObject { if oldValue.showsObjectToolbar != general.showsObjectToolbar { MainWindowToolbar.applyObjectToolbarSettingChange() } + if oldValue.showsToolbarLabels != general.showsToolbarLabels { + MainWindowToolbar.applyToolbarLabelsSettingChange() + } syncTracker.markDirty(.settings, id: AppSettingsCategory.general) } } diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 232ba676af..bfcb515239 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -64,6 +64,8 @@ struct GeneralSettings: Codable, Equatable { var showsFavoritesSection: Bool var showsObjectsOnSelection: Bool var showsObjectToolbar: Bool + // Written only by the Layout buttons. The toolbar's own menu is where a person picks labels, so there is no toggle. + var showsToolbarLabels: Bool var showObjectComments: Bool var showObjectIcons: Bool var showSystemContainers: Bool @@ -83,6 +85,7 @@ struct GeneralSettings: Codable, Equatable { showsFavoritesSection: false, showsObjectsOnSelection: false, showsObjectToolbar: false, + showsToolbarLabels: false, showObjectComments: true, showObjectIcons: true, showSystemContainers: false, @@ -103,6 +106,7 @@ struct GeneralSettings: Codable, Equatable { showsFavoritesSection: Bool = false, showsObjectsOnSelection: Bool = false, showsObjectToolbar: Bool = false, + showsToolbarLabels: Bool = false, showObjectComments: Bool = true, showObjectIcons: Bool = true, showSystemContainers: Bool = false, @@ -121,6 +125,7 @@ struct GeneralSettings: Codable, Equatable { self.showsFavoritesSection = showsFavoritesSection self.showsObjectsOnSelection = showsObjectsOnSelection self.showsObjectToolbar = showsObjectToolbar + self.showsToolbarLabels = showsToolbarLabels self.showObjectComments = showObjectComments self.showObjectIcons = showObjectIcons self.showSystemContainers = showSystemContainers @@ -145,6 +150,7 @@ struct GeneralSettings: Codable, Equatable { .showsObjectsOnSelection, default: fallback.showsObjectsOnSelection ) showsObjectToolbar = container.decodeSetting(.showsObjectToolbar, default: fallback.showsObjectToolbar) + showsToolbarLabels = container.decodeSetting(.showsToolbarLabels, default: fallback.showsToolbarLabels) showObjectComments = container.decodeSetting(.showObjectComments, default: fallback.showObjectComments) showObjectIcons = container.decodeSetting(.showObjectIcons, default: fallback.showObjectIcons) showSystemContainers = container.decodeSetting(.showSystemContainers, default: fallback.showSystemContainers) diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index a1b6358096..cf4139590a 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -6,8 +6,8 @@ import Foundation /// The Layout buttons in Settings > General: table details, favorite tables at the top of the tree, -/// the Objects tab on selection, the Objects toolbar buttons, the connections list and Tree as the -/// default sidebar layout, on or off in one step. +/// the Objects tab on selection, the Objects toolbar buttons, labels under the toolbar's icons, the +/// connections list and Tree as the default sidebar layout, on or off in one step. /// /// It edits the same values the separate controls edit and leaves the write to the caller. Settings /// passes its General settings binding, so the change lands on `AppSettingsManager.general` in one @@ -18,6 +18,7 @@ internal enum NavigatorLayoutPreset { settings.showsFavoritesSection = true settings.showsObjectsOnSelection = true settings.showsObjectToolbar = true + settings.showsToolbarLabels = true settings.showsConnectionNavigator = true defaultLayout = .tree } @@ -28,6 +29,7 @@ internal enum NavigatorLayoutPreset { settings.showsFavoritesSection = standard.showsFavoritesSection settings.showsObjectsOnSelection = standard.showsObjectsOnSelection settings.showsObjectToolbar = standard.showsObjectToolbar + settings.showsToolbarLabels = standard.showsToolbarLabels settings.showsConnectionNavigator = standard.showsConnectionNavigator defaultLayout = .flat } diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 8c7f861dea..e53300e8ba 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -74,8 +74,9 @@ struct GeneralSettingsView: View { } footer: { Text(String(localized: """ Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects \ - tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the \ - default sidebar layout. Standard Layout turns them off again. Open connections switch layout too. + tab on selection, the Objects toolbar buttons, toolbar labels and the connections list, and makes \ + Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch \ + layout too. """)) } diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift new file mode 100644 index 0000000000..87ea348e3c --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift @@ -0,0 +1,117 @@ +// +// ToolbarLabelsTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import Testing + +/// The Navigator Layout's labels under the toolbar's icons, written into the display mode once per +/// change of the setting, so a mode the user picks from the toolbar's own menu afterwards stays. +@MainActor +struct ToolbarLabelsTests { + /// A toolbar in a window, on a private identifier that never autosaves: the test host shares the + /// app's defaults, so a toolbar named like the app's own would carry its mode into the next launch. + private static func owner( + labelsOn: Bool, + record: ToolbarLabelsRecord, + mode: NSToolbar.DisplayMode = .iconOnly + ) -> MainWindowToolbar { + let toolbar = NSToolbar(identifier: "com.TablePro.tests.labels.\(UUID().uuidString)") + toolbar.autosavesConfiguration = false + let owner = MainWindowToolbar(managedToolbar: toolbar) + owner.isInWindow = { true } + owner.labelsRecord = record + owner.labelsEnabled = { labelsOn } + toolbar.displayMode = mode + return owner + } + + @Test("Labels on puts a label under every icon, and off puts the icons back alone") + func displayModeFollowsTheSetting() { + #expect(MainWindowToolbar.displayMode(showsLabels: true) == .iconAndLabel) + #expect(MainWindowToolbar.displayMode(showsLabels: false) == .iconOnly) + } + + @Test("Turning labels on shows them once") + func turningOnShowsLabels() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLabelsRecord(defaults: storage.defaults) + let owner = Self.owner(labelsOn: true, record: record) + + owner.reconcileDisplayMode() + + #expect(owner.managedToolbar.displayMode == .iconAndLabel) + #expect(record.isApplied) + } + + /// The toolbar's own menu is where a person picks a mode, so the layout asks once and then + /// leaves the choice alone, across later windows and launches too. + @Test("A mode the user picks after the layout asked for labels stays") + func theUsersLaterChoiceWins() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLabelsRecord(defaults: storage.defaults) + let owner = Self.owner(labelsOn: true, record: record) + owner.reconcileDisplayMode() + + owner.managedToolbar.displayMode = .iconOnly + owner.reconcileDisplayMode() + #expect(owner.managedToolbar.displayMode == .iconOnly) + + let later = Self.owner(labelsOn: true, record: record, mode: .labelOnly) + later.reconcileDisplayMode() + #expect(later.managedToolbar.displayMode == .labelOnly, "A later window keeps the mode it restored") + } + + @Test("Turning labels off puts the icons back alone") + func turningOffHidesLabels() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLabelsRecord(defaults: storage.defaults) + record.record(true) + let owner = Self.owner(labelsOn: false, record: record, mode: .iconAndLabel) + + owner.reconcileDisplayMode() + + #expect(owner.managedToolbar.displayMode == .iconOnly) + #expect(!record.isApplied) + } + + /// Someone who picked Icon and Text from the toolbar's menu without ever using the layout keeps it. + @Test("With labels never asked for, the toolbar keeps its mode and nothing is written") + func labelsNeverAskedForLeaveTheModeAlone() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLabelsRecord(defaults: storage.defaults) + let owner = Self.owner(labelsOn: false, record: record, mode: .iconAndLabel) + + owner.reconcileDisplayMode() + + #expect(owner.managedToolbar.displayMode == .iconAndLabel) + #expect(storage.defaults.object(forKey: ToolbarLabelsRecord.key) == nil) + } + + /// A change made while no connection window is open is left for the first window that opens, + /// which restores its saved mode before it reconciles. + @Test("A toolbar outside a window leaves the change for the next one") + func noWindowLeavesTheChangeForTheNextOne() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLabelsRecord(defaults: storage.defaults) + let owner = Self.owner(labelsOn: true, record: record) + owner.isInWindow = { false } + + owner.reconcileDisplayMode() + #expect(owner.managedToolbar.displayMode == .iconOnly) + #expect(!record.isApplied) + + owner.isInWindow = { true } + owner.reconcileDisplayMode() + #expect(owner.managedToolbar.displayMode == .iconAndLabel) + #expect(record.isApplied) + } + + @Test("The record sits beside the toolbar's arrangement, which keeps its v4 identifier") + func recordKeyFollowsTheArrangement() { + #expect(ToolbarLabelsRecord.key == "com.TablePro.main.toolbar.v4.labels") + #expect(MainWindowToolbar.toolbarIdentifier == "com.TablePro.main.toolbar.v4") + } +} diff --git a/apple/TableProTests/Models/GeneralSettingsTests.swift b/apple/TableProTests/Models/GeneralSettingsTests.swift index 1a4d15710f..f6a837acae 100644 --- a/apple/TableProTests/Models/GeneralSettingsTests.swift +++ b/apple/TableProTests/Models/GeneralSettingsTests.swift @@ -67,6 +67,7 @@ struct GeneralSettingsBoolSettingTests { BoolSetting(key: "showRecentTables", defaultValue: false), BoolSetting(key: "showsObjectsOnSelection", defaultValue: false), BoolSetting(key: "showsObjectToolbar", defaultValue: false), + BoolSetting(key: "showsToolbarLabels", defaultValue: false), BoolSetting(key: "showObjectComments", defaultValue: true), BoolSetting(key: "showObjectIcons", defaultValue: true), BoolSetting(key: "showSystemContainers", defaultValue: false), diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index cd41a7cef6..755a4a8132 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -17,11 +17,12 @@ struct NavigatorLayoutPresetTests { expected.showsFavoritesSection = true expected.showsObjectsOnSelection = true expected.showsObjectToolbar = true + expected.showsToolbarLabels = true expected.showsConnectionNavigator = true return expected } - @Test("Use Navigator Layout turns on all five features and makes Tree the default layout") + @Test("Use Navigator Layout turns on all six features and makes Tree the default layout") func applyTurnsEverythingOn() { var settings = GeneralSettings.default var layout = SidebarLayout.flat @@ -32,11 +33,12 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsFavoritesSection) #expect(settings.showsObjectsOnSelection) #expect(settings.showsObjectToolbar) + #expect(settings.showsToolbarLabels) #expect(settings.showsConnectionNavigator) #expect(layout == .tree) } - @Test("Use Standard Layout puts all six back to their defaults") + @Test("Use Standard Layout puts all seven back to their defaults") func restorePutsTheDefaultsBack() { var settings = Self.navigatorLayout(from: .default) var layout = SidebarLayout.tree @@ -47,6 +49,7 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsFavoritesSection == GeneralSettings.default.showsFavoritesSection) #expect(settings.showsObjectsOnSelection == GeneralSettings.default.showsObjectsOnSelection) #expect(settings.showsObjectToolbar == GeneralSettings.default.showsObjectToolbar) + #expect(!settings.showsToolbarLabels, "Standard Layout is icons only") #expect(settings.showsConnectionNavigator == GeneralSettings.default.showsConnectionNavigator) #expect(settings == GeneralSettings.default) #expect(layout == .flat) @@ -124,6 +127,7 @@ extension GlobalStateSuites { $0.general.showTableDetails = false $0.general.showsObjectsOnSelection = false $0.general.showsObjectToolbar = false + $0.general.showsToolbarLabels = false $0.general.showsConnectionNavigator = false } ) @@ -132,7 +136,9 @@ extension GlobalStateSuites { defer { fixture.tearDown() } let storage = try EphemeralDefaults() fixture.toolbarOwner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) + fixture.toolbarOwner.labelsRecord = ToolbarLabelsRecord(defaults: storage.defaults) let toolbar = try #require(fixture.window.toolbar) + #expect(toolbar.displayMode == .iconOnly) let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) let hasButtons = { toolbar.items.contains { objectKinds.contains($0.itemIdentifier) } } var railChanges = 0 @@ -143,11 +149,13 @@ extension GlobalStateSuites { NavigatorLayoutPreset.apply(to: &AppSettingsManager.shared.general, defaultLayout: &layout) #expect(hasButtons(), "The Objects buttons reach the open window") + #expect(toolbar.displayMode == .iconAndLabel, "Labels go under the toolbar's icons") #expect(railChanges == 1, "The connections column is told to swap in the navigator") NavigatorLayoutPreset.restore(to: &AppSettingsManager.shared.general, defaultLayout: &layout) #expect(!hasButtons(), "The Objects buttons leave the open window") + #expect(toolbar.displayMode == .iconOnly, "Standard Layout puts the icons back alone") #expect(railChanges == 2, "The connections column is told to swap the navigator out") } } From 0ae2622f89ac422342789a0c326f2f8525134b67 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:58:06 +0700 Subject: [PATCH 073/123] feat(mysql): list table sizes in bytes The table listing returned sizes as text rounded to megabytes ("0.05 MB"), which the Objects tab can neither format for the reader nor sort as numbers. MySQL, MariaDB and Databend now return DATA_LENGTH, INDEX_LENGTH and their sum as bytes. The Objects tab is the only reader of this statement. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MySQLDriverPlugin/DatabendCatalog.swift | 6 +++--- .../MySQLPluginDriver+DatabaseMetadata.swift | 8 +++++--- .../MySQLDatabaseMetadataTests.swift | 20 +++++++++++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/apple/Plugins/MySQLDriverPlugin/DatabendCatalog.swift b/apple/Plugins/MySQLDriverPlugin/DatabendCatalog.swift index 7556c43c62..e9186430c6 100644 --- a/apple/Plugins/MySQLDriverPlugin/DatabendCatalog.swift +++ b/apple/Plugins/MySQLDriverPlugin/DatabendCatalog.swift @@ -88,9 +88,9 @@ internal enum DatabendCatalog { table_name AS name, table_type AS kind, table_rows AS estimated_rows, - CONCAT(ROUND((data_length + index_length) / 1024 / 1024, 2), ' MB') AS total_size, - CONCAT(ROUND(data_length / 1024 / 1024, 2), ' MB') AS data_size, - CONCAT(ROUND(index_length / 1024 / 1024, 2), ' MB') AS index_size, + data_length + index_length AS total_size, + data_length AS data_size, + index_length AS index_size, table_comment AS comment FROM information_schema.tables WHERE table_schema = DATABASE() diff --git a/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift b/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift index 9137b2e794..573335ce32 100644 --- a/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift +++ b/apple/Plugins/MySQLDriverPlugin/MySQLPluginDriver+DatabaseMetadata.swift @@ -84,6 +84,8 @@ internal extension MySQLPluginDriver { /// The character set is the collation's prefix (`MySQLTableOptions.characterSet(ofCollation:)`): MariaDB /// 10.10+ reports `utf8mb4_uca1400_ai_ci`, which no `COLLATION_NAME` matches. + /// + /// Sizes are bytes, so the host formats them for the reader and sorts them as numbers. func allTablesMetadataSQL(schema: String?) -> String? { guard !flavor.isDatabend else { return DatabendCatalog.allTablesMetadataSQL } guard !flavor.isStarRocks else { return nil } @@ -96,9 +98,9 @@ internal extension MySQLPluginDriver { IFNULL(SUBSTRING_INDEX(TABLE_COLLATION, '_', 1), '') as charset, TABLE_COLLATION as collation, TABLE_ROWS as estimated_rows, - CONCAT(ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2), ' MB') as total_size, - CONCAT(ROUND(DATA_LENGTH / 1024 / 1024, 2), ' MB') as data_size, - CONCAT(ROUND(INDEX_LENGTH / 1024 / 1024, 2), ' MB') as index_size, + DATA_LENGTH + INDEX_LENGTH as total_size, + DATA_LENGTH as data_size, + INDEX_LENGTH as index_size, ENGINE as engine, CREATE_TIME as create_time, UPDATE_TIME as update_time, diff --git a/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift b/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift index d0fd8b157e..49a3655312 100644 --- a/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift +++ b/apple/Plugins/MySQLDriverTests/MySQLDatabaseMetadataTests.swift @@ -68,6 +68,26 @@ struct MySQLDatabaseMetadataTests { #expect(updated.upperBound < comment.lowerBound) } + // The Objects list formats bytes for the reader and sorts them as numbers; "0.05 MB" text could do neither. + @Test("The table listing reports its sizes as bytes, not as text rounded to megabytes") + func listingReportsBytes() throws { + let statement = try #require(unconnectedDriver().allTablesMetadataSQL(schema: "shop")) + + #expect(statement.contains("DATA_LENGTH + INDEX_LENGTH as total_size")) + #expect(statement.contains("DATA_LENGTH as data_size")) + #expect(statement.contains("INDEX_LENGTH as index_size")) + #expect(!statement.contains("MB")) + } + + @Test("Databend's table listing reports its sizes as bytes too") + func databendListingReportsBytes() { + let statement = DatabendCatalog.allTablesMetadataSQL + + #expect(statement.contains("data_length AS data_size")) + #expect(statement.contains("index_length AS index_size")) + #expect(!statement.contains("MB")) + } + // SHOW TABLE STATUS already answers Engine, Create_time and Update_time. @Test("A server without the catalog keeps its SHOW TABLE STATUS listing as it was") func tableStatusFallbackIsUnchanged() { From 551de851694465e8507b25e85fb9bf668a604fc6 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:58:12 +0700 Subject: [PATCH 074/123] feat(objects): format listing values and lay out the list's columns The Objects list reads each column by the plugin's alias, now kept on the listing beside the localized titles. Counts read with grouping separators, a numeric size reads as a byte count (text a plugin formatted shows as it came), and a catalog timestamp shows as yyyy-MM-dd HH:mm:ss. Tables show Name, Rows, Data Length, Engine, Created Date, Modified Date, Collation and Comment first; Schema starts hidden while it repeats the container, and Type, Charset, Total Size and Index Size start hidden. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/ObjectListingPresentation.swift | 506 ++++++++++++++++++ .../Services/Query/ObjectListingRows.swift | 71 ++- .../Services/Query/TableListingLoader.swift | 16 +- .../ObjectListingPresentationTests.swift | 317 +++++++++++ .../Query/ObjectListingRowsTests.swift | 6 +- 5 files changed, 877 insertions(+), 39 deletions(-) create mode 100644 apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift create mode 100644 apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift diff --git a/apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift b/apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift new file mode 100644 index 0000000000..7331dc80a3 --- /dev/null +++ b/apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift @@ -0,0 +1,506 @@ +// +// ObjectListingPresentation.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +/// How the Objects list reads one column's values. +internal enum ObjectListingValueFormat: Equatable, Sendable { + case text + /// A count, such as a table's estimated rows. + case count + /// A size. A number is bytes; text a plugin formatted itself ("16 kB") shows as it came. + case bytes + /// A timestamp, shown in one fixed shape so every row lines up. + case date + + /// Numbers line up on their last digit, the way a file size column does. + var alignsTrailing: Bool { + self == .count || self == .bytes + } +} + +/// What a cell sorts by, so 9 sorts before 10 and an empty cell sorts before every value. +internal enum ObjectListingSortKey: Comparable, Sendable { + case missing + case number(Double) + case text(String) + + static func < (lhs: Self, rhs: Self) -> Bool { + switch (lhs, rhs) { + case (.missing, .missing): return false + case (.missing, _): return true + case (_, .missing): return false + case (.number(let left), .number(let right)): return left < right + case (.number, .text): return true + case (.text, .number): return false + case (.text(let left), .text(let right)): return left.localizedStandardCompare(right) == .orderedAscending + } + } +} + +/// Turns listing values into the text the Objects list draws and the keys it sorts by. +/// +/// Built once per listing: a byte count formatter is slow to make, and a listing formats every cell. +internal struct ObjectListingValueFormatter { + private let locale: Locale + private let timeZone: TimeZone + private let byteCounter: ByteCountFormatter + + init(locale: Locale = .current, timeZone: TimeZone = .current) { + self.locale = locale + self.timeZone = timeZone + byteCounter = ByteCountFormatter() + // Binary units: InnoDB stores 16 KiB pages, so 163,840 bytes reads 160 KB rather than 164 KB. + byteCounter.countStyle = .binary + byteCounter.allowsNonnumericFormatting = false + } + + func display(_ value: PluginCellValue, as format: ObjectListingValueFormat) -> String { + guard let text = value.asText else { return "" } + switch format { + case .text: + return text + case .count: + guard let number = Self.number(in: text) else { return text } + if let whole = Int64(exactly: number) { + return whole.formatted(.number.grouping(.automatic).locale(locale)) + } + return number.formatted(.number.locale(locale)) + case .bytes: + guard let number = Self.number(in: text), number >= 0, let bytes = Int64(exactly: number.rounded()) else { + return text + } + return byteCounter.string(fromByteCount: bytes) + case .date: + guard let timestamp = ObjectListingTimestamp(parsing: text) else { return text } + return timestamp.display(in: timeZone) + } + } + + func sortKey(_ value: PluginCellValue, as format: ObjectListingValueFormat) -> ObjectListingSortKey { + guard let text = value.asText, !text.trimmingCharacters(in: .whitespaces).isEmpty else { return .missing } + switch format { + case .text: + return .text(text) + case .count: + return Self.number(in: text).map(ObjectListingSortKey.number) ?? .text(text) + case .bytes: + return (Self.number(in: text) ?? Self.pluginSizeBytes(in: text)).map(ObjectListingSortKey.number) ?? .text(text) + case .date: + return ObjectListingTimestamp(parsing: text).map { .number($0.sortValue) } ?? .text(text) + } + } + + /// Plain decimal digits only. `Double(_:)` alone also reads "nan", "inf" and hex floats, which no + /// count or size is. + static func number(in text: String) -> Double? { + let trimmed = text.trimmingCharacters(in: .whitespaces) + var digits = 0 + var dots = 0 + for (offset, character) in trimmed.enumerated() { + if character.isASCII, character.isNumber { + digits += 1 + } else if character == "." { + dots += 1 + } else if character == "-", offset == 0 { + continue + } else { + return nil + } + } + guard digits > 0, dots <= 1 else { return nil } + return Double(trimmed) + } + + /// A size a plugin already formatted, such as PostgreSQL's `pg_size_pretty` "16 kB" or "0.05 MB", + /// read back to bytes so the column still sorts by size. Those spellings count in 1,024s. + static func pluginSizeBytes(in text: String) -> Double? { + let parts = text.trimmingCharacters(in: .whitespaces).split(separator: " ", omittingEmptySubsequences: true) + guard parts.count == 2, let number = number(in: String(parts[0])) else { return nil } + let units = ["bytes", "b", "kb", "mb", "gb", "tb", "pb"] + guard let index = units.firstIndex(of: parts[1].lowercased()) else { return nil } + return number * pow(1_024, Double(max(index - 1, 0))) + } +} + +/// A catalog timestamp: MySQL's `2026-08-12 08:05:33`, with a fraction or an offset where an engine adds one. +/// +/// One without an offset is the server's wall clock, and the client cannot know the server's zone, +/// so it shows as written. One with an offset is an instant and shows in the reader's zone. +internal struct ObjectListingTimestamp: Equatable { + let year: Int + let month: Int + let day: Int + let hour: Int + let minute: Int + let second: Int + /// Seconds east of UTC, nil when the text names no zone. + let offset: Int? + + init?(parsing text: String) { + var scanner = TimestampScanner(Array(text.trimmingCharacters(in: .whitespaces).utf8)) + guard let year = scanner.digits(4), scanner.take("-"), + let month = scanner.digits(2), scanner.take("-"), + let day = scanner.digits(2), scanner.take(" ") || scanner.take("T"), + let hour = scanner.digits(2), scanner.take(":"), + let minute = scanner.digits(2) + else { return nil } + var second = 0 + if scanner.take(":") { + guard let seconds = scanner.digits(2) else { return nil } + second = seconds + if scanner.take(".") { + guard scanner.skipDigits() > 0 else { return nil } + } + } + scanner.skipSpaces() + var offset: Int? + if scanner.take("Z") { + offset = 0 + } else if let sign = scanner.sign() { + guard let hours = scanner.digits(2) else { return nil } + _ = scanner.take(":") + let minutes = scanner.digits(2) ?? 0 + offset = sign * (hours * 3_600 + minutes * 60) + } + guard scanner.isAtEnd, (1 ... 12).contains(month), (1 ... 31).contains(day), + hour < 24, minute < 60, second < 61 + else { return nil } + self.year = year + self.month = month + self.day = day + self.hour = hour + self.minute = minute + self.second = second + self.offset = offset + } + + private init(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int) { + self.year = year + self.month = month + self.day = day + self.hour = hour + self.minute = minute + self.second = second + offset = nil + } + + func display(in zone: TimeZone) -> String { + let shown = offset == nil ? self : wallClock(in: zone) ?? self + return String( + format: "%04d-%02d-%02d %02d:%02d:%02d", + shown.year, shown.month, shown.day, shown.hour, shown.minute, shown.second + ) + } + + /// Wall clocks compare as if they shared one zone, which they do on one server. + var sortValue: Double { + guard let date = Self.utcCalendar.date(from: components) else { return 0 } + return date.timeIntervalSince1970 - Double(offset ?? 0) + } + + private var components: DateComponents { + DateComponents(year: year, month: month, day: day, hour: hour, minute: minute, second: second) + } + + private func wallClock(in zone: TimeZone) -> ObjectListingTimestamp? { + guard let utc = Self.utcCalendar.date(from: components) else { return nil } + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = zone + let local = calendar.dateComponents( + [.year, .month, .day, .hour, .minute, .second], + from: utc.addingTimeInterval(-Double(offset ?? 0)) + ) + guard let year = local.year, let month = local.month, let day = local.day, + let hour = local.hour, let minute = local.minute, let second = local.second + else { return nil } + return ObjectListingTimestamp(year: year, month: month, day: day, hour: hour, minute: minute, second: second) + } + + private static var utcCalendar: Calendar { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC") ?? .current + return calendar + } +} + +private struct TimestampScanner { + private let bytes: [UInt8] + private var index = 0 + + init(_ bytes: [UInt8]) { + self.bytes = bytes + } + + var isAtEnd: Bool { + index == bytes.count + } + + mutating func digits(_ count: Int) -> Int? { + guard index + count <= bytes.count else { return nil } + var value = 0 + for byte in bytes[index ..< index + count] { + guard (UInt8(ascii: "0") ... UInt8(ascii: "9")).contains(byte) else { return nil } + value = value * 10 + Int(byte - UInt8(ascii: "0")) + } + index += count + return value + } + + mutating func skipDigits() -> Int { + let start = index + while index < bytes.count, (UInt8(ascii: "0") ... UInt8(ascii: "9")).contains(bytes[index]) { + index += 1 + } + return index - start + } + + mutating func skipSpaces() { + while index < bytes.count, bytes[index] == UInt8(ascii: " ") { + index += 1 + } + } + + mutating func take(_ character: Unicode.Scalar) -> Bool { + guard index < bytes.count, bytes[index] == UInt8(ascii: character) else { return false } + index += 1 + return true + } + + mutating func sign() -> Int? { + if take("+") { return 1 } + if take("-") { return -1 } + return nil + } +} + +// MARK: - Columns + +/// A column the plugins' table listings share, by the alias their SQL gives it. The order of the +/// cases is the order the list shows them in. +internal enum ObjectListingField: CaseIterable, Sendable { + case name + case rows + case dataSize + case engine + case created + case updated + case collation + case comment + case schema + case kind + case charset + case totalSize + case indexSize + + /// `rows`, `data_length` and `index_length` are how MySQL's `SHOW TABLE STATUS` fallback names them. + init?(alias: String) { + switch alias.lowercased() { + case "name": self = .name + case "estimated_rows", "rows": self = .rows + case "data_size", "data_length": self = .dataSize + case "engine": self = .engine + case "create_time": self = .created + case "update_time": self = .updated + case "collation": self = .collation + case "comment": self = .comment + case "schema", "schema_name": self = .schema + case "kind": self = .kind + case "charset": self = .charset + case "total_size": self = .totalSize + case "index_size", "index_length": self = .indexSize + default: return nil + } + } + + var title: String { + switch self { + case .name: String(localized: "Name") + case .rows: String(localized: "Rows") + case .dataSize: String(localized: "Data Length") + case .engine: String(localized: "Engine") + case .created: String(localized: "Created Date") + case .updated: String(localized: "Modified Date") + case .collation: String(localized: "Collation") + case .comment: String(localized: "Comment") + case .schema: String(localized: "Schema") + case .kind: String(localized: "Type") + case .charset: String(localized: "Charset") + case .totalSize: String(localized: "Total Size") + case .indexSize: String(localized: "Index Size") + } + } + + var format: ObjectListingValueFormat { + switch self { + case .rows: .count + case .dataSize, .totalSize, .indexSize: .bytes + case .created, .updated: .date + case .name, .engine, .collation, .comment, .schema, .kind, .charset: .text + } + } + + /// The type repeats the kind the picker names, the charset repeats the collation, and the total and + /// index sizes add little beside the data length. A user can still show any of them. + var isShownByDefault: Bool { + switch self { + case .schema, .kind, .charset, .totalSize, .indexSize: false + case .name, .rows, .dataSize, .engine, .created, .updated, .collation, .comment: true + } + } +} + +/// One column of the Objects list. +internal struct ObjectListingColumn: Equatable, Identifiable, Sendable { + /// The plugin's alias or the built column's key, lowercased. A saved show or hide choice keys on it. + let id: String + let title: String + /// Where the column's values sit in each listing row. + let valueIndex: Int + let format: ObjectListingValueFormat + let isShownByDefault: Bool +} + +internal enum ObjectListingColumnLayout { + /// The listing's columns in the list's order: the known ones in `ObjectListingField` order, the + /// visible ones first, and a column only this plugin lists after Comment in the plugin's order. + /// + /// `containerName` is the database or schema the tab lists. A Schema column naming only it says + /// nothing, and neither does a column every row left empty, so both start hidden. + static func columns(of listing: TableListing, containerName: String?) -> [ObjectListingColumn] { + let titles = listing.rows.columns + let keys = titles.indices.map { index in + listing.columnKeys.indices.contains(index) ? listing.columnKeys[index] : titles[index].lowercased() + } + let fields = keys.map(ObjectListingField.init(alias:)) + let hasDataSize = fields.contains(.dataSize) + let visibleFieldCount = ObjectListingField.allCases.filter(\.isShownByDefault).count + + func rank(_ index: Int) -> Double { + // A total stands in for the data length a listing lacks, so it takes that place. + let field = fields[index] == .totalSize && !hasDataSize ? .dataSize : fields[index] + guard let field, let order = ObjectListingField.allCases.firstIndex(of: field) else { + return Double(visibleFieldCount) - 0.5 + } + return Double(order) + } + + var seen: Set = [] + let ordered = titles.indices.sorted { (rank($0), $0) < (rank($1), $1) } + return ordered.map { index in + let field = fields[index] + var id = keys[index] + if !seen.insert(id).inserted { + id = "\(id)#\(index)" + seen.insert(id) + } + return ObjectListingColumn( + id: id, + title: field?.title ?? titles[index], + valueIndex: index, + format: field?.format ?? .text, + isShownByDefault: isShownByDefault( + field, + valueIndex: index, + rows: listing.rows, + hasDataSize: hasDataSize, + containerName: containerName + ) + ) + } + } + + private static func isShownByDefault( + _ field: ObjectListingField?, + valueIndex: Int, + rows: TableRows, + hasDataSize: Bool, + containerName: String? + ) -> Bool { + let values = rows.rows.compactMap { $0[valueIndex].asText?.nilIfEmpty } + switch field { + case .name: + return true + case .schema: + return values.contains { $0 != containerName } + case .totalSize where !hasDataSize: + return !values.isEmpty + default: + return (field?.isShownByDefault ?? true) && !values.isEmpty + } + } +} + +// MARK: - Rows + +/// One object as the Objects list draws it. +internal struct ObjectListingRow: Equatable, Identifiable, Sendable { + let id: RowID + let item: ObjectListingItem + let iconName: String + /// The drawn text of each value, by value index. + let texts: [String] + let sortKeys: [ObjectListingSortKey] +} + +/// The column the reader sorted the list by. +internal struct ObjectListingSort: Equatable, Sendable { + let columnID: String + let ascending: Bool +} + +internal enum ObjectListingRowBuilder { + /// A row with no name, which names no object, is left out: nothing could open it. + static func rows( + of listing: TableListing, + columns: [ObjectListingColumn], + formatter: ObjectListingValueFormatter + ) -> [ObjectListingRow] { + let formats = Dictionary(columns.map { ($0.valueIndex, $0.format) }, uniquingKeysWith: { first, _ in first }) + let valueCount = listing.rows.columns.count + return listing.rows.rows.compactMap { row in + guard let item = listing.items[row.id] else { return nil } + var texts: [String] = [] + var keys: [ObjectListingSortKey] = [] + texts.reserveCapacity(valueCount) + keys.reserveCapacity(valueCount) + for index in 0 ..< valueCount { + let format = formats[index] ?? .text + texts.append(formatter.display(row[index], as: format)) + keys.append(formatter.sortKey(row[index], as: format)) + } + return ObjectListingRow(id: row.id, item: item, iconName: item.iconName, texts: texts, sortKeys: keys) + } + } + + /// Ties keep the listing's own order, so a second click on a column never shuffles equal rows. + static func sorted( + _ rows: [ObjectListingRow], + by sort: ObjectListingSort?, + columns: [ObjectListingColumn] + ) -> [ObjectListingRow] { + guard let sort, let column = columns.first(where: { $0.id == sort.columnID }) else { return rows } + let index = column.valueIndex + return rows.enumerated().sorted { lhs, rhs in + let left = lhs.element.sortKeys.indices.contains(index) ? lhs.element.sortKeys[index] : .missing + let right = rhs.element.sortKeys.indices.contains(index) ? rhs.element.sortKeys[index] : .missing + if left < right { return sort.ascending } + if right < left { return !sort.ascending } + return lhs.offset < rhs.offset + } + .map(\.element) + } +} + +extension ObjectListingItem { + /// The glyph the sidebar draws for the same object. + var iconName: String { + switch self { + case .relation(_, _, let type): return TableRowLogic.iconName(for: type) + case .sourced(let ref): return ref.kind.iconName + } + } +} diff --git a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift index 6ecfa62e6d..e6c347e75a 100644 --- a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift +++ b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift @@ -56,7 +56,8 @@ extension ObjectListingItem { extension TableListing { /// A list the sidebar commits again unchanged has nothing for the grid to redraw. func showsSameRows(as other: TableListing) -> Bool { - rows.columns == other.rows.columns && rows.rows == other.rows.rows && items == other.items + rows.columns == other.rows.columns && columnKeys == other.columnKeys + && rows.rows == other.rows.rows && items == other.items } /// Where each object `previous` listed sits in this listing, by row id. Row ids are positions, so @@ -118,22 +119,7 @@ internal struct ObjectListingColumns: Equatable { /// The plugins alias their listing columns for SQL, not for reading, so a known alias reads as words. /// An alias this does not know keeps the plugin's spelling. static func displayTitle(for column: String) -> String { - switch column.lowercased() { - case "schema", "schema_name": String(localized: "Schema") - case "name": String(localized: "Name") - case "kind": String(localized: "Type") - case "charset": String(localized: "Charset") - case "collation": String(localized: "Collation") - case "estimated_rows": String(localized: "Rows") - case "total_size": String(localized: "Total Size") - case "data_size": String(localized: "Data Size") - case "index_size": String(localized: "Index Size") - case "engine": String(localized: "Engine") - case "create_time": String(localized: "Created") - case "update_time": String(localized: "Updated") - case "comment": String(localized: "Comment") - default: column - } + ObjectListingField(alias: column)?.title ?? column } /// An unknown word, such as a ClickHouse engine name, reads as a table: only a view must not @@ -165,38 +151,38 @@ internal enum ObjectListingRows { switch list { case .relations(let tables): let columns: [ListingColumn] = [ - ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, - ListingColumn(String(localized: "Schema")) { $0.schema ?? schema }, - ListingColumn(String(localized: "Rows"), isCount: true) { $0.rowCount.map(String.init) }, - ListingColumn(String(localized: "Comment")) { $0.comment?.nilIfEmpty }, + ListingColumn("name", String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn("schema", String(localized: "Schema")) { $0.schema ?? schema }, + ListingColumn("estimated_rows", String(localized: "Rows"), isCount: true) { $0.rowCount.map(String.init) }, + ListingColumn("comment", String(localized: "Comment")) { $0.comment?.nilIfEmpty }, ] let matching = tables.filter { SidebarObjectKind.resolve(tableType: $0.type) == kind } return build(matching, columns: columns) { .relation(name: $0.name, schema: schema ?? $0.schema, type: $0.type) } case .routines(let routines): let columns: [ListingColumn] = [ - ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, - ListingColumn(String(localized: "Schema")) { $0.schema ?? schema }, - ListingColumn(String(localized: "Arguments")) { $0.argumentSignature?.nilIfEmpty }, - ListingColumn(String(localized: "Returns")) { $0.returnType?.nilIfEmpty }, - ListingColumn(String(localized: "Language")) { $0.language?.nilIfEmpty }, + ListingColumn("name", String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn("schema", String(localized: "Schema")) { $0.schema ?? schema }, + ListingColumn("arguments", String(localized: "Arguments")) { $0.argumentSignature?.nilIfEmpty }, + ListingColumn("returns", String(localized: "Returns")) { $0.returnType?.nilIfEmpty }, + ListingColumn("language", String(localized: "Language")) { $0.language?.nilIfEmpty }, ] let matching = routines.filter { $0.kind.sidebarObjectKind == kind } return build(matching, columns: columns) { .sourced(DatabaseObjectRef(routine: $0, database: database)) } case .triggers(let triggers): let columns: [ListingColumn] = [ - ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, - ListingColumn(String(localized: "Table")) { $0.table?.nilIfEmpty }, - ListingColumn(String(localized: "Timing")) { $0.timing.nilIfEmpty }, - ListingColumn(String(localized: "Event")) { $0.event.nilIfEmpty }, - ListingColumn(String(localized: "Enabled")) { trigger in + ListingColumn("name", String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn("table", String(localized: "Table")) { $0.table?.nilIfEmpty }, + ListingColumn("timing", String(localized: "Timing")) { $0.timing.nilIfEmpty }, + ListingColumn("event", String(localized: "Event")) { $0.event.nilIfEmpty }, + ListingColumn("enabled", String(localized: "Enabled")) { trigger in trigger.enabled.map { $0 ? String(localized: "Yes") : String(localized: "No") } }, ] return build(triggers, columns: columns) { .sourced(DatabaseObjectRef(trigger: $0, database: database)) } case .types(let types): let columns: [ListingColumn] = [ - ListingColumn(String(localized: "Name"), isOptional: false) { $0.name }, - ListingColumn(String(localized: "Schema")) { $0.schema ?? schema }, + ListingColumn("name", String(localized: "Name"), isOptional: false) { $0.name }, + ListingColumn("schema", String(localized: "Schema")) { $0.schema ?? schema }, ] return build(types, columns: columns) { .sourced(DatabaseObjectRef(userType: $0, database: database)) } } @@ -221,19 +207,22 @@ internal enum ObjectListingRows { rows: TableRows.from(queryRows: rows, columns: kept.map(\.title), columnTypes: types), isIncomplete: false, statusMessage: nil, - items: items + items: items, + columnKeys: kept.map(\.key) ) } } /// A column no object has a value for says nothing, as a Schema column does on an engine without schemas. private struct ListingColumn { + let key: String let title: String let isOptional: Bool let isCount: Bool let value: (Object) -> String? - init(_ title: String, isOptional: Bool = true, isCount: Bool = false, value: @escaping (Object) -> String?) { + init(_ key: String, _ title: String, isOptional: Bool = true, isCount: Bool = false, value: @escaping (Object) -> String?) { + self.key = key self.title = title self.isOptional = isOptional self.isCount = isCount @@ -248,11 +237,21 @@ internal enum ObjectListingFilter { let needle = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !needle.isEmpty, !listing.items.isEmpty else { return listing.rows } let hidden = Set(listing.rows.rows.compactMap { row -> RowID? in - guard let name = listing.items[row.id]?.name, name.localizedStandardContains(needle) else { return row.id } + guard let name = listing.items[row.id]?.name, matches(name, needle) else { return row.id } return nil }) var shown = listing.rows shown.remove(rowIDs: hidden) return shown } + + /// Whether `name` holds the filter text, ignoring case, accents and the spaces around the text. + static func keeps(_ name: String, matching text: String) -> Bool { + let needle = text.trimmingCharacters(in: .whitespacesAndNewlines) + return needle.isEmpty || matches(name, needle) + } + + private static func matches(_ name: String, _ needle: String) -> Bool { + name.localizedStandardContains(needle) + } } diff --git a/apple/TablePro/Core/Services/Query/TableListingLoader.swift b/apple/TablePro/Core/Services/Query/TableListingLoader.swift index 2b948b133b..c7b523cc04 100644 --- a/apple/TablePro/Core/Services/Query/TableListingLoader.swift +++ b/apple/TablePro/Core/Services/Query/TableListingLoader.swift @@ -52,7 +52,8 @@ internal struct TableListingLoader: Sendable { rows: rows, isIncomplete: result.isTruncated, statusMessage: result.statusMessage, - items: items + items: items, + columnKeys: listingColumns == nil ? [] : result.columns.map { $0.lowercased() } )) } catch { if DatabaseCancellationDiagnosis.isCancellation(error) { return .cancelled } @@ -73,11 +74,22 @@ internal struct TableListing: Sendable { /// The object each row lists, which the name filter and the row commands read. Empty for a /// listing with no name column, whose rows stay plain values. let items: [RowID: ObjectListingItem] + /// Each column's source name, the plugin's alias or the built column's key, lowercased. The list + /// formats, orders and remembers columns by it, since the titles are localized. Empty for a + /// listing whose rows name no objects. + let columnKeys: [String] - init(rows: TableRows, isIncomplete: Bool, statusMessage: String?, items: [RowID: ObjectListingItem] = [:]) { + init( + rows: TableRows, + isIncomplete: Bool, + statusMessage: String?, + items: [RowID: ObjectListingItem] = [:], + columnKeys: [String] = [] + ) { self.rows = rows self.isIncomplete = isIncomplete self.items = items + self.columnKeys = columnKeys if let statusMessage, !statusMessage.isEmpty { notice = statusMessage } else { diff --git a/apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift b/apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift new file mode 100644 index 0000000000..4ab5a6d9f7 --- /dev/null +++ b/apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift @@ -0,0 +1,317 @@ +// +// ObjectListingPresentationTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +struct ObjectListingPresentationTests { + private let utc = TimeZone(identifier: "UTC") ?? .current + + private var formatter: ObjectListingValueFormatter { + ObjectListingValueFormatter(locale: Locale(identifier: "en_US"), timeZone: utc) + } + + private func shown(_ text: String?, as format: ObjectListingValueFormat) -> String { + formatter.display(.fromOptional(text), as: format) + } + + private func key(_ text: String?, as format: ObjectListingValueFormat) -> ObjectListingSortKey { + formatter.sortKey(.fromOptional(text), as: format) + } + + // The app's own byte formatter, so the expectation follows the host's language the way the list does. + private func bytes(_ count: Int64) -> String { + let formatter = ByteCountFormatter() + formatter.countStyle = .binary + formatter.allowsNonnumericFormatting = false + return formatter.string(fromByteCount: count) + } + + /// The MySQL listing's columns, in the order its statement selects them. + private static let mysqlColumns = [ + "schema", "name", "kind", "charset", "collation", "estimated_rows", "total_size", "data_size", "index_size", + "engine", "create_time", "update_time", "comment", + ] + + private func listing(_ columns: [String], _ rows: [[String?]]) -> TableListing { + let tableRows = TableRows.from( + queryRows: rows.map { $0.map(PluginCellValue.fromOptional) }, + columns: columns.map(ObjectListingColumns.displayTitle(for:)), + columnTypes: Array(repeating: .text(rawType: nil), count: columns.count) + ) + let items = ObjectListingColumns(columns: columns)?.items( + in: tableRows, containerSchema: nil, readsSchemaColumn: false + ) ?? [:] + return TableListing(rows: tableRows, isIncomplete: false, statusMessage: nil, items: items, columnKeys: columns) + } + + private func mysqlRow( + _ name: String, + rows: String? = "10", + data: String? = "16384", + updated: String? = "2026-11-10 07:00:30", + comment: String? = "Kept" + ) -> [String?] { + ["shop", name, "BASE TABLE", "utf8mb4", "utf8mb4_unicode_ci", rows, "32768", data, "16384", + "InnoDB", "2026-08-12 08:05:33", updated, comment] + } + + // MARK: - Counts + + @Test("A count reads with grouping separators, and text that is not a count shows as it came") + func countsGroupTheirDigits() { + #expect(shown("6215717", as: .count) == "6,215,717") + #expect(shown("570", as: .count) == "570") + #expect(shown("12.0", as: .count) == "12") + #expect(shown("n/a", as: .count) == "n/a") + #expect(shown("", as: .count) == "") + #expect(shown(nil, as: .count) == "") + } + + @Test("Counts sort as numbers, with an empty cell before every count") + func countsSortAsNumbers() { + #expect(key("9", as: .count) < key("10", as: .count)) + #expect(key(nil, as: .count) < key("0", as: .count)) + #expect(key("", as: .count) == .missing) + } + + // MARK: - Sizes + + @Test("A size in bytes reads as a byte count in binary units") + func bytesReadAsByteCounts() { + #expect(shown("163840", as: .bytes) == bytes(163_840)) + #expect(shown("2050000000", as: .bytes) == bytes(2_050_000_000)) + #expect(shown("0", as: .bytes) == bytes(0)) + #expect(shown("163840", as: .bytes).contains("160")) + } + + @Test("A size a plugin formatted itself shows as it came", arguments: ["16 kB", "0.05 MB", "1,2 GB", "-"]) + func formattedSizesPassThrough(text: String) { + #expect(shown(text, as: .bytes) == text) + } + + @Test("Sizes sort by bytes, including the ones a plugin formatted in 1,024s") + func sizesSortByBytes() { + #expect(key("16384", as: .bytes) == .number(16_384)) + #expect(key("16 kB", as: .bytes) == .number(16_384)) + #expect(key("0.05 MB", as: .bytes) == .number(0.05 * 1_048_576)) + #expect(key("16 kB", as: .bytes) < key("1 MB", as: .bytes)) + #expect(key("a lot", as: .bytes) == .text("a lot")) + } + + @Test("Only plain decimal digits count as a number", arguments: [ + ("42", 42.0), ("-5", -5.0), ("3.25", 3.25), (" 7 ", 7.0), + ]) + func plainDigitsAreNumbers(text: String, value: Double) { + #expect(ObjectListingValueFormatter.number(in: text) == value) + } + + @Test("Words Swift would read as a number are not one here", arguments: ["nan", "inf", "0x10", "1e5", "1.2.3", "", "-"]) + func otherSpellingsAreNotNumbers(text: String) { + #expect(ObjectListingValueFormatter.number(in: text) == nil) + } + + // MARK: - Dates + + @Test("A catalog timestamp shows in one fixed shape", arguments: [ + ("2026-08-12 08:05:33", "2026-08-12 08:05:33"), + ("2026-08-12 08:05:33.123456", "2026-08-12 08:05:33"), + ("2026-08-12T08:05:33", "2026-08-12 08:05:33"), + ("2026-08-12 08:05", "2026-08-12 08:05:00"), + ("2026-08-12T08:05:33Z", "2026-08-12 08:05:33"), + ]) + func timestampsShowInOneShape(text: String, expected: String) { + #expect(shown(text, as: .date) == expected) + } + + // A wall clock without a zone is the server's, which the client cannot place, so it stays as written. + @Test("A timestamp with an offset shows in the reader's zone, and one without stays the server's wall clock") + func offsetsMoveToTheReadersZone() throws { + let saigon = try #require(TimeZone(identifier: "Asia/Ho_Chi_Minh")) + let local = ObjectListingValueFormatter(locale: Locale(identifier: "en_US"), timeZone: saigon) + + #expect(local.display(.text("2026-08-12 08:05:33+02:00"), as: .date) == "2026-08-12 13:05:33") + #expect(local.display(.text("2026-08-12 23:30:00Z"), as: .date) == "2026-08-13 06:30:00") + #expect(local.display(.text("2026-08-12 08:05:33"), as: .date) == "2026-08-12 08:05:33") + } + + @Test("Text that is not a timestamp shows as it came", arguments: ["yesterday", "2026-13-01 00:00:00", "2026-08-12", ""]) + func otherDatesPassThrough(text: String) { + #expect(shown(text, as: .date) == text) + } + + @Test("Timestamps sort by the instant they name") + func timestampsSortByInstant() { + #expect(key("2026-08-12 08:05:33", as: .date) < key("2026-08-12 08:05:34", as: .date)) + #expect(key("2026-08-12 08:00:00+02", as: .date) < key("2026-08-12 07:00:00Z", as: .date)) + #expect(key(nil, as: .date) == .missing) + } + + @Test("Text keeps its spelling and sorts the way Finder sorts names") + func textSortsLikeFinder() { + #expect(shown("InnoDB", as: .text) == "InnoDB") + #expect(key("table2", as: .text) < key("table10", as: .text)) + #expect(key("Alpha", as: .text) < key("beta", as: .text)) + } + + // MARK: - Columns + + @Test("A Tables listing shows Name, Rows, Data Length, Engine, the dates, Collation and Comment, in that order") + func tablesColumnsInTheirOrder() { + let columns = ObjectListingColumnLayout.columns( + of: listing(Self.mysqlColumns, [mysqlRow("orders", comment: "Paid orders")]), + containerName: "shop" + ) + + #expect(columns.filter { $0.isShownByDefault }.map { $0.title } == [ + String(localized: "Name"), String(localized: "Rows"), String(localized: "Data Length"), + String(localized: "Engine"), String(localized: "Created Date"), String(localized: "Modified Date"), + String(localized: "Collation"), String(localized: "Comment"), + ]) + #expect(columns.map { $0.id } == [ + "name", "estimated_rows", "data_size", "engine", "create_time", "update_time", "collation", "comment", + "schema", "kind", "charset", "total_size", "index_size", + ]) + #expect(columns.first { $0.id == "estimated_rows" }?.format == .count) + #expect(columns.first { $0.id == "data_size" }?.format == .bytes) + #expect(columns.first { $0.id == "create_time" }?.format == .date) + } + + // Modified Date is empty for this InnoDB table, but a later row could carry one: only a column every row leaves empty hides. + @Test("A column every row leaves empty starts hidden; one some rows fill stays") + func emptyColumnsStartHidden() { + let columns = ObjectListingColumnLayout.columns( + of: listing(Self.mysqlColumns, [mysqlRow("orders", comment: ""), mysqlRow("audit", comment: "Kept 90 days")]), + containerName: "shop" + ) + let modified = ObjectListingColumnLayout.columns( + of: listing(Self.mysqlColumns, [mysqlRow("orders", updated: nil, comment: "")]), + containerName: "shop" + ) + + #expect(columns.first { $0.id == "comment" }?.isShownByDefault == true) + #expect(modified.first { $0.id == "update_time" }?.isShownByDefault == false) + #expect(modified.first { $0.id == "comment" }?.isShownByDefault == false) + } + + @Test("Schema starts hidden while it names only the listed container, and shows when a row names another") + func schemaHidesWhenItRepeatsTheContainer() { + let same = listing(["schema", "name"], [["shop", "orders"], ["", "customers"]]) + let mixed = listing(["schema", "name"], [["shop", "orders"], ["archive", "orders"]]) + + #expect(ObjectListingColumnLayout.columns(of: same, containerName: "shop").first { $0.id == "schema" }?.isShownByDefault == false) + #expect(ObjectListingColumnLayout.columns(of: mixed, containerName: "shop").first { $0.id == "schema" }?.isShownByDefault == true) + } + + @Test("Total Size shows in Data Length's place where a listing has none, as ClickHouse's has none") + func totalSizeStandsInForDataLength() { + let clickhouse = listing(["schema", "name", "kind", "estimated_rows", "total_size", "comment"], [ + ["default", "events", "MergeTree", "100", "1.20 MiB", "Raw events"], + ]) + + let columns = ObjectListingColumnLayout.columns(of: clickhouse, containerName: "default") + + #expect(columns.filter { $0.isShownByDefault }.map { $0.id } == ["name", "estimated_rows", "total_size", "comment"]) + } + + @Test("A column only this plugin lists keeps its spelling and shows after Comment, in the plugin's order") + func unknownColumnsFollowComment() { + let redshift = listing(["schema", "name", "kind", "estimated_rows", "size_mb", "pct_used"], [ + ["public", "events", "TABLE", "100", "12", "0.5"], + ]) + + let columns = ObjectListingColumnLayout.columns(of: redshift, containerName: "public") + + #expect(columns.map { $0.id } == ["name", "estimated_rows", "size_mb", "pct_used", "schema", "kind"]) + #expect(columns.first { $0.id == "size_mb" }?.title == "size_mb") + #expect(columns.first { $0.id == "size_mb" }?.isShownByDefault == true) + } + + @Test("MySQL's SHOW TABLE STATUS columns read as the same fields") + func tableStatusAliasesAreKnown() { + #expect(ObjectListingField(alias: "Rows") == .rows) + #expect(ObjectListingField(alias: "Data_length") == .dataSize) + #expect(ObjectListingField(alias: "Index_length") == .indexSize) + #expect(ObjectListingField(alias: "Avg_row_length") == nil) + } + + @Test("Another kind's built columns keep their order, and its Schema hides while it repeats the container") + func builtKindsKeepTheirColumns() { + let routines = [ + RoutineInfo(name: "touch", kind: .function, schema: "sales", argumentSignature: "(integer)", returnType: "integer", language: "plpgsql"), + ] + let built = ObjectListingRows.listing( + kind: .function, + from: .routines(routines), + scope: DatabaseScope(connectionId: UUID(), database: "shop", schema: "sales") + ) + + let columns = ObjectListingColumnLayout.columns(of: built, containerName: "sales") + + #expect(columns.map { $0.id } == ["name", "arguments", "returns", "language", "schema"]) + #expect(columns.filter { $0.isShownByDefault }.map { $0.id } == ["name", "arguments", "returns", "language"]) + } + + @Test("Two columns sharing one alias keep apart, so each can be shown or hidden") + func duplicateAliasesGetTheirOwnIds() { + let doubled = listing(["name", "note", "note"], [["orders", "a", "b"]]) + + let ids = ObjectListingColumnLayout.columns(of: doubled, containerName: nil).map(\.id) + + #expect(Set(ids).count == 3) + } + + // MARK: - Rows + + @Test("Each row carries its object, the sidebar's glyph and its formatted values") + func rowsCarryTheirObject() throws { + let source = listing(Self.mysqlColumns, [mysqlRow("orders", rows: "6215717", data: "163840", updated: nil)]) + let columns = ObjectListingColumnLayout.columns(of: source, containerName: "shop") + + let row = try #require(ObjectListingRowBuilder.rows(of: source, columns: columns, formatter: formatter).first) + + #expect(row.item == .relation(name: "orders", schema: nil, type: .table)) + #expect(row.iconName == TableRowLogic.iconName(for: .table)) + #expect(row.texts[5] == "6,215,717") + #expect(row.texts[7] == bytes(163_840)) + #expect(row.texts[10] == "2026-08-12 08:05:33") + #expect(row.texts[11] == "") + } + + @Test("A source object shows its own kind's glyph") + func sourcedRowsShowTheirKind() throws { + let built = ObjectListingRows.listing( + kind: .function, + from: .routines([RoutineInfo(name: "touch", kind: .function, schema: "sales")]), + scope: DatabaseScope(connectionId: UUID(), database: "shop", schema: "sales") + ) + let columns = ObjectListingColumnLayout.columns(of: built, containerName: "sales") + + let row = try #require(ObjectListingRowBuilder.rows(of: built, columns: columns, formatter: formatter).first) + + #expect(row.iconName == SidebarObjectKind.function.iconName) + } + + @Test("Rows sort by a column's values as numbers, and equal values keep the listing's order") + func rowsSortByTheirValues() { + let source = listing(Self.mysqlColumns, [ + mysqlRow("small", data: "16384"), mysqlRow("large", data: "2050000000"), + mysqlRow("medium", data: "163840"), mysqlRow("twin", data: "16384"), + ]) + let columns = ObjectListingColumnLayout.columns(of: source, containerName: "shop") + let rows = ObjectListingRowBuilder.rows(of: source, columns: columns, formatter: formatter) + + let descending = ObjectListingRowBuilder.sorted(rows, by: ObjectListingSort(columnID: "data_size", ascending: false), columns: columns) + let ascending = ObjectListingRowBuilder.sorted(rows, by: ObjectListingSort(columnID: "data_size", ascending: true), columns: columns) + let unsorted = ObjectListingRowBuilder.sorted(rows, by: nil, columns: columns) + + #expect(descending.map { $0.item.name } == ["large", "medium", "small", "twin"]) + #expect(ascending.map { $0.item.name } == ["small", "twin", "medium", "large"]) + #expect(unsorted.map { $0.item.name } == ["small", "large", "medium", "twin"]) + } +} diff --git a/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift b/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift index 4713b86a63..325f50e4d7 100644 --- a/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift +++ b/apple/TableProTests/Core/Services/Query/ObjectListingRowsTests.swift @@ -36,6 +36,7 @@ struct ObjectListingRowsTests { let listing = ObjectListingRows.listing(kind: .view, from: .relations(tables), scope: scope) #expect(listing.rows.columns == [String(localized: "Name"), String(localized: "Schema"), String(localized: "Comment")]) + #expect(listing.columnKeys == ["name", "schema", "comment"]) #expect(cells(listing.rows) == [["recent_orders", "sales", "Last 30 days"]]) #expect(listing.items[.existing(0)] == .relation(name: "recent_orders", schema: "sales", type: .view)) } @@ -47,6 +48,7 @@ struct ObjectListingRowsTests { let listing = ObjectListingRows.listing(kind: .sequence, from: .relations(tables), scope: scope) #expect(listing.rows.columns == [String(localized: "Name"), String(localized: "Schema"), String(localized: "Rows")]) + #expect(listing.columnKeys == ["name", "schema", "estimated_rows"]) #expect(listing.rows.columnTypes[2] == .integer(rawType: nil)) } @@ -155,7 +157,9 @@ struct ObjectListingRowsTests { func listingAliasesReadAsWords() { #expect(ObjectListingColumns.displayTitle(for: "estimated_rows") == "Rows") #expect(ObjectListingColumns.displayTitle(for: "SCHEMA_NAME") == "Schema") - #expect(ObjectListingColumns.displayTitle(for: "update_time") == "Updated") + #expect(ObjectListingColumns.displayTitle(for: "data_size") == "Data Length") + #expect(ObjectListingColumns.displayTitle(for: "create_time") == "Created Date") + #expect(ObjectListingColumns.displayTitle(for: "update_time") == "Modified Date") #expect(ObjectListingColumns.displayTitle(for: "total_rows") == "total_rows") } From 17c58aeeda320a3f4214c8243dddcb3af29d0b04 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:58:23 +0700 Subject: [PATCH 075/123] feat(objects): show objects in a sortable list with a tool strip Rows that name objects now show in an AppKit list instead of the data grid: the system font, alternating rows, the sidebar's glyph before each name, sortable headers, multi-select, the row menu, and a double click or Return to open. A right-click on the header shows or hides columns, remembered per object kind. A shell command's rows, such as a Redis SCAN page, keep the grid. The selection is held by object rather than by row position, so a refresh that lists a new object above the selected one keeps the same one selected. The tab's bar becomes a tool strip: Open, Show Structure, New Table, Delete, Import, Export and Refresh, each enabled only when it applies, with the kind picker, the name filter and the count on the right. Delete goes through the sidebar's staged drop and its confirmation; New Table, Import and Export use the coordinator's existing commands. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 1 + .../Services/Query/ObjectListingRows.swift | 17 - .../ViewModels/ObjectListingList.swift | 141 ++++++ .../ViewModels/TableListingViewModel.swift | 92 +++- .../Main/Child/MainEditorContentView.swift | 3 + ...MainContentCoordinator+ObjectListing.swift | 68 +++ .../Views/TableListing/ObjectListingBar.swift | 70 ++- .../TableListing/ObjectListingMenu.swift | 52 ++- .../TableListing/ObjectListingTableView.swift | 437 ++++++++++++++++++ .../TableListing/TableListingTabView.swift | 21 +- .../ViewModels/ObjectListingListTests.swift | 177 +++++++ .../TableListingViewModelTests.swift | 202 +++++--- .../Main/CoordinatorTableListingTests.swift | 46 ++ .../TableListing/ObjectListingMenuTests.swift | 60 +++ .../ObjectListingTableViewTests.swift | 146 ++++++ 15 files changed, 1416 insertions(+), 117 deletions(-) create mode 100644 apple/TablePro/ViewModels/ObjectListingList.swift create mode 100644 apple/TablePro/Views/TableListing/ObjectListingTableView.swift create mode 100644 apple/TableProTests/ViewModels/ObjectListingListTests.swift create mode 100644 apple/TableProTests/Views/TableListing/ObjectListingTableViewTests.swift diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index f268dfbadb..110d295bd8 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -167,6 +167,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Favorite tables (iCloud-synced) | UserDefaults | `FavoriteTablesStorage` | | Team library, per team: pull cursor, items, unpushed edits, conflicts (synced with tablepro-cloud's `/v2`, never iCloud) | JSON, one file per team | `TeamLibraryStateStore` through `TeamLibrarySync` | | Sidebar database and schema filters, recent tables | UserDefaults, device-local | `DatabaseTreeFilterStorage`, `RecentTablesStore` | +| Objects tab column choices, per object kind | UserDefaults `com.TablePro.objectsList.columns.`, device-local, never synced | `ObjectListingColumnVisibilityStore` | | Connection navigator group expansion | UserDefaults `com.TablePro.navigator.groupExpansion`, device-local, never synced | `ConnectionNavigatorExpansionStore` | | Connection navigator column width | AppKit split view autosave `com.TablePro.connectionNavigator`, device-local | `NavigationSidebarViewController` through `SplitViewAutosaveName.current(_:)` | | History drawer state | UserDefaults, device-local | `HistoryPanelPreferencesStorage` | diff --git a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift index e6c347e75a..f807d7e4ba 100644 --- a/apple/TablePro/Core/Services/Query/ObjectListingRows.swift +++ b/apple/TablePro/Core/Services/Query/ObjectListingRows.swift @@ -59,23 +59,6 @@ extension TableListing { rows.columns == other.rows.columns && columnKeys == other.columnKeys && rows.rows == other.rows.rows && items == other.items } - - /// Where each object `previous` listed sits in this listing, by row id. Row ids are positions, so - /// an object created or dropped above another moves it to another id. Nil when `previous` names no - /// objects: its rows are plain values with nothing to follow. - func rowIDs(carriedFrom previous: TableListing) -> [RowID: RowID]? { - guard !previous.items.isEmpty else { return nil } - var rowIDsByKey: [ObjectListingItem.Key: RowID] = [:] - for row in rows.rows { - guard let item = items[row.id], rowIDsByKey[item.key] == nil else { continue } - rowIDsByKey[item.key] = row.id - } - var carried: [RowID: RowID] = [:] - for (rowID, item) in previous.items { - carried[rowID] = rowIDsByKey[item.key] - } - return carried - } } /// Where a plugin's table listing names its objects: the plugins alias the columns `name`, diff --git a/apple/TablePro/ViewModels/ObjectListingList.swift b/apple/TablePro/ViewModels/ObjectListingList.swift new file mode 100644 index 0000000000..83914a2218 --- /dev/null +++ b/apple/TablePro/ViewModels/ObjectListingList.swift @@ -0,0 +1,141 @@ +// +// ObjectListingList.swift +// TablePro +// + +import Combine +import Foundation + +/// The columns a reader showed or hid in the Objects list, per object kind. Device-local, never synced. +@MainActor +internal final class ObjectListingColumnVisibilityStore { + internal static let shared = ObjectListingColumnVisibilityStore() + + private static let keyPrefix = "com.TablePro.objectsList.columns." + + private let defaults: UserDefaults + + internal init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { + self.defaults = defaults + } + + /// Column id to shown, only for the columns the reader changed. Every other column keeps its default. + internal func choices(for kind: SidebarObjectKind) -> [String: Bool] { + defaults.dictionary(forKey: Self.key(kind))?.compactMapValues { $0 as? Bool } ?? [:] + } + + internal func setColumn(_ columnID: String, shown: Bool, kind: SidebarObjectKind) { + var choices = choices(for: kind) + choices[columnID] = shown + defaults.set(choices, forKey: Self.key(kind)) + } + + private static func key(_ kind: SidebarObjectKind) -> String { + keyPrefix + kind.rawValue + } +} + +/// The rows, columns, sort and selection the Objects list shows for one tab. +/// +/// It outlives the list's view, so a tab switch keeps the sort, the selection and the column widths. +/// The selection is held by object rather than by position, so a refresh that lists a new table above +/// the selected one keeps the same table selected. +@MainActor +internal final class ObjectListingList: ObservableObject { + @Published private(set) var columns: [ObjectListingColumn] = [] + @Published private(set) var rows: [ObjectListingRow] = [] + @Published private(set) var sort: ObjectListingSort? + @Published private(set) var selection: Set = [] + @Published private(set) var columnChoices: [String: Bool] + /// Moves whenever `rows` or `columns` is replaced, so the table reloads only then. + @Published private(set) var revision = 0 + + /// Widths the reader dragged a column to, kept for the next time the tab's view is made. + var columnWidths: [String: CGFloat] = [:] + + /// The reader sorted the list, which keeps a preview tab. + var onSortChange: (() -> Void)? + + let kind: SidebarObjectKind + + private let containerName: String? + private let visibility: ObjectListingColumnVisibilityStore + private let formatter: () -> ObjectListingValueFormatter + private var allRows: [ObjectListingRow] = [] + private var filterText = "" + + init( + kind: SidebarObjectKind, + containerName: String?, + visibility: ObjectListingColumnVisibilityStore = .shared, + formatter: @escaping () -> ObjectListingValueFormatter = { ObjectListingValueFormatter() } + ) { + self.kind = kind + self.containerName = containerName + self.visibility = visibility + self.formatter = formatter + columnChoices = visibility.choices(for: kind) + } + + /// The columns the list draws, in order. + var shownColumns: [ObjectListingColumn] { + columns.filter(isShown) + } + + func isShown(_ column: ObjectListingColumn) -> Bool { + columnChoices[column.id] ?? column.isShownByDefault + } + + /// The selected objects in the order the list shows them. + var selectedItems: [ObjectListingItem] { + rows.filter { selection.contains($0.item.key) }.map(\.item) + } + + /// A listing landed or the filter changed. Rows the filter hides leave the selection, so a + /// command never acts on an object the reader cannot see. + func show(_ listing: TableListing, filterText: String) { + let columns = ObjectListingColumnLayout.columns(of: listing, containerName: containerName) + allRows = ObjectListingRowBuilder.rows(of: listing, columns: columns, formatter: formatter()) + if columns != self.columns { + self.columns = columns + } + self.filterText = filterText + arrangeRows() + } + + func applyFilter(_ text: String) { + guard text != filterText else { return } + filterText = text + arrangeRows() + } + + func setSort(_ sort: ObjectListingSort?) { + guard sort != self.sort else { return } + self.sort = sort + arrangeRows() + onSortChange?() + } + + func select(_ keys: Set) { + guard keys != selection else { return } + selection = keys + } + + func setColumn(_ columnID: String, shown: Bool) { + // Name is what every row is read by, so it never hides. + guard columnID != "name", columns.contains(where: { $0.id == columnID }) else { return } + columnChoices[columnID] = shown + visibility.setColumn(columnID, shown: shown, kind: kind) + } + + private func arrangeRows() { + let filtered = allRows.filter { ObjectListingFilter.keeps($0.item.name, matching: filterText) } + rows = ObjectListingRowBuilder.sorted(filtered, by: sort, columns: columns) + let shownKeys = Set(rows.map(\.item.key)) + let kept = selection.intersection(shownKeys) + if kept != selection { + selection = kept + } + revision &+= 1 + } +} diff --git a/apple/TablePro/ViewModels/TableListingViewModel.swift b/apple/TablePro/ViewModels/TableListingViewModel.swift index 6ef5dc22c2..53043f7674 100644 --- a/apple/TablePro/ViewModels/TableListingViewModel.swift +++ b/apple/TablePro/ViewModels/TableListingViewModel.swift @@ -24,12 +24,14 @@ internal final class TableListingViewModel: ObservableObject { @Published var filterText = "" { didSet { guard filterText != oldValue else { return } - showRows() + showRows(listingChanged: false) onInteraction() } } - // Outlives the tab's view, so the sort, the selection and the column widths survive a tab switch. + // Both outlive the tab's view, so the sort, the selection and the column widths survive a tab switch. + // The list shows rows that name objects; the grid shows a shell command's plain rows. + let list: ObjectListingList let grid = HeldRowsGridAdapter(configuration: DataGridConfiguration(), sortsHeldRows: true) let target: DatabaseTreeObjectGroup @@ -38,6 +40,7 @@ internal final class TableListingViewModel: ObservableObject { private let metadataProvider: any ScopedMetadataProviding private let objectSource: any CatalogObjectListSource private let perform: (ObjectListingAction) -> Void + private let commandFacts: ([ObjectListingItem]) -> ObjectListingCommandFacts private let onInteraction: () -> Void private var loadTask: Task? private var generation = 0 @@ -54,10 +57,18 @@ internal final class TableListingViewModel: ObservableObject { objectSource: any CatalogObjectListSource = DatabaseTreeMetadataService.shared, refreshRequests: AnyPublisher = AppEvents.shared.tabRefreshRequested.eraseToAnyPublisher(), perform: @escaping (ObjectListingAction) -> Void = { _ in }, + commandFacts: @escaping ([ObjectListingItem]) -> ObjectListingCommandFacts = { _ in ObjectListingCommandFacts() }, + columnVisibility: ObjectListingColumnVisibilityStore = .shared, onInteraction: @escaping () -> Void = {} ) { self.scope = scope self.target = DatabaseTreeObjectGroup(database: scope.database, schema: scope.schema, kind: kind) + self.list = ObjectListingList( + kind: kind, + containerName: scope.schema.flatMap { $0.isEmpty ? nil : $0 } ?? scope.database, + visibility: columnVisibility + ) + self.commandFacts = commandFacts self.loader = loader self.metadataProvider = metadataProvider self.objectSource = objectSource @@ -67,10 +78,7 @@ internal final class TableListingViewModel: ObservableObject { .filter { $0 == tabId } .sink { [weak self] _ in self?.reload() } grid.onSortChange = { [weak self] _ in self?.onInteraction() } - grid.rowMenuItems = { [weak self] rowIDs, clicked in - self?.menuItems(for: rowIDs, clicked: clicked) ?? [] - } - grid.opensRow = { [weak self] rowID in self?.open(rowID) } + list.onSortChange = { [weak self] in self?.onInteraction() } // Tables come from the plugin's listing statement; every other kind is the sidebar's own list. if kind != .table { listSubscription = objectSource.objectListChanges(kind.category, in: scope) @@ -78,11 +86,18 @@ internal final class TableListingViewModel: ObservableObject { } } - /// Whether each row names an object, which the name filter and the row commands need. + /// Whether each row names an object, which the name filter, the list and the row commands need. var rowsNameObjects: Bool { state.value.map { !$0.items.isEmpty } ?? false } + /// The tool strip's buttons for what the list has selected now. + var commandAvailability: ObjectListingCommandAvailability { + guard rowsNameObjects else { return .none } + let selection = list.selectedItems + return ObjectListingCommandAvailability.resolve(kind: target.kind, selection: selection, facts: commandFacts(selection)) + } + @discardableResult func loadIfNeeded() -> Task? { guard case .idle = state else { return nil } @@ -167,13 +182,12 @@ internal final class TableListingViewModel: ObservableObject { private func commit(_ outcome: MetadataFetchOutcome, token: Int) { guard token == generation else { return } isRefreshing = false - let previous = state.value state = state.settled(by: outcome, discardingValue: false) // A cancel from here bumps the generation, so this one came from elsewhere and nothing else is coming. if case .cancelled = outcome, case .idle = state { wasInterrupted = true } - showRows(replacing: previous) + showRows() } /// The sidebar committed this kind's list, after a refresh, a statement or a drop there: rows on @@ -183,32 +197,68 @@ internal final class TableListingViewModel: ObservableObject { let listing = ObjectListingRows.listing(kind: target.kind, from: list, scope: scope) guard !listing.showsSameRows(as: shown) else { return } state = .loaded(listing) - showRows(replacing: shown) + showRows() } - /// The grid keeps its selection by row id, which is a position here, so rows replacing `previous` - /// carry it to the same objects: Return and the menu act on what the reader picked. - private func showRows(replacing previous: TableListing? = nil) { + /// A filter change only narrows the rows on hand, so the list formats nothing again. + private func showRows(listingChanged: Bool = true) { guard let listing = state.value else { count = nil return } let shown = ObjectListingFilter.rows(of: listing, matching: filterText) count = ObjectListingCount(shown: shown.count, total: listing.rows.count) - grid.setRows(shown, carryingSelection: previous.flatMap { listing.rowIDs(carriedFrom: $0) }) + if listing.items.isEmpty { + grid.setRows(shown) + } else if listingChanged { + list.show(listing, filterText: filterText) + } else { + list.applyFilter(filterText) + } + } + + // MARK: - Commands + + /// A double click or Return on a row. + func open(_ item: ObjectListingItem) { + run(ObjectListingMenu.primaryAction(for: item)) } - private func menuItems(for rowIDs: [RowID], clicked: RowID) -> [NSMenuItem] { - guard let items = state.value?.items, let clickedItem = items[clicked] else { return [] } - let targets = rowIDs.compactMap { items[$0] } - return ObjectListingMenu.commands(clicked: clickedItem, targets: targets).map { command in + /// The clicked row's menu, acting on the whole selection when the clicked row is part of it. + func menuItems(clicked: ObjectListingItem, targets: [ObjectListingItem]) -> [NSMenuItem] { + ObjectListingMenu.commands(clicked: clicked, targets: targets).map { command in ClosureMenuTarget.item(title: command.title) { [weak self] in self?.run(command.action) } } } - private func open(_ rowID: RowID) { - guard let item = state.value?.items[rowID] else { return } - run(ObjectListingMenu.primaryAction(for: item)) + func openSelection() { + guard commandAvailability.canOpen, let item = list.selectedItems.first else { return } + open(item) + } + + func designSelection() { + guard commandAvailability.canDesign, let item = list.selectedItems.first else { return } + run(.showStructure(item)) + } + + func createObject() { + guard commandAvailability.canCreate else { return } + run(.createTable) + } + + func deleteSelection() { + guard commandAvailability.canDelete else { return } + run(.drop(list.selectedItems)) + } + + func importData() { + guard commandAvailability.canImport else { return } + run(.importData) + } + + func exportSelection() { + guard commandAvailability.canExport else { return } + run(.export(list.selectedItems)) } private func run(_ action: ObjectListingAction) { diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index 89da36d00a..bd33342942 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -247,6 +247,9 @@ struct MainEditorContentView: View { perform: { [weak coordinator = self.coordinator] action in coordinator?.performListingAction(action, fromTab: tabId) }, + commandFacts: { [weak coordinator = self.coordinator] items in + coordinator?.listingCommandFacts(for: items, inTab: tabId) ?? ObjectListingCommandFacts() + }, onInteraction: { [weak tabManager = self.tabManager] in tabManager?.promotePreviewTab(id: tabId) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift index cecbcfaab5..b0a0fd3ee6 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift @@ -63,6 +63,7 @@ extension MainContentCoordinator { guard let tab = tabManager.tabs.first(where: { $0.id == tabId && $0.tabType == .tableListing }) else { return } tabManager.promotePreviewTab(id: tabId) let database = tab.tableContext.databaseName + let schema = tab.tableContext.schemaName switch action { case .open(let item): openListedRelation(item, database: database, showStructure: false, forceNewTab: false) @@ -75,6 +76,73 @@ extension MainContentCoordinator { showObjectSource(objectRef) case .copyNames(let names): ClipboardService.shared.writeText(names.joined(separator: ",")) + case .createTable: + createNewTable(databaseName: database, schemaName: schema) + case .importData: + // An import writes into the browsed container, so the tab's container is reached first, + // as the sidebar's own Import does. + Task { @MainActor [weak self] in + await self?.switchContainers(database: database, schema: schema) + self?.openImportPanel() + } + case .export(let items): + let refs = listingTableRefs(items, in: tab) + guard let first = refs.first else { return } + let scope = ExportPreselection.scope( + for: first, + grouping: PluginManager.shared.databaseGroupingStrategy(for: connection.type) + ) + Task { @MainActor [weak self] in + await self?.switchContainers(database: database, schema: schema) + self?.openExportDialog(preselectedTableNames: Set(refs.map(\.table.name)), scope: scope) + } + case .drop(let items): + let refs = listingTableRefs(items, in: tab) + guard !refs.isEmpty, !safeModeLevel.blocksAllWrites else { return } + // The sidebar's own path: it asks before it queues the drop, and Save runs it against the + // browsed database, so the tab's container is reached first. + Task { @MainActor [weak self] in + await self?.switchContainers(database: database, schema: schema) + self?.sidebarViewModel?.batchToggleDelete(refs: refs) + } + } + } + + /// What the tool strip of `tabId` can offer for `items`, its selected objects. + func listingCommandFacts(for items: [ObjectListingItem], inTab tabId: UUID) -> ObjectListingCommandFacts { + let isReadOnly = safeModeLevel.blocksAllWrites + guard !isReadOnly else { return ObjectListingCommandFacts(isReadOnly: true) } + let driver = DatabaseManager.shared.driver(for: connectionId) + var facts = ObjectListingCommandFacts(isReadOnly: false) + facts.canCreateTable = CreateTableEligibility.canCreateTable(with: driver) + facts.canImport = importFormatLookup.supportsImport(connection.type) + && !importFormatLookup.offeredFormats(connection.type).isEmpty + if let adapter = driver as? PluginDriverAdapter, + let tab = tabManager.tabs.first(where: { $0.id == tabId && $0.tabType == .tableListing }) { + let refs = listingTableRefs(items, in: tab) + facts.canDropSelection = refs.count == items.count && TableOperationEligibility.canDrop( + refs, + context: adapter.tableOperationEligibility(for: refs, isReadOnly: false) + ) + } + return facts + } + + /// The refs the sidebar's commands take for the listed relations. Where the sidebar lists the + /// object, its own `TableInfo` is used, so a queued drop marks the same row there. + func listingTableRefs(_ items: [ObjectListingItem], in tab: QueryTab) -> [DatabaseTreeTableRef] { + let database = tab.tableContext.databaseName + let schema = tab.tableContext.schemaName + let listed = DatabaseTreeMetadataService.shared.tables(connectionId: connectionId, database: database, schema: schema) + return items.compactMap { item in + guard case .relation(let name, let itemSchema, let type) = item else { return nil } + let kind = SidebarObjectKind.resolve(tableType: type) + let table = listed.first { candidate in + candidate.name == name + && SidebarObjectKind.resolve(tableType: candidate.type) == kind + && (candidate.schema == nil || itemSchema == nil || candidate.schema == itemSchema) + } ?? TableInfo(name: name, type: type, rowCount: nil, schema: itemSchema) + return DatabaseTreeTableRef(database: database, schema: schema ?? table.schema, table: table) } } diff --git a/apple/TablePro/Views/TableListing/ObjectListingBar.swift b/apple/TablePro/Views/TableListing/ObjectListingBar.swift index 29b1f5cb45..9d7e239726 100644 --- a/apple/TablePro/Views/TableListing/ObjectListingBar.swift +++ b/apple/TablePro/Views/TableListing/ObjectListingBar.swift @@ -5,15 +5,45 @@ import SwiftUI +/// The Objects tab's tool strip: the object commands on the left, then what narrows the list on the right. internal struct ObjectListingBar: View { @ObservedObject var model: TableListingViewModel + @ObservedObject var list: ObjectListingList let kinds: [SidebarObjectKind] let kindTitle: (SidebarObjectKind) -> String let onSelectKind: (SidebarObjectKind) -> Void var body: some View { + let availability = model.commandAvailability VStack(spacing: 0) { HStack(spacing: 8) { + HStack(spacing: 2) { + command(String(localized: "Open"), "arrow.up.forward.square", "objects-open-button", + enabled: availability.canOpen, model.openSelection) + command(String(localized: "Show Structure"), "pencil.and.ruler", "objects-design-button", + enabled: availability.canDesign, model.designSelection) + command(String(localized: "New Table"), "plus.circle", "objects-new-button", + enabled: availability.canCreate, model.createObject) + command(String(localized: "Delete"), "minus.circle", "objects-delete-button", + enabled: availability.canDelete, model.deleteSelection) + groupDivider + command(String(localized: "Import"), "square.and.arrow.down", "objects-import-button", + enabled: availability.canImport, model.importData) + command(String(localized: "Export"), "square.and.arrow.up", "objects-export-button", + enabled: availability.canExport, model.exportSelection) + groupDivider + PaneRefreshControls( + isRefreshing: model.isRefreshing, + lastRefreshDate: nil, + accessibilityIdentifier: "objects-refresh-button" + ) { + model.reload() + } + .buttonStyle(.borderless) + } + + Spacer(minLength: 8) + Picker(String(localized: "Object Kind"), selection: kindSelection) { ForEach(kinds, id: \.self) { kind in Text(kindTitle(kind)).tag(kind) @@ -28,36 +58,52 @@ internal struct ObjectListingBar: View { text: $model.filterText, placeholder: String(localized: "Filter by Name"), controlSize: .small, - maxWidth: 240, + maxWidth: 200, accessibilityIdentifier: "objects-name-filter" ) .disabled(!model.rowsNameObjects) - Spacer(minLength: 8) - if let count = model.count { ObjectListingCountText(count: count) .font(.callout) .foregroundStyle(.secondary) .monospacedDigit() - } - - PaneRefreshControls( - isRefreshing: model.isRefreshing, - lastRefreshDate: nil, - accessibilityIdentifier: "objects-refresh-button" - ) { - model.reload() + .fixedSize() } } .padding(.horizontal, 10) - .padding(.vertical, 6) + .padding(.vertical, 5) Divider() } .paneBarBackground() } + private var groupDivider: some View { + Divider() + .frame(height: 16) + .padding(.horizontal, 4) + } + + private func command( + _ title: String, + _ symbol: String, + _ identifier: String, + enabled: Bool, + _ action: @escaping () -> Void + ) -> some View { + Button(action: action) { + Label(title, systemImage: symbol) + .frame(width: 24, height: 20) + } + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .disabled(!enabled) + .help(title) + .accessibilityLabel(title) + .accessibilityIdentifier(identifier) + } + private var kindSelection: Binding { Binding(get: { model.target.kind }, set: { onSelectKind($0) }) } diff --git a/apple/TablePro/Views/TableListing/ObjectListingMenu.swift b/apple/TablePro/Views/TableListing/ObjectListingMenu.swift index 3dc6d5ba1b..fd8cb4bb23 100644 --- a/apple/TablePro/Views/TableListing/ObjectListingMenu.swift +++ b/apple/TablePro/Views/TableListing/ObjectListingMenu.swift @@ -5,13 +5,18 @@ import Foundation -/// What a row of the Objects tab does, routed to the coordinator commands the sidebar's rows run. +/// What a row or the tool strip of the Objects tab does, routed to the coordinator commands the +/// sidebar's rows and the menu bar run. internal enum ObjectListingAction: Equatable { case open(ObjectListingItem) case openInNewTab(ObjectListingItem) case showStructure(ObjectListingItem) case showSource(ObjectListingItem) case copyNames([String]) + case createTable + case importData + case export([ObjectListingItem]) + case drop([ObjectListingItem]) } internal struct ObjectListingMenuCommand: Equatable { @@ -57,3 +62,48 @@ internal enum ObjectListingMenu { count == 1 ? String(localized: "Copy Name") : String(format: String(localized: "Copy %lld Names"), count) } } + +/// What the coordinator knows about the connection that the tool strip's buttons depend on. +internal struct ObjectListingCommandFacts: Equatable { + /// Safe mode blocks every write. + var isReadOnly = true + var canCreateTable = false + /// The connection imports at least one format. + var canImport = false + /// The engine has a drop statement for every selected object. + var canDropSelection = false +} + +/// Which of the tool strip's buttons apply to the selection, the kind and the connection. +internal struct ObjectListingCommandAvailability: Equatable { + var canOpen = false + var canDesign = false + var canCreate = false + var canDelete = false + var canImport = false + var canExport = false + + internal static let none = ObjectListingCommandAvailability() + + /// Open and Design act on one object, as a double click does. Delete and Export act on tables and + /// other relations only: a routine or a type has its own drop path in the sidebar, and nothing exports one. + internal static func resolve( + kind: SidebarObjectKind, + selection: [ObjectListingItem], + facts: ObjectListingCommandFacts + ) -> ObjectListingCommandAvailability { + let relations = selection.filter { item in + if case .relation = item { return true } + return false + } + let selectsOnlyRelations = !selection.isEmpty && relations.count == selection.count + return ObjectListingCommandAvailability( + canOpen: selection.count == 1, + canDesign: selection.count == 1 && selectsOnlyRelations, + canCreate: kind == .table && facts.canCreateTable && !facts.isReadOnly, + canDelete: selectsOnlyRelations && facts.canDropSelection && !facts.isReadOnly, + canImport: kind == .table && facts.canImport && !facts.isReadOnly, + canExport: selectsOnlyRelations + ) + } +} diff --git a/apple/TablePro/Views/TableListing/ObjectListingTableView.swift b/apple/TablePro/Views/TableListing/ObjectListingTableView.swift new file mode 100644 index 0000000000..3d9bb82da8 --- /dev/null +++ b/apple/TablePro/Views/TableListing/ObjectListingTableView.swift @@ -0,0 +1,437 @@ +// +// ObjectListingTableView.swift +// TablePro +// + +import AppKit +import Combine +import SwiftUI + +/// The Objects tab's rows as a list in the system font: the sidebar's glyph before each name, sortable +/// headers, columns shown or hidden from the header's menu, multi-select, the row menu, and a double +/// click or Return to open. +/// +/// AppKit on purpose. The data grid draws records: monospaced cells, row numbers and a cell cursor, +/// which a list of objects has no use for. A SwiftUI `Table` cannot hide a column from the header's +/// menu or draw a records header and selection through `ThemeTableHeaderView` and `ThemeTableChrome`. +internal struct ObjectListingTableView: NSViewRepresentable { + @ObservedObject var list: ObjectListingList + let model: TableListingViewModel + + func makeCoordinator() -> ObjectListingTableCoordinator { + ObjectListingTableCoordinator(list: list, model: model) + } + + func makeNSView(context: Context) -> NSScrollView { + context.coordinator.makeScrollView() + } + + func updateNSView(_ scrollView: NSScrollView, context: Context) { + context.coordinator.model = model + context.coordinator.sync() + } +} + +/// Return opens and Copy copies the selected names. `NSTableView` routes neither on its own. +internal final class ObjectListingNSTableView: NSTableView { + internal weak var coordinator: ObjectListingTableCoordinator? + + override internal func insertNewline(_ sender: Any?) { + coordinator?.openSelection() + } + + @objc internal func copy(_ sender: Any?) { + coordinator?.copySelectedNames() + } + + override internal func validateUserInterfaceItem(_ item: any NSValidatedUserInterfaceItem) -> Bool { + if item.action == #selector(copy(_:)) { + return !selectedRowIndexes.isEmpty + } + return super.validateUserInterfaceItem(item) + } +} + +/// A right-click on the header lists the columns to show or hide. +internal final class ObjectListingHeaderView: ThemeTableHeaderView { + internal weak var coordinator: ObjectListingTableCoordinator? + + override internal func menu(for event: NSEvent) -> NSMenu? { + coordinator?.columnMenu() ?? super.menu(for: event) + } +} + +@MainActor +internal final class ObjectListingTableCoordinator: NSObject { + private static let rowHeight: CGFloat = 22 + + private(set) var list: ObjectListingList + weak var model: TableListingViewModel? + + private weak var tableView: ObjectListingNSTableView? + // Held here: its theme subscription and the row views hold it weakly. + private var themeChrome: ThemeTableChrome? + private var themeSubscription: AnyCancellable? + private var builtColumnIDs: [String] = [] + private var appliedRevision: Int? + private var isApplyingSort = false + private var isApplyingSelection = false + + init(list: ObjectListingList, model: TableListingViewModel) { + self.list = list + self.model = model + } + + func makeScrollView() -> NSScrollView { + let tableView = ObjectListingNSTableView() + tableView.coordinator = self + tableView.dataSource = self + tableView.delegate = self + tableView.style = .fullWidth + tableView.rowSizeStyle = .custom + tableView.rowHeight = Self.rowHeight + tableView.usesAlternatingRowBackgroundColors = true + tableView.gridStyleMask = [] + tableView.allowsMultipleSelection = true + tableView.allowsEmptySelection = true + tableView.allowsColumnReordering = true + tableView.allowsColumnResizing = true + tableView.columnAutoresizingStyle = .lastColumnOnlyAutoresizingStyle + tableView.target = self + tableView.doubleAction = #selector(openClickedRow) + tableView.setAccessibilityLabel(String(localized: "Objects")) + tableView.setAccessibilityIdentifier("objects-list") + + let header = ObjectListingHeaderView() + header.coordinator = self + tableView.headerView = header + + let rowMenu = NSMenu() + rowMenu.delegate = self + tableView.menu = rowMenu + + let scrollView = NSScrollView() + scrollView.documentView = tableView + scrollView.hasVerticalScroller = true + scrollView.hasHorizontalScroller = true + scrollView.autohidesScrollers = true + self.tableView = tableView + + buildColumnsIfNeeded() + // Attached once the table sits in its scroll view and before it builds rows: the chrome + // records the scroll view's background to give it back. + themeChrome = ThemeTableChrome(tableView: tableView, family: .records) + themeSubscription = ThemeScope.live.changes + .sink { [weak self] _ in self?.restyleVisibleCells() } + sync() + return scrollView + } + + /// Brings the table up to the list: columns, then rows, then the sort arrow and the selection. + func sync() { + guard let tableView else { return } + buildColumnsIfNeeded() + applyColumnVisibility() + applySortIndicator() + if appliedRevision != list.revision { + appliedRevision = list.revision + // A reload keeps the selected positions, which may now hold other objects; the list's + // selection by object is put back right after. + isApplyingSelection = true + tableView.reloadData() + isApplyingSelection = false + } + applySelection() + } + + // MARK: - Columns + + private func buildColumnsIfNeeded() { + guard let tableView else { return } + let ids = list.columns.map(\.id) + guard ids != builtColumnIDs else { return } + builtColumnIDs = ids + for column in tableView.tableColumns { + tableView.removeTableColumn(column) + } + for column in list.columns { + let tableColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(column.id)) + tableColumn.headerCell = ThemeTableHeaderCell() + tableColumn.title = column.title + tableColumn.headerToolTip = column.title + tableColumn.minWidth = 40 + tableColumn.width = list.columnWidths[column.id] ?? Self.defaultWidth(of: column) + tableColumn.sortDescriptorPrototype = NSSortDescriptor( + key: column.id, + // Numbers and dates read largest or newest first; names read A to Z. + ascending: column.format == .text + ) + tableColumn.isHidden = !list.isShown(column) + tableView.addTableColumn(tableColumn) + } + } + + // Hiding keeps the column's place and width. The list has a dozen columns at most, so the cost + // `isHidden` has on a wide grid does not apply. + private func applyColumnVisibility() { + guard let tableView else { return } + for column in list.columns { + guard let tableColumn = tableView.tableColumn(withIdentifier: NSUserInterfaceItemIdentifier(column.id)) else { + continue + } + let hidden = !list.isShown(column) + if tableColumn.isHidden != hidden { + tableColumn.isHidden = hidden + } + } + } + + private static func defaultWidth(of column: ObjectListingColumn) -> CGFloat { + if column.id == "name" { return 240 } + switch column.format { + case .count, .bytes: return 96 + case .date: return 150 + case .text: return column.id == "comment" ? 240 : 130 + } + } + + func columnMenu() -> NSMenu { + let menu = NSMenu() + for column in list.columns where column.id != "name" { + let item = NSMenuItem(title: column.title, action: #selector(toggleColumn(_:)), keyEquivalent: "") + item.target = self + item.representedObject = column.id + item.state = list.isShown(column) ? .on : .off + menu.addItem(item) + } + return menu + } + + @objc private func toggleColumn(_ sender: NSMenuItem) { + guard let id = sender.representedObject as? String, + let column = list.columns.first(where: { $0.id == id }) + else { return } + list.setColumn(id, shown: !list.isShown(column)) + applyColumnVisibility() + } + + // MARK: - Sort + + private func applySortIndicator() { + guard let tableView else { return } + let descriptors = list.sort.map { [NSSortDescriptor(key: $0.columnID, ascending: $0.ascending)] } ?? [] + if tableView.sortDescriptors != descriptors { + // Setting the descriptors calls back into `sortDescriptorsDidChange`. + isApplyingSort = true + tableView.sortDescriptors = descriptors + isApplyingSort = false + } + // AppKit reports no sort direction to VoiceOver on its own. + for tableColumn in tableView.tableColumns { + let direction: NSAccessibilitySortDirection + if let sort = list.sort, sort.columnID == tableColumn.identifier.rawValue { + direction = sort.ascending ? .ascending : .descending + } else { + direction = .unknown + } + tableColumn.headerCell.setAccessibilitySortDirection(direction) + } + } + + // MARK: - Selection + + private func applySelection() { + guard let tableView else { return } + let wanted = IndexSet(list.rows.indices.filter { list.selection.contains(list.rows[$0].item.key) }) + guard tableView.selectedRowIndexes != wanted else { return } + isApplyingSelection = true + tableView.selectRowIndexes(wanted, byExtendingSelection: false) + isApplyingSelection = false + } + + private func row(at index: Int) -> ObjectListingRow? { + list.rows.indices.contains(index) ? list.rows[index] : nil + } + + private var selectedRows: [ObjectListingRow] { + tableView?.selectedRowIndexes.compactMap(row(at:)) ?? [] + } + + // MARK: - Commands + + @objc private func openClickedRow() { + guard let tableView, let row = row(at: tableView.clickedRow) else { return } + model?.open(row.item) + } + + func openSelection() { + model?.openSelection() + } + + func copySelectedNames() { + let names = selectedRows.map(\.item.name) + guard !names.isEmpty else { return } + ClipboardService.shared.writeText(names.joined(separator: ",")) + } + + // MARK: - Theme + + private func restyleVisibleCells() { + tableView?.enumerateAvailableRowViews { rowView, _ in + for index in 0 ..< rowView.numberOfColumns { + (rowView.view(atColumn: index) as? ObjectListingCellView)?.applyStyle() + } + } + } +} + +extension ObjectListingTableCoordinator: NSTableViewDataSource, NSTableViewDelegate { + func numberOfRows(in tableView: NSTableView) -> Int { + list.rows.count + } + + func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row index: Int) -> NSView? { + guard let tableColumn, let row = row(at: index), + let column = list.columns.first(where: { $0.id == tableColumn.identifier.rawValue }) + else { return nil } + let isName = column.id == "name" + let identifier = isName ? ObjectListingCellView.nameIdentifier : ObjectListingCellView.valueIdentifier + let cell = tableView.makeView(withIdentifier: identifier, owner: nil) as? ObjectListingCellView + ?? ObjectListingCellView(identifier: identifier, showsGlyph: isName) + let text = row.texts.indices.contains(column.valueIndex) ? row.texts[column.valueIndex] : "" + cell.configure( + text: text, + alignsTrailing: column.format.alignsTrailing, + glyph: isName ? row.iconName : nil, + glyphLabel: isName ? row.item.kindName : nil + ) + return cell + } + + func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { + themeChrome?.makeRowView(in: tableView) + } + + func tableView(_ tableView: NSTableView, typeSelectStringFor tableColumn: NSTableColumn?, row index: Int) -> String? { + guard tableColumn?.identifier.rawValue == "name" else { return nil } + return row(at: index)?.item.name + } + + func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { + guard !isApplyingSort else { return } + // One key at a time: a click replaces the sort rather than adding a second key behind it. + let sort = tableView.sortDescriptors.first.flatMap { descriptor in + descriptor.key.map { ObjectListingSort(columnID: $0, ascending: descriptor.ascending) } + } + list.setSort(sort) + sync() + } + + func tableViewSelectionDidChange(_ notification: Notification) { + guard !isApplyingSelection, themeChrome?.isRebuildingRows != true else { return } + list.select(Set(selectedRows.map(\.item.key))) + } + + func tableViewColumnDidResize(_ notification: Notification) { + guard let column = notification.userInfo?["NSTableColumn"] as? NSTableColumn else { return } + list.columnWidths[column.identifier.rawValue] = column.width + } +} + +extension ObjectListingTableCoordinator: NSMenuDelegate { + /// Built from `clickedRow`, so the clicked row's highlight is AppKit's own. The menu acts on the + /// selection when the clicked row is part of it, else on the clicked row alone. + func menuNeedsUpdate(_ menu: NSMenu) { + menu.removeAllItems() + guard let tableView, let model, let clicked = row(at: tableView.clickedRow) else { return } + let targets = tableView.selectedRowIndexes.contains(tableView.clickedRow) ? selectedRows.map(\.item) : [clicked.item] + for item in model.menuItems(clicked: clicked.item, targets: targets) { + menu.addItem(item) + } + } +} + +/// One line of text, with the object's glyph in the Name column. +internal final class ObjectListingCellView: NSTableCellView { + internal static let nameIdentifier = NSUserInterfaceItemIdentifier("ObjectListingNameCell") + internal static let valueIdentifier = NSUserInterfaceItemIdentifier("ObjectListingValueCell") + + private let label = NSTextField(labelWithString: "") + private let glyph = NSImageView() + + internal init(identifier: NSUserInterfaceItemIdentifier, showsGlyph: Bool) { + super.init(frame: .zero) + self.identifier = identifier + label.lineBreakMode = .byTruncatingTail + label.cell?.usesSingleLineMode = true + label.translatesAutoresizingMaskIntoConstraints = false + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + addSubview(label) + textField = label + + var constraints = [ + label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4), + label.centerYAnchor.constraint(equalTo: centerYAnchor), + ] + if showsGlyph { + glyph.translatesAutoresizingMaskIntoConstraints = false + glyph.imageScaling = .scaleProportionallyDown + addSubview(glyph) + imageView = glyph + constraints += [ + glyph.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 4), + glyph.centerYAnchor.constraint(equalTo: centerYAnchor), + glyph.widthAnchor.constraint(equalToConstant: 16), + glyph.heightAnchor.constraint(equalToConstant: 16), + label.leadingAnchor.constraint(equalTo: glyph.trailingAnchor, constant: 6), + ] + } else { + constraints.append(label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 4)) + } + NSLayoutConstraint.activate(constraints) + } + + @available(*, unavailable) + internal required init?(coder: NSCoder) { + fatalError("ObjectListingCellView does not support NSCoder init") + } + + override internal var backgroundStyle: NSView.BackgroundStyle { + didSet { applyStyle() } + } + + internal func configure(text: String, alignsTrailing: Bool, glyph symbol: String?, glyphLabel: String?) { + label.stringValue = text + label.alignment = alignsTrailing ? .right : .natural + // Digits of one width, so counts and sizes line up down the column. + label.font = alignsTrailing + ? .monospacedDigitSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) + : .systemFont(ofSize: NSFont.systemFontSize) + if let symbol { + glyph.image = NSImage(systemSymbolName: symbol, accessibilityDescription: glyphLabel) + } + applyStyle() + } + + /// Also run on a theme change: a field redraws only when it is handed a new color. + internal func applyStyle() { + let isEmphasized = backgroundStyle == .emphasized + let slot = ThemeTableChrome.recordsTextSlot( + onEmphasizedSelection: isEmphasized, + highContrast: NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast + ) + label.textColor = slot.map { ThemeScope.live.palette[$0] } ?? .labelColor + // The sidebar's tint for the same glyph, turning white on the emphasized selection as the text does. + glyph.contentTintColor = isEmphasized ? .alternateSelectedControlTextColor : .controlAccentColor + } +} + +extension ObjectListingItem { + /// What VoiceOver says the glyph shows. + var kindName: String { + switch self { + case .relation(_, _, let type): return TableRowLogic.accessibilityKindLabel(for: type) + case .sourced(let ref): return ref.kind.displayName + } + } +} diff --git a/apple/TablePro/Views/TableListing/TableListingTabView.swift b/apple/TablePro/Views/TableListing/TableListingTabView.swift index 08aaf24cb4..1608ff3795 100644 --- a/apple/TablePro/Views/TableListing/TableListingTabView.swift +++ b/apple/TablePro/Views/TableListing/TableListingTabView.swift @@ -6,6 +6,7 @@ import SwiftUI // Read-only and complete, so a header click sorts the rows on hand rather than re-running anything. +// Rows that name objects show in the list; anything else keeps the data grid. internal struct TableListingTabView: View { @ObservedObject var model: TableListingViewModel let databaseType: DatabaseType @@ -17,6 +18,7 @@ internal struct TableListingTabView: View { VStack(spacing: 0) { ObjectListingBar( model: model, + list: model.list, kinds: kinds, kindTitle: kindTitle, onSelectKind: onSelectKind @@ -43,7 +45,13 @@ internal struct TableListingTabView: View { emptyState(listing) case .loaded(let listing): VStack(spacing: 0) { - rowsGrid + if model.rowsNameObjects { + // A retarget hands this view a new list, which a new table shows from scratch. + ObjectListingTableView(list: model.list, model: model) + .id(ObjectIdentifier(model.list)) + } else { + rowsGrid + } if let notice = listing.notice { noticeBar(notice) } @@ -92,22 +100,19 @@ internal struct TableListingTabView: View { .statusBarChrome() } + // A shell command's rows, such as a Redis SCAN page, name no object: they stay plain values in the grid. private var rowsGrid: some View { DataGridView(model: model.grid.model) - .onAppear { model.grid.model.configuration = configuration(opensRows: model.rowsNameObjects) } - .onChange(of: model.rowsNameObjects) { opensRows in - model.grid.model.configuration = configuration(opensRows: opensRows) - } + .onAppear { model.grid.model.configuration = configuration } } - // A row that names an object opens it; a shell command's rows keep the cell viewer. - private func configuration(opensRows: Bool) -> DataGridConfiguration { + private var configuration: DataGridConfiguration { var configuration = DataGridConfiguration() configuration.traits = DataGridEngineTraits(databaseType: databaseType) configuration.showRowNumbers = true configuration.supportsValueFilter = false configuration.appliesRowCopyFormat = true - configuration.commands = opensRows ? [.freezeColumns, .displayAs, .openRow] : [.freezeColumns, .displayAs] + configuration.commands = [.freezeColumns, .displayAs] return configuration } } diff --git a/apple/TableProTests/ViewModels/ObjectListingListTests.swift b/apple/TableProTests/ViewModels/ObjectListingListTests.swift new file mode 100644 index 0000000000..df9d5939af --- /dev/null +++ b/apple/TableProTests/ViewModels/ObjectListingListTests.swift @@ -0,0 +1,177 @@ +// +// ObjectListingListTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ObjectListingListTests { + private let defaults: EphemeralDefaults + + init() throws { + defaults = try EphemeralDefaults() + } + + private func makeList(kind: SidebarObjectKind = .table) -> ObjectListingList { + ObjectListingList( + kind: kind, + containerName: "shop", + visibility: ObjectListingColumnVisibilityStore(defaults: defaults.defaults), + formatter: { ObjectListingValueFormatter(locale: Locale(identifier: "en_US"), timeZone: .current) } + ) + } + + /// A Tables listing of `names`, each row carrying a size in bytes. + private func listing(_ names: [String], sizes: [String]? = nil) -> TableListing { + let rows = names.enumerated().map { index, name -> [PluginCellValue] in + [.text("shop"), .text(name), .text(sizes?[index] ?? "16384")] + } + let tableRows = TableRows.from( + queryRows: rows, + columns: ["Schema", "Name", "Data Length"], + columnTypes: Array(repeating: .text(rawType: nil), count: 3) + ) + var items: [RowID: ObjectListingItem] = [:] + for (index, name) in names.enumerated() { + items[.existing(index)] = .relation(name: name, schema: nil, type: .table) + } + return TableListing( + rows: tableRows, isIncomplete: false, statusMessage: nil, items: items, + columnKeys: ["schema", "name", "data_size"] + ) + } + + private func key(_ name: String) -> ObjectListingItem.Key { + ObjectListingItem.relation(name: name, schema: nil, type: .table).key + } + + private func names(_ list: ObjectListingList) -> [String] { + list.rows.map { $0.item.name } + } + + @Test("A listing reaches the list in its own order, formatted, with its columns") + func listingReachesTheList() { + let list = makeList() + + list.show(listing(["orders", "customers"], sizes: ["163840", "16384"]), filterText: "") + + #expect(names(list) == ["orders", "customers"]) + #expect(list.columns.map { $0.id } == ["name", "data_size", "schema"]) + #expect(list.shownColumns.map { $0.id } == ["name", "data_size"]) + #expect(list.rows.first?.texts[2] != "163840") + } + + // Held by object, so a table created above the selected one does not move the selection to its neighbour. + @Test("A new listing keeps the selection on the same objects, and drops the ones that went") + func selectionFollowsItsObjects() { + let list = makeList() + list.show(listing(["customers", "orders"]), filterText: "") + list.select([key("orders")]) + + list.show(listing(["accounts", "customers", "orders"]), filterText: "") + #expect(list.selectedItems.map { $0.name } == ["orders"]) + + list.show(listing(["accounts", "customers"]), filterText: "") + #expect(list.selection.isEmpty) + } + + @Test("A sort orders the rows by the column's values, keeps the selection, and orders the next listing too") + func sortOrdersTheRows() { + let list = makeList() + var sortChanges = 0 + list.onSortChange = { sortChanges += 1 } + list.show(listing(["small", "large", "medium"], sizes: ["16384", "2050000000", "163840"]), filterText: "") + list.select([key("small")]) + + list.setSort(ObjectListingSort(columnID: "data_size", ascending: false)) + + #expect(names(list) == ["large", "medium", "small"]) + #expect(list.selectedItems.map { $0.name } == ["small"]) + #expect(sortChanges == 1) + + list.show(listing(["tiny", "large"], sizes: ["1", "2050000000"]), filterText: "") + #expect(names(list) == ["large", "tiny"]) + } + + @Test("The filter narrows the rows, and a row it hides leaves the selection") + func filterNarrowsTheRows() { + let list = makeList() + list.show(listing(["orders", "order_items", "customers"]), filterText: "") + list.select([key("orders"), key("customers")]) + + list.applyFilter("ORDER") + + #expect(names(list) == ["orders", "order_items"]) + #expect(list.selectedItems.map { $0.name } == ["orders"]) + + list.applyFilter("") + #expect(names(list) == ["orders", "order_items", "customers"]) + } + + @Test("A row with no object behind it is not listed, since nothing could open it") + func rowsWithoutAnObjectAreLeftOut() { + let list = makeList() + let source = listing(["orders", "customers"]) + let partial = TableListing( + rows: source.rows, isIncomplete: false, statusMessage: nil, + items: [.existing(1): .relation(name: "customers", schema: nil, type: .table)], + columnKeys: source.columnKeys + ) + + list.show(partial, filterText: "") + + #expect(names(list) == ["customers"]) + } + + @Test("Rows replaced move the revision, and a selection alone leaves it, so the table reloads only for rows") + func revisionMovesWithRows() { + let list = makeList() + list.show(listing(["orders"]), filterText: "") + let shown = list.revision + + list.select([key("orders")]) + #expect(list.revision == shown) + + list.setSort(ObjectListingSort(columnID: "name", ascending: false)) + #expect(list.revision != shown) + } + + @Test("A column the reader shows or hides stays that way for every tab of the kind, and Name never hides") + func columnChoicesPersistPerKind() throws { + let list = makeList() + list.show(listing(["orders"]), filterText: "") + let schema = try #require(list.columns.first { $0.id == "schema" }) + let size = try #require(list.columns.first { $0.id == "data_size" }) + + list.setColumn("schema", shown: true) + list.setColumn("data_size", shown: false) + list.setColumn("name", shown: false) + + #expect(list.isShown(schema)) + #expect(!list.isShown(size)) + #expect(list.shownColumns.map { $0.id } == ["name", "schema"]) + + let nextTab = makeList() + nextTab.show(listing(["customers"]), filterText: "") + #expect(nextTab.shownColumns.map { $0.id } == ["name", "schema"]) + + let views = makeList(kind: .view) + views.show(listing(["recent_orders"]), filterText: "") + #expect(views.shownColumns.map { $0.id } == ["name", "data_size"]) + } + + @Test("A column the listing does not have is not recorded") + func unknownColumnsAreNotRecorded() { + let list = makeList() + list.show(listing(["orders"]), filterText: "") + + list.setColumn("engine", shown: true) + + #expect(ObjectListingColumnVisibilityStore(defaults: defaults.defaults).choices(for: .table).isEmpty) + } +} diff --git a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift index 5c54101bd0..06de51cb80 100644 --- a/apple/TableProTests/ViewModels/TableListingViewModelTests.swift +++ b/apple/TableProTests/ViewModels/TableListingViewModelTests.swift @@ -148,6 +148,12 @@ struct TableListingViewModelTests { private let tabId = UUID() private let refreshRequests = PassthroughSubject() + // The list reads the reader's column choices; each case gets its own, so none leaks into the next. + private let defaults: EphemeralDefaults + + init() throws { + defaults = try EphemeralDefaults() + } private func makeViewModel( databaseType: DatabaseType = .postgresql, @@ -157,6 +163,7 @@ struct TableListingViewModelTests { kind: SidebarObjectKind = .table, objectSource: ScriptedObjectSource? = nil, perform: @escaping (ObjectListingAction) -> Void = { _ in }, + commandFacts: @escaping ([ObjectListingItem]) -> ObjectListingCommandFacts = { _ in ObjectListingCommandFacts() }, onInteraction: @escaping () -> Void = {} ) -> (TableListingViewModel, ScriptedListingProvider) { let provider = ScriptedListingProvider( @@ -171,6 +178,8 @@ struct TableListingViewModelTests { objectSource: objectSource ?? ScriptedObjectSource(), refreshRequests: refreshRequests.eraseToAnyPublisher(), perform: perform, + commandFacts: commandFacts, + columnVisibility: ObjectListingColumnVisibilityStore(defaults: defaults.defaults), onInteraction: onInteraction ) return (viewModel, provider) @@ -405,65 +414,70 @@ struct TableListingViewModelTests { #expect(store.model(forTab: openId, target: open.target) { closing } === open) } - // MARK: - Grid + // MARK: - List + + private func listNames(_ viewModel: TableListingViewModel) -> [String] { + viewModel.list.rows.map { $0.item.name } + } private func gridNames(_ viewModel: TableListingViewModel) -> [String] { viewModel.grid.model.rows.rows.map { $0.values.first.flatMap { $0.asText } ?? "" } } - @Test("A landed listing reaches the tab's grid") - func listingReachesTheGrid() async { + private func table(_ name: String) -> ObjectListingItem { + .relation(name: name, schema: "sales", type: .table) + } + + private func nameSort(ascending: Bool) -> ObjectListingSort { + ObjectListingSort(columnID: "name", ascending: ascending) + } + + @Test("A landed listing of objects reaches the tab's list, and the grid stays empty") + func listingReachesTheList() async { let (viewModel, provider) = makeViewModel() provider.answer(with: .names(["orders", "customers"])) await viewModel.reload().value - #expect(gridNames(viewModel) == ["orders", "customers"]) - #expect(viewModel.grid.model.rowCount == 2) - #expect(viewModel.grid.model.store.layoutScope == .ephemeral) + #expect(listNames(viewModel) == ["orders", "customers"]) + #expect(viewModel.list.columns.map { $0.id } == ["name"]) + #expect(viewModel.grid.model.rowCount == 0) } @Test("A header sort orders the listed tables, and the selection stays on the same table") - func headerSortOrdersTheHeldRows() async throws { + func headerSortOrdersTheRows() async { let (viewModel, provider) = makeViewModel() provider.answer(with: .names(["orders", "customers", "accounts"])) await viewModel.reload().value - let model = viewModel.grid.model - let orders = try #require(model.rowID(at: 0)) - model.selectRows([orders]) + viewModel.list.select([table("orders").key]) - model.setSort(SortState(columns: [SortColumn(columnIndex: 0, direction: .ascending)], source: .user)) + viewModel.list.setSort(nameSort(ascending: true)) - #expect(gridNames(viewModel) == ["accounts", "customers", "orders"]) - #expect(model.selectedRowIDs == [orders]) - #expect(model.displayIndex(of: orders) == 2) + #expect(listNames(viewModel) == ["accounts", "customers", "orders"]) + #expect(viewModel.list.selectedItems == [table("orders")]) } - // Row ids are positions, so without this a table created above the selected one moved the highlight - // to its neighbour, and Return or the menu acted on the wrong table. + // Row ids are positions, so a selection held by them moved to a neighbour when a table was created + // above the selected one, and Return or the menu acted on the wrong table. @Test("A refresh keeps the selection on the same object, and clears it when the object went") - func selectionFollowsItsObjectAcrossARefresh() async throws { + func selectionFollowsItsObjectAcrossARefresh() async { var actions: [ObjectListingAction] = [] let (viewModel, provider) = makeViewModel(perform: { actions.append($0) }) provider.answer(with: .names(["customers", "orders"])) await viewModel.reload().value - let model = viewModel.grid.model - model.selectCell(GridCoord(row: 1, displayColumn: 0)) - #expect(model.selectedRowIDs == [.existing(1)]) + viewModel.list.select([table("orders").key]) provider.answer(with: .names(["accounts", "customers", "orders"])) await viewModel.reload().value - let selected = try #require(model.selectedRowIDs.first) - #expect(model.selectedRowIDs.count == 1) - #expect(viewModel.state.value?.items[selected]?.name == "orders") - viewModel.grid.gridOpenRow(selected) - #expect(actions == [.open(.relation(name: "orders", schema: "sales", type: .table))]) + #expect(viewModel.list.selectedItems == [table("orders")]) + viewModel.openSelection() + #expect(actions == [.open(table("orders"))]) provider.answer(with: .names(["accounts", "customers"])) await viewModel.reload().value - #expect(model.selectedRowIDs.isEmpty) + #expect(viewModel.list.selection.isEmpty) } @Test("The sort the reader chose orders the next listing too") @@ -471,15 +485,15 @@ struct TableListingViewModelTests { let (viewModel, provider) = makeViewModel() provider.answer(with: .names(["orders", "customers"])) await viewModel.reload().value - let descending = SortState(columns: [SortColumn(columnIndex: 0, direction: .descending)], source: .user) - viewModel.grid.model.setSort(descending) + viewModel.list.setSort(nameSort(ascending: false)) provider.answer(with: .names(["accounts", "orders", "zones"])) await viewModel.reload().value - #expect(gridNames(viewModel) == ["zones", "orders", "accounts"]) - #expect(viewModel.grid.model.store.sortState == descending) + #expect(listNames(viewModel) == ["zones", "orders", "accounts"]) + #expect(viewModel.list.sort == nameSort(ascending: false)) } + // MARK: - Other kinds private func functions(_ names: String...) -> CatalogObjectList { @@ -567,37 +581,36 @@ struct TableListingViewModelTests { source.reply = .fetched(functions("touch", "audit", "archive_orders")) let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) await viewModel.loadIfNeeded()?.value - let model = viewModel.grid.model - model.setSort(SortState(columns: [SortColumn(columnIndex: 0, direction: .ascending)], source: .user)) + viewModel.list.setSort(nameSort(ascending: true)) viewModel.filterText = "a" - #expect(gridNames(viewModel) == ["archive_orders", "audit"]) - model.selectCell(GridCoord(row: 1, displayColumn: 0)) + #expect(listNames(viewModel) == ["archive_orders", "audit"]) + let audit = try #require(viewModel.list.rows.last?.item) + viewModel.list.select([audit.key]) // A statement created two functions, one of them listed before the selected one. source.changes.send(functions("purge", "touch", "audit", "archive_orders", "alert")) - #expect(gridNames(viewModel) == ["alert", "archive_orders", "audit"]) + #expect(listNames(viewModel) == ["alert", "archive_orders", "audit"]) #expect(viewModel.count == ObjectListingCount(shown: 3, total: 5)) - let selected = try #require(model.selectedRowIDs.first) - #expect(viewModel.state.value?.items[selected]?.name == "audit") + #expect(viewModel.list.selectedItems.map { $0.name } == ["audit"]) source.changes.send(functions("touch", "archive_orders")) - #expect(gridNames(viewModel) == ["archive_orders"]) - #expect(model.selectedRowIDs.isEmpty) + #expect(listNames(viewModel) == ["archive_orders"]) + #expect(viewModel.list.selection.isEmpty) } - @Test("A list the sidebar commits again unchanged leaves the grid as it is") - func unchangedListLeavesTheGrid() async { + @Test("A list the sidebar commits again unchanged leaves the list as it is") + func unchangedListLeavesTheList() async { let source = ScriptedObjectSource() source.reply = .fetched(functions("touch", "audit")) let (viewModel, _) = makeViewModel(kind: .function, objectSource: source) await viewModel.loadIfNeeded()?.value - let revision = viewModel.grid.model.displayRevision + let revision = viewModel.list.revision source.changes.send(functions("touch", "audit")) - #expect(viewModel.grid.model.displayRevision == revision) + #expect(viewModel.list.revision == revision) } @Test("The sidebar's list leaves a tab with nothing loaded to its own first load") @@ -625,7 +638,7 @@ struct TableListingViewModelTests { viewModel.filterText = "ORDER" - #expect(gridNames(viewModel) == ["orders", "order_items"]) + #expect(listNames(viewModel) == ["orders", "order_items"]) #expect(viewModel.count == ObjectListingCount(shown: 2, total: 3)) #expect(provider.executedQueries.count == 1) #expect(interactions == 1) @@ -644,7 +657,7 @@ struct TableListingViewModelTests { provider.answer(with: .names(["orders", "customers", "customer_notes"])) await viewModel.reload().value - #expect(gridNames(viewModel) == ["customers", "customer_notes"]) + #expect(listNames(viewModel) == ["customers", "customer_notes"]) #expect(viewModel.count == ObjectListingCount(shown: 2, total: 3)) } @@ -655,7 +668,7 @@ struct TableListingViewModelTests { provider.answer(with: .names(["orders", "customers"])) await viewModel.reload().value - viewModel.grid.model.setSort(SortState(columns: [SortColumn(columnIndex: 0, direction: .ascending)], source: .user)) + viewModel.list.setSort(nameSort(ascending: true)) #expect(interactions == 1) } @@ -680,10 +693,10 @@ struct TableListingViewModelTests { let (viewModel, provider) = makeViewModel(perform: { actions.append($0) }, onInteraction: { interactions += 1 }) provider.answer(with: .names(["orders"])) await viewModel.reload().value - let orders = ObjectListingItem.relation(name: "orders", schema: "sales", type: .table) + let orders = table("orders") - viewModel.grid.gridOpenRow(.existing(0)) - let titles = viewModel.grid.gridRowMenuItems(for: [.existing(0)], clickedRow: .existing(0)).map(\.title) + viewModel.open(orders) + let titles = viewModel.menuItems(clicked: orders, targets: [orders]).map { $0.title } #expect(actions == [.open(orders)]) #expect(interactions == 1) @@ -692,23 +705,24 @@ struct TableListingViewModelTests { ]) } - @Test("After a sort and a filter, a row's command acts on the object that row shows") + @Test("After a sort and a filter, Return acts on the object the selected row shows") func rowActionsFollowTheShownRow() async throws { var actions: [ObjectListingAction] = [] let (viewModel, provider) = makeViewModel(perform: { actions.append($0) }) provider.answer(with: .names(["orders", "customers", "order_items"])) await viewModel.reload().value - viewModel.grid.model.setSort(SortState(columns: [SortColumn(columnIndex: 0, direction: .descending)], source: .user)) + viewModel.list.setSort(nameSort(ascending: false)) viewModel.filterText = "order" - let second = try #require(viewModel.grid.model.rowID(at: 1)) - viewModel.grid.gridOpenRow(second) + let second = try #require(viewModel.list.rows.dropFirst().first) + viewModel.list.select([second.item.key]) + viewModel.openSelection() - #expect(gridNames(viewModel) == ["orders", "order_items"]) - #expect(actions == [.open(.relation(name: "order_items", schema: "sales", type: .table))]) + #expect(listNames(viewModel) == ["orders", "order_items"]) + #expect(actions == [.open(table("order_items"))]) } - @Test("A listing with no name column has no filter and no row commands") + @Test("A listing with no name column stays in the grid, with no filter, no list and no commands") func listingWithoutNamesHasNoRowActions() async { var actions: [ObjectListingAction] = [] let (viewModel, provider) = makeViewModel( @@ -718,10 +732,82 @@ struct TableListingViewModelTests { provider.answer(with: .names(["session:1"])) await viewModel.reload().value - viewModel.grid.gridOpenRow(.existing(0)) + viewModel.openSelection() + viewModel.exportSelection() #expect(!viewModel.rowsNameObjects) - #expect(viewModel.grid.gridRowMenuItems(for: [.existing(0)], clickedRow: .existing(0)).isEmpty) + #expect(gridNames(viewModel) == ["session:1"]) + #expect(viewModel.list.rows.isEmpty) + #expect(viewModel.commandAvailability == .none) + #expect(actions.isEmpty) + } + + // MARK: - Tool strip + + private func allowingFacts(_ items: [ObjectListingItem]) -> ObjectListingCommandFacts { + ObjectListingCommandFacts(isReadOnly: false, canCreateTable: true, canImport: true, canDropSelection: !items.isEmpty) + } + + @Test("The tool strip offers what the selection, the kind and the connection allow") + func toolStripFollowsTheSelection() async { + let (viewModel, provider) = makeViewModel(commandFacts: allowingFacts) + provider.answer(with: .names(["orders", "customers"])) + await viewModel.reload().value + + #expect(viewModel.commandAvailability == ObjectListingCommandAvailability(canCreate: true, canImport: true)) + + viewModel.list.select([table("orders").key]) + #expect(viewModel.commandAvailability == ObjectListingCommandAvailability( + canOpen: true, canDesign: true, canCreate: true, canDelete: true, canImport: true, canExport: true + )) + + viewModel.list.select([table("orders").key, table("customers").key]) + #expect(viewModel.commandAvailability == ObjectListingCommandAvailability( + canCreate: true, canDelete: true, canImport: true, canExport: true + )) + } + + @Test("Each tool strip command runs the coordinator's action on the selection, in the list's order, and keeps the preview") + func toolStripCommandsRunTheirActions() async { + var actions: [ObjectListingAction] = [] + var interactions = 0 + let (viewModel, provider) = makeViewModel( + perform: { actions.append($0) }, commandFacts: allowingFacts, onInteraction: { interactions += 1 } + ) + provider.answer(with: .names(["orders", "customers"])) + await viewModel.reload().value + viewModel.list.select([table("customers").key, table("orders").key]) + + viewModel.deleteSelection() + viewModel.exportSelection() + viewModel.createObject() + viewModel.importData() + viewModel.list.select([table("orders").key]) + viewModel.designSelection() + + #expect(actions == [ + .drop([table("orders"), table("customers")]), + .export([table("orders"), table("customers")]), + .createTable, + .importData, + .showStructure(table("orders")), + ]) + #expect(interactions == 5) + } + + @Test("A command the strip does not offer runs nothing, as on a read-only connection") + func refusedCommandsRunNothing() async { + var actions: [ObjectListingAction] = [] + let (viewModel, provider) = makeViewModel(perform: { actions.append($0) }) + provider.answer(with: .names(["orders"])) + await viewModel.reload().value + viewModel.list.select([table("orders").key]) + + viewModel.deleteSelection() + viewModel.createObject() + viewModel.importData() + + #expect(viewModel.commandAvailability.canDelete == false) #expect(actions.isEmpty) } diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index 4b0e38debe..b10eb2375b 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -343,6 +343,52 @@ struct CoordinatorTableListingTests { #expect(tabManager.tabs.first { $0.id == listing }?.isPreview == false) } + // MARK: - Tool strip + + @Test("The strip's drops and exports name the listing's own database, and only its relations") + func stripRefsNameTheListingsDatabase() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("archive"), asPreview: false) + let tab = try #require(tabManager.selectedTab) + + let refs = coordinator.listingTableRefs([ + .relation(name: "orders", schema: nil, type: .table), + .sourced(DatabaseObjectRef(kind: .function, name: "touch", database: "archive", schema: nil)), + ], in: tab) + + #expect(refs.count == 1) + #expect(refs.first?.database == "archive") + #expect(refs.first?.table.name == "orders") + #expect(refs.first?.table.type == .table) + } + + @Test("A read-only connection's strip offers no write") + func readOnlyOffersNoWrite() throws { + let (coordinator, tabManager, _) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.toolbarState.safeModeLevel = .readOnly + coordinator.showObjects(group("shop"), asPreview: false) + let id = try #require(tabManager.selectedTabId) + + let facts = coordinator.listingCommandFacts(for: [.relation(name: "orders", schema: nil, type: .table)], inTab: id) + + #expect(facts == ObjectListingCommandFacts(isReadOnly: true)) + } + + @Test("New Table on a connection whose driver cannot create one opens nothing") + func createTableNeedsADriverThatCreates() throws { + let (coordinator, tabManager, log) = makeCoordinator() + defer { coordinator.teardown() } + coordinator.showObjects(group("archive"), asPreview: false) + let listing = try #require(tabManager.selectedTabId) + + coordinator.performListingAction(.createTable, fromTab: listing) + + #expect(log.payloads.isEmpty) + #expect(tabManager.tabs.count == 1) + } + // MARK: - The browse cursor /// Each database is an entry of its own on the strip, so a listing tab names the entry it shows in. diff --git a/apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift b/apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift index edb7c7b7e8..18c1343c90 100644 --- a/apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift +++ b/apple/TableProTests/Views/TableListing/ObjectListingMenuTests.swift @@ -62,4 +62,64 @@ struct ObjectListingMenuTests { action: .copyNames(["orders", "recent_orders"]) )) } + + // MARK: - Tool strip + + private let writable = ObjectListingCommandFacts(isReadOnly: false, canCreateTable: true, canImport: true, canDropSelection: true) + + @Test("Open and Design act on one object; Delete and Export on every selected relation") + func selectionDecidesTheObjectCommands() { + let one = ObjectListingCommandAvailability.resolve(kind: .table, selection: [orders], facts: writable) + let two = ObjectListingCommandAvailability.resolve(kind: .table, selection: [orders, recent], facts: writable) + let none = ObjectListingCommandAvailability.resolve(kind: .table, selection: [], facts: writable) + + #expect(one == ObjectListingCommandAvailability( + canOpen: true, canDesign: true, canCreate: true, canDelete: true, canImport: true, canExport: true + )) + #expect(two == ObjectListingCommandAvailability(canCreate: true, canDelete: true, canImport: true, canExport: true)) + #expect(none == ObjectListingCommandAvailability(canCreate: true, canImport: true)) + } + + @Test("A routine opens as its source, but has no structure, no drop here and nothing to export") + func sourcedObjectsOnlyOpen() { + let function = ObjectListingCommandAvailability.resolve(kind: .function, selection: [touch], facts: writable) + + #expect(function == ObjectListingCommandAvailability(canOpen: true)) + } + + @Test("New and Import are for tables; another kind's strip offers neither") + func creationAndImportAreForTables() { + let views = ObjectListingCommandAvailability.resolve(kind: .view, selection: [recent], facts: writable) + + #expect(!views.canCreate) + #expect(!views.canImport) + #expect(views.canDelete) + #expect(views.canExport) + } + + @Test("Safe mode turns off every write and keeps reading", arguments: [true, false]) + func readOnlyKeepsOnlyReads(isReadOnly: Bool) { + var facts = writable + facts.isReadOnly = isReadOnly + + let availability = ObjectListingCommandAvailability.resolve(kind: .table, selection: [orders], facts: facts) + + #expect(availability.canCreate == !isReadOnly) + #expect(availability.canDelete == !isReadOnly) + #expect(availability.canImport == !isReadOnly) + #expect(availability.canOpen && availability.canDesign && availability.canExport) + } + + @Test("Each write needs the connection to support it", arguments: [ + ObjectListingCommandFacts(isReadOnly: false, canCreateTable: false, canImport: true, canDropSelection: true), + ObjectListingCommandFacts(isReadOnly: false, canCreateTable: true, canImport: false, canDropSelection: true), + ObjectListingCommandFacts(isReadOnly: false, canCreateTable: true, canImport: true, canDropSelection: false), + ]) + func writesNeedSupport(facts: ObjectListingCommandFacts) { + let availability = ObjectListingCommandAvailability.resolve(kind: .table, selection: [orders], facts: facts) + + #expect(availability.canCreate == facts.canCreateTable) + #expect(availability.canImport == facts.canImport) + #expect(availability.canDelete == facts.canDropSelection) + } } diff --git a/apple/TableProTests/Views/TableListing/ObjectListingTableViewTests.swift b/apple/TableProTests/Views/TableListing/ObjectListingTableViewTests.swift new file mode 100644 index 0000000000..ebe6c5e7b8 --- /dev/null +++ b/apple/TableProTests/Views/TableListing/ObjectListingTableViewTests.swift @@ -0,0 +1,146 @@ +// +// ObjectListingTableViewTests.swift +// TableProTests +// + +import AppKit +import Combine +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ObjectListingTableViewTests { + private let defaults: EphemeralDefaults + + init() throws { + defaults = try EphemeralDefaults() + } + + private func makeModel() -> TableListingViewModel { + TableListingViewModel( + tabId: UUID(), + scope: DatabaseScope(connectionId: UUID(), database: "shop", schema: nil), + loader: TableListingLoader(databaseType: .mysql, slot: .database), + refreshRequests: Empty().eraseToAnyPublisher(), + columnVisibility: ObjectListingColumnVisibilityStore(defaults: defaults.defaults) + ) + } + + private func listing(_ names: [String], sizes: [String]) -> TableListing { + let rows = zip(names, sizes).map { name, size -> [PluginCellValue] in + [.text("shop"), .text(name), .text("BASE TABLE"), .text(size), .text("InnoDB")] + } + let tableRows = TableRows.from( + queryRows: rows, + columns: ["Schema", "Name", "Type", "Data Length", "Engine"], + columnTypes: Array(repeating: .text(rawType: nil), count: 5) + ) + var items: [RowID: ObjectListingItem] = [:] + for (index, name) in names.enumerated() { + items[.existing(index)] = .relation(name: name, schema: nil, type: .table) + } + return TableListing( + rows: tableRows, isIncomplete: false, statusMessage: nil, items: items, + columnKeys: ["schema", "name", "kind", "data_size", "engine"] + ) + } + + private func mount(_ model: TableListingViewModel) throws -> (ObjectListingTableCoordinator, NSTableView) { + let coordinator = ObjectListingTableCoordinator(list: model.list, model: model) + let scrollView = coordinator.makeScrollView() + let table = try #require(scrollView.documentView as? NSTableView) + return (coordinator, table) + } + + private func key(_ name: String) -> ObjectListingItem.Key { + ObjectListingItem.relation(name: name, schema: nil, type: .table).key + } + + @Test("The table lists every column in the list's order and hides the ones that start hidden") + func columnsFollowTheList() throws { + let model = makeModel() + model.list.show(listing(["orders"], sizes: ["16384"]), filterText: "") + + let (_, table) = try mount(model) + + #expect(table.tableColumns.map { $0.identifier.rawValue } == ["name", "data_size", "engine", "schema", "kind"]) + #expect(table.tableColumns.filter { !$0.isHidden }.map { $0.identifier.rawValue } == ["name", "data_size", "engine"]) + #expect(table.headerView is ThemeTableHeaderView) + #expect(table.tableColumns.allSatisfy { $0.headerCell is ThemeTableHeaderCell }) + #expect(table.numberOfRows == 1) + } + + @Test("A Name cell shows the sidebar's glyph and the system font; a size cell lines up on the right") + func cellsReadLikeAList() throws { + let model = makeModel() + model.list.show(listing(["orders"], sizes: ["163840"]), filterText: "") + let (coordinator, table) = try mount(model) + let name = try #require(table.tableColumn(withIdentifier: NSUserInterfaceItemIdentifier("name"))) + let size = try #require(table.tableColumn(withIdentifier: NSUserInterfaceItemIdentifier("data_size"))) + + let nameCell = try #require(coordinator.tableView(table, viewFor: name, row: 0) as? NSTableCellView) + let sizeCell = try #require(coordinator.tableView(table, viewFor: size, row: 0) as? NSTableCellView) + + #expect(nameCell.textField?.stringValue == "orders") + #expect(nameCell.imageView?.image != nil) + #expect(nameCell.textField?.font?.isFixedPitch == false) + #expect(sizeCell.imageView == nil) + #expect(sizeCell.textField?.alignment == .right) + #expect(sizeCell.textField?.stringValue != "163840") + } + + @Test("A header click sorts by that one column, and the arrow follows the list's sort") + func headerSortsByOneColumn() throws { + let model = makeModel() + model.list.show(listing(["small", "large", "medium"], sizes: ["1", "300", "20"]), filterText: "") + // The table holds its data source weakly, as it does the representable's coordinator. + let (coordinator, table) = try mount(model) + defer { withExtendedLifetime(coordinator) {} } + + table.sortDescriptors = [ + NSSortDescriptor(key: "data_size", ascending: false), + NSSortDescriptor(key: "name", ascending: true), + ] + + #expect(model.list.sort == ObjectListingSort(columnID: "data_size", ascending: false)) + #expect(model.list.rows.map { $0.item.name } == ["large", "medium", "small"]) + #expect(table.sortDescriptors.map { $0.key } == ["data_size"]) + } + + @Test("Selecting rows selects their objects, and a new listing keeps the selection on them") + func selectionFollowsObjects() throws { + let model = makeModel() + model.list.show(listing(["customers", "orders"], sizes: ["1", "2"]), filterText: "") + let (coordinator, table) = try mount(model) + + table.selectRowIndexes(IndexSet(integer: 1), byExtendingSelection: false) + #expect(model.list.selection == [key("orders")]) + + model.list.show(listing(["accounts", "customers", "orders"], sizes: ["1", "1", "2"]), filterText: "") + coordinator.sync() + + #expect(table.selectedRowIndexes == IndexSet(integer: 2)) + #expect(model.list.selection == [key("orders")]) + } + + @Test("The header's menu lists every column but Name, and hiding one hides it in every tab of the kind") + func headerMenuHidesColumns() throws { + let model = makeModel() + model.list.show(listing(["orders"], sizes: ["1"]), filterText: "") + let (coordinator, table) = try mount(model) + let menu = coordinator.columnMenu() + let engine = try #require(menu.items.first { ($0.representedObject as? String) == "engine" }) + + #expect(!menu.items.contains { ($0.representedObject as? String) == "name" }) + #expect(engine.state == .on) + + let action = try #require(engine.action) + _ = (engine.target as? NSObject)?.perform(action, with: engine) + + #expect(table.tableColumn(withIdentifier: NSUserInterfaceItemIdentifier("engine"))?.isHidden == true) + #expect(ObjectListingColumnVisibilityStore(defaults: defaults.defaults).choices(for: .table) == ["engine": false]) + } +} From a56f61aa830b8e80dcf69784737ddad2ed4f2ccf Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:58:31 +0700 Subject: [PATCH 076/123] feat(objects): title the Objects tab "Objects" The tab's own kind picker names the kind, so its title in the tab strip and the window no longer changes with it: "Objects", qualified by schema where objects are listed per schema. A listing restored from an older session is retitled on restore, since background tabs draw their title before they ever activate. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Services/Infrastructure/EditorTabOpener.swift | 2 +- .../Infrastructure/WindowTitleResolver.swift | 2 +- apple/TablePro/Models/Query/QueryTab.swift | 5 ++++- apple/TablePro/Models/Query/QueryTabManager.swift | 10 ++++++---- .../MainContentCoordinator+ObjectListing.swift | 11 ++--------- .../Core/Services/PersistedTabRoundTripTests.swift | 12 +++++++++++- .../Query/QueryTabManagerTableListingTests.swift | 9 +++++---- .../Services/WindowTitleResolverTests.swift | 4 ++-- .../Views/Main/CoordinatorTableListingTests.swift | 14 +++++++------- 9 files changed, 39 insertions(+), 30 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabOpener.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabOpener.swift index fc2d84e0af..cd83186bc2 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabOpener.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabOpener.swift @@ -100,7 +100,7 @@ internal enum EditorTabOpener { tabManager.addVersionHistoryTab(subject: subject, title: payload.tabTitle ?? QueryTabManager.versionHistoryFallbackTitle) case .tableListing: tabManager.addTableListingTab( - title: payload.tabTitle ?? String(localized: "Tables"), + title: QueryTabManager.tableListingTitle(schemaName: payload.schemaName), databaseName: payload.databaseName ?? openingDatabaseName, schemaName: payload.schemaName ) diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowTitleResolver.swift b/apple/TablePro/Core/Services/Infrastructure/WindowTitleResolver.swift index 26df4f0481..5c157e0817 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowTitleResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowTitleResolver.swift @@ -178,7 +178,7 @@ enum WindowTitleResolver { if let explicitTitle, !explicitTitle.isBlank { return explicitTitle } - return String(localized: "Tables") + return QueryTabManager.tableListingTitle(schemaName: nil) case .routineDebug: if let explicitTitle, !explicitTitle.isBlank { return explicitTitle diff --git a/apple/TablePro/Models/Query/QueryTab.swift b/apple/TablePro/Models/Query/QueryTab.swift index e94be37182..baad537800 100644 --- a/apple/TablePro/Models/Query/QueryTab.swift +++ b/apple/TablePro/Models/Query/QueryTab.swift @@ -166,7 +166,10 @@ struct QueryTab: Identifiable, Equatable { init(from persisted: PersistedTab, defaultPageSize: Int) { self.id = persisted.id - self.title = persisted.title + // A listing saved by an older build is titled after its kind ("Tables: sales"); every listing now reads Objects. + self.title = persisted.tabType == .tableListing + ? QueryTabManager.tableListingTitle(schemaName: persisted.schemaName) + : persisted.title self.tabType = persisted.tabType self.isPreview = false self.isPinned = persisted.isPinned diff --git a/apple/TablePro/Models/Query/QueryTabManager.swift b/apple/TablePro/Models/Query/QueryTabManager.swift index 5acfd0763a..3421c3d98d 100644 --- a/apple/TablePro/Models/Query/QueryTabManager.swift +++ b/apple/TablePro/Models/Query/QueryTabManager.swift @@ -670,10 +670,12 @@ final class QueryTabManager: ObservableObject { return newTab.id } - // Qualified by schema where tables are listed per schema, or two listings in one database would share a label. - static func tableListingTitle(kindTitle: String, schemaName: String?) -> String { - guard let schemaName, !schemaName.isEmpty else { return kindTitle } - return String(format: String(localized: "%@: %@"), kindTitle, schemaName) + // The kind picker inside the tab names the kind, so the title stays put when the kind changes. It is + // qualified by schema where objects are listed per schema, or two listings in one database would share a label. + nonisolated static func tableListingTitle(schemaName: String?) -> String { + let title = String(localized: "Objects") + guard let schemaName, !schemaName.isEmpty else { return title } + return String(format: String(localized: "%@: %@"), title, schemaName) } static var versionHistoryFallbackTitle: String { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift index b0a0fd3ee6..4d7ed8b77e 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ObjectListing.swift @@ -24,7 +24,7 @@ extension MainContentCoordinator { releasePreviewForReplacement(closing) } let tabId = tabManager.addTableListingTab( - title: listingTitle(kind: target.kind, schemaName: schemaName), + title: QueryTabManager.tableListingTitle(schemaName: schemaName), databaseName: target.database, schemaName: schemaName, kind: target.kind, @@ -165,18 +165,11 @@ extension MainContentCoordinator { guard let tab = tabManager.tabs.first(where: { $0.id == tabId && $0.tabType == .tableListing }) else { return } tabManager.setTableListingKind( kind, - title: listingTitle(kind: kind, schemaName: tab.tableContext.schemaName), + title: QueryTabManager.tableListingTitle(schemaName: tab.tableContext.schemaName), tabId: tabId ) } - private func listingTitle(kind: SidebarObjectKind, schemaName: String?) -> String { - QueryTabManager.tableListingTitle( - kindTitle: kind.title(tableEntityName: PluginManager.shared.tableEntityName(for: connection.type)), - schemaName: schemaName - ) - } - /// Kept, pinned and busy tabs are never taken over: the rule a table preview follows. private var replaceablePreview: QueryTab? { guard let tab = tabManager.selectedTab, tab.isPreview, isActiveTabReusable else { return nil } diff --git a/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift b/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift index 75f081b25b..3d2fd701fc 100644 --- a/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift +++ b/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift @@ -575,12 +575,22 @@ struct PersistedTabRoundTripTests { #expect(persisted.query.isEmpty) #expect(restored.tabType == .tableListing) - #expect(restored.title == "Tables: sales") + #expect(restored.title == QueryTabManager.tableListingTitle(schemaName: "sales")) #expect(restored.tableContext.databaseName == "shop") #expect(restored.tableContext.schemaName == "sales") #expect(restored.tableContext.isEditable == false) } + /// Titles are drawn for background tabs that never activate, so a listing an older build titled + /// after its kind reads Objects from the moment it is restored. + @Test("A listing saved under its kind's title restores titled Objects") + func olderListingTitleRestoresAsObjects() throws { + let json = #"{"id":"\#(UUID().uuidString)","title":"Views: sales","query":"","tabType":{"tableListing":{}},"schemaName":"sales"}"# + let decoded = try JSONDecoder().decode(PersistedTab.self, from: Data(json.utf8)) + + #expect(QueryTab(from: decoded, defaultPageSize: 1_000).title == QueryTabManager.tableListingTitle(schemaName: "sales")) + } + @Test("A tab written before history tabs existed decodes with no subject") func olderTabHasNoHistorySubject() throws { let json = #"{"id":"\#(UUID().uuidString)","title":"Query 1","query":"SELECT 1","tabType":{"query":{}}}"# diff --git a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift index 6424ad3190..902f6eb931 100644 --- a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift +++ b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift @@ -53,11 +53,12 @@ struct QueryTabManagerTableListingTests { #expect(manager.tabs.first { $0.id == unscoped }?.tableContext.schemaName == nil) } - @Test("The title names the schema only where tables are listed per schema") + @Test("The title reads Objects, naming the schema only where objects are listed per schema") func titleNamesTheSchema() { - #expect(QueryTabManager.tableListingTitle(kindTitle: "Tables", schemaName: "public") == "Tables: public") - #expect(QueryTabManager.tableListingTitle(kindTitle: "Collections", schemaName: nil) == "Collections") - #expect(QueryTabManager.tableListingTitle(kindTitle: "Tables", schemaName: "") == "Tables") + let objects = String(localized: "Objects") + #expect(QueryTabManager.tableListingTitle(schemaName: "public") == String(format: String(localized: "%@: %@"), objects, "public")) + #expect(QueryTabManager.tableListingTitle(schemaName: nil) == objects) + #expect(QueryTabManager.tableListingTitle(schemaName: "") == objects) } @Test("A new kind retargets the container's tab and relabels it, never opening another") diff --git a/apple/TableProTests/Services/WindowTitleResolverTests.swift b/apple/TableProTests/Services/WindowTitleResolverTests.swift index aea16a7f40..130b3846f5 100644 --- a/apple/TableProTests/Services/WindowTitleResolverTests.swift +++ b/apple/TableProTests/Services/WindowTitleResolverTests.swift @@ -37,7 +37,7 @@ struct WindowTitleResolverPayloadTitleTests { #expect(title == String(localized: "Create Table")) } - @Test("A listing payload takes its tab title, and a blank one falls back to Tables") + @Test("A listing payload takes its tab title, and a blank one falls back to Objects") func tableListingLabel() { let named = EditorTabPayload(connectionId: UUID(), tabType: .tableListing, tabTitle: "Tables: sales") let blank = EditorTabPayload(connectionId: UUID(), tabType: .tableListing, tabTitle: " ") @@ -46,7 +46,7 @@ struct WindowTitleResolverPayloadTitleTests { ) == "Tables: sales") #expect(WindowTitleResolver.resolveTitle( payload: blank, databaseType: .postgresql, queryLanguageName: "PostgreSQL" - ) == String(localized: "Tables")) + ) == String(localized: "Objects")) } @Test("A history payload takes its tab title, and a blank one falls back to History") diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index b10eb2375b..0ac0307d27 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -64,7 +64,7 @@ struct CoordinatorTableListingTests { let tab = try #require(tabManager.selectedTab) #expect(tab.tabType == .tableListing) - #expect(tab.title == "Tables") + #expect(tab.title == String(localized: "Objects")) #expect(tab.tableContext.databaseName == coordinator.browseDatabaseName) #expect(tab.tableContext.isEditable == false) #expect(tab.content.query.isEmpty) @@ -120,7 +120,7 @@ struct CoordinatorTableListingTests { #expect(tab.tabType == .tableListing) #expect(tab.tableContext.databaseName == "archive") #expect(tab.display.listingKind == .view) - #expect(tab.title == "Views") + #expect(tab.title == String(localized: "Objects")) #expect(!tab.isPreview) } @@ -198,7 +198,7 @@ struct CoordinatorTableListingTests { #expect(preview.isPreview) #expect(preview.display.listingKind == .view) #expect(keptTab.display.listingKind == nil) - #expect(keptTab.title == "Tables") + #expect(keptTab.title == String(localized: "Objects")) #expect(!keptTab.isPreview) } @@ -296,7 +296,7 @@ struct CoordinatorTableListingTests { ]) } - @Test("Picking a kind retargets the tab, relabels it and keeps the preview") + @Test("Picking a kind retargets the tab, keeps its Objects title and keeps the preview") func pickingAKindKeepsThePreview() throws { let (coordinator, tabManager, _) = makeCoordinator() defer { coordinator.teardown() } @@ -308,11 +308,11 @@ struct CoordinatorTableListingTests { let tab = try #require(tabManager.selectedTab) #expect(tab.id == id) #expect(tab.display.listingKind == .view) - #expect(tab.title == "Views") + #expect(tab.title == String(localized: "Objects")) #expect(!tab.isPreview) } - @Test("Falling back to Tables relabels the tab and leaves a preview a preview") + @Test("Falling back to Tables keeps the Objects title and leaves a preview a preview") func fallbackKeepsThePreview() throws { let (coordinator, tabManager, _) = makeCoordinator() defer { coordinator.teardown() } @@ -323,7 +323,7 @@ struct CoordinatorTableListingTests { let tab = try #require(tabManager.selectedTab) #expect(tab.display.listingKind == nil) - #expect(tab.title == "Tables") + #expect(tab.title == String(localized: "Objects")) #expect(tab.isPreview) } From 906c1561536da76e3275fa07833950f3da4fcbdb Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:52:23 +0700 Subject: [PATCH 077/123] feat(settings): add a setting that lists saved connections in the tree Off by default. Navigator Layout turns it on and turns the separate connections column off, since the tree then lists the connections itself. Standard Layout puts both back to their defaults. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Core/Storage/AppSettingsManager.swift | 4 +- .../Models/Settings/GeneralSettings.swift | 5 +++ .../Settings/NavigatorLayoutPreset.swift | 9 +++- .../Views/Settings/GeneralSettingsView.swift | 12 ++++-- .../ConnectionsInTreeSettingTests.swift | 43 +++++++++++++++++++ .../Models/NavigatorLayoutPresetTests.swift | 26 +++++++++-- 6 files changed, 89 insertions(+), 10 deletions(-) create mode 100644 apple/TableProTests/Models/ConnectionsInTreeSettingTests.swift diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index c23efc4e52..42b5795d14 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -12,8 +12,10 @@ final class AppSettingsManager: ObservableObject { didSet { general.language.apply() storage.saveGeneral(general) + // The strip stands aside for a tree that lists the connections itself, so that setting moves it too. if oldValue.showWorkspaceRail != general.showWorkspaceRail - || oldValue.showsConnectionNavigator != general.showsConnectionNavigator { + || oldValue.showsConnectionNavigator != general.showsConnectionNavigator + || oldValue.showsConnectionsInTree != general.showsConnectionsInTree { appEvents.workspaceRailVisibilityChanged.send(()) } if oldValue.connectionHealthCheck != general.connectionHealthCheck { diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index bfcb515239..f9bb295454 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -74,6 +74,7 @@ struct GeneralSettings: Codable, Equatable { var showWorkspaceRail: Bool var sidebarRowSize: SidebarRowSizePreference var showsConnectionNavigator: Bool + var showsConnectionsInTree: Bool var connectionHealthCheck: ConnectionHealthCheck static let `default` = GeneralSettings( @@ -94,6 +95,7 @@ struct GeneralSettings: Codable, Equatable { showWorkspaceRail: true, sidebarRowSize: .matchSystem, showsConnectionNavigator: false, + showsConnectionsInTree: false, connectionHealthCheck: .every30Seconds ) @@ -115,6 +117,7 @@ struct GeneralSettings: Codable, Equatable { showWorkspaceRail: Bool = true, sidebarRowSize: SidebarRowSizePreference = .matchSystem, showsConnectionNavigator: Bool = false, + showsConnectionsInTree: Bool = false, connectionHealthCheck: ConnectionHealthCheck = .every30Seconds ) { self.startupBehavior = startupBehavior @@ -134,6 +137,7 @@ struct GeneralSettings: Codable, Equatable { self.showWorkspaceRail = showWorkspaceRail self.sidebarRowSize = sidebarRowSize self.showsConnectionNavigator = showsConnectionNavigator + self.showsConnectionsInTree = showsConnectionsInTree self.connectionHealthCheck = connectionHealthCheck } @@ -162,6 +166,7 @@ struct GeneralSettings: Codable, Equatable { .showsConnectionNavigator, default: fallback.showsConnectionNavigator ) + showsConnectionsInTree = container.decodeSetting(.showsConnectionsInTree, default: fallback.showsConnectionsInTree) connectionHealthCheck = container.decodeSetting(.connectionHealthCheck, default: fallback.connectionHealthCheck) } } diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index cf4139590a..9debf0dc8e 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -7,7 +7,10 @@ import Foundation /// The Layout buttons in Settings > General: table details, favorite tables at the top of the tree, /// the Objects tab on selection, the Objects toolbar buttons, labels under the toolbar's icons, the -/// connections list and Tree as the default sidebar layout, on or off in one step. +/// saved connections in the tree and Tree as the default sidebar layout, on or off in one step. +/// +/// The tree lists the saved connections itself, so the layout keeps the separate connections column +/// off: the sidebar is one tree, with the connection on screen opened in it. /// /// It edits the same values the separate controls edit and leaves the write to the caller. Settings /// passes its General settings binding, so the change lands on `AppSettingsManager.general` in one @@ -19,7 +22,8 @@ internal enum NavigatorLayoutPreset { settings.showsObjectsOnSelection = true settings.showsObjectToolbar = true settings.showsToolbarLabels = true - settings.showsConnectionNavigator = true + settings.showsConnectionsInTree = true + settings.showsConnectionNavigator = false defaultLayout = .tree } @@ -30,6 +34,7 @@ internal enum NavigatorLayoutPreset { settings.showsObjectsOnSelection = standard.showsObjectsOnSelection settings.showsObjectToolbar = standard.showsObjectToolbar settings.showsToolbarLabels = standard.showsToolbarLabels + settings.showsConnectionsInTree = standard.showsConnectionsInTree settings.showsConnectionNavigator = standard.showsConnectionNavigator defaultLayout = .flat } diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index e53300e8ba..c6b819c4ae 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -74,9 +74,9 @@ struct GeneralSettingsView: View { } footer: { Text(String(localized: """ Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects \ - tab on selection, the Objects toolbar buttons, toolbar labels and the connections list, and makes \ - Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch \ - layout too. + tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the \ + tree, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open \ + connections switch layout too. """)) } @@ -87,6 +87,12 @@ struct GeneralSettingsView: View { Toggle("List every saved connection beside the database tree", isOn: $settings.showsConnectionNavigator) .help("Turns the connections column into a list of every saved connection, in its groups. Double-click one to open it.") + Toggle("Show saved connections in the database tree", isOn: $settings.showsConnectionsInTree) + .help(String(localized: """ + In the Tree layout, lists every saved connection in its groups at the top of the sidebar, \ + with the connection on screen opened to its databases. Double-click another one to open 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.") diff --git a/apple/TableProTests/Models/ConnectionsInTreeSettingTests.swift b/apple/TableProTests/Models/ConnectionsInTreeSettingTests.swift new file mode 100644 index 0000000000..1baa4e5fa2 --- /dev/null +++ b/apple/TableProTests/Models/ConnectionsInTreeSettingTests.swift @@ -0,0 +1,43 @@ +// +// ConnectionsInTreeSettingTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct ConnectionsInTreeSettingTests { + private static func encoded(_ settings: GeneralSettings) throws -> [String: Any] { + let data = try JSONEncoder().encode(settings) + return try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private static func decoded(_ object: [String: Any]) throws -> GeneralSettings { + try JSONDecoder().decode(GeneralSettings.self, from: JSONSerialization.data(withJSONObject: object)) + } + + @Test("Saved connections stay out of the tree by default") + func startsOff() { + #expect(GeneralSettings.default.showsConnectionsInTree == false) + #expect(GeneralSettings().showsConnectionsInTree == false) + } + + @Test("Settings saved before the setting existed decode with it off") + func missingKeyDecodesOff() throws { + let decoded = try Self.decoded(["startupBehavior": "showWelcome"]) + #expect(decoded.showsConnectionsInTree == false) + } + + @Test("Turning it on survives a round trip and leaves the connections column alone") + func roundTripsOn() throws { + var object = try Self.encoded(.default) + object["showsConnectionsInTree"] = true + + let decoded = try Self.decoded(object) + + #expect(decoded.showsConnectionsInTree) + #expect(!decoded.showsConnectionNavigator) + #expect(decoded.showWorkspaceRail) + } +} diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index 755a4a8132..c19450b044 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -18,7 +18,8 @@ struct NavigatorLayoutPresetTests { expected.showsObjectsOnSelection = true expected.showsObjectToolbar = true expected.showsToolbarLabels = true - expected.showsConnectionNavigator = true + expected.showsConnectionsInTree = true + expected.showsConnectionNavigator = false return expected } @@ -34,13 +35,28 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsObjectsOnSelection) #expect(settings.showsObjectToolbar) #expect(settings.showsToolbarLabels) - #expect(settings.showsConnectionNavigator) + #expect(settings.showsConnectionsInTree) #expect(layout == .tree) } + /// The tree lists the saved connections itself, so a second list of them in its own column + /// would put the window back at two columns. + @Test("Use Navigator Layout turns the separate connections column off") + func applyTurnsTheConnectionsColumnOff() { + var settings = GeneralSettings.default + settings.showsConnectionNavigator = true + var layout = SidebarLayout.flat + + NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &layout) + + #expect(settings.showsConnectionsInTree) + #expect(!settings.showsConnectionNavigator) + } + @Test("Use Standard Layout puts all seven back to their defaults") func restorePutsTheDefaultsBack() { var settings = Self.navigatorLayout(from: .default) + settings.showsConnectionNavigator = true var layout = SidebarLayout.tree NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &layout) @@ -50,6 +66,7 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsObjectsOnSelection == GeneralSettings.default.showsObjectsOnSelection) #expect(settings.showsObjectToolbar == GeneralSettings.default.showsObjectToolbar) #expect(!settings.showsToolbarLabels, "Standard Layout is icons only") + #expect(settings.showsConnectionsInTree == GeneralSettings.default.showsConnectionsInTree) #expect(settings.showsConnectionNavigator == GeneralSettings.default.showsConnectionNavigator) #expect(settings == GeneralSettings.default) #expect(layout == .flat) @@ -129,6 +146,7 @@ extension GlobalStateSuites { $0.general.showsObjectToolbar = false $0.general.showsToolbarLabels = false $0.general.showsConnectionNavigator = false + $0.general.showsConnectionsInTree = false } ) func presetReachesAnOpenWindow() throws { @@ -150,13 +168,13 @@ extension GlobalStateSuites { #expect(hasButtons(), "The Objects buttons reach the open window") #expect(toolbar.displayMode == .iconAndLabel, "Labels go under the toolbar's icons") - #expect(railChanges == 1, "The connections column is told to swap in the navigator") + #expect(railChanges == 1, "The connections column is told the tree now lists the connections") NavigatorLayoutPreset.restore(to: &AppSettingsManager.shared.general, defaultLayout: &layout) #expect(!hasButtons(), "The Objects buttons leave the open window") #expect(toolbar.displayMode == .iconOnly, "Standard Layout puts the icons back alone") - #expect(railChanges == 2, "The connections column is told to swap the navigator out") + #expect(railChanges == 2, "The connections column is told the tree stops listing them") } } } From a4e917bbe3a7209daa7890513bbe05177e301c33 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:52:31 +0700 Subject: [PATCH 078/123] feat(sidebar): list saved connections at the top of the database tree With the setting on and the Tree layout, the tree reads as one: group, saved connection, database, objects. The workspace's own connection is opened to its databases; every other connection is a row with its status. A click on one this window hosts switches to it, and a double click or Return opens one nobody hosts through the router, as the connections column does. Connection rows take that column's context menu, and the filter keeps the own connection and the connections whose names match. Under a connection no section is a source list group row, so Favorites, Recent and Temporary draw as ordinary rows with an icon. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ViewModels/SidebarViewModel.swift | 13 + .../ConnectionNavigatorRowView.swift | 5 +- .../Views/Sidebar/DatabaseTreeCellView.swift | 4 +- .../Sidebar/DatabaseTreeConnectionRows.swift | 153 +++++++++ .../DatabaseTreeDoubleClickIntent.swift | 4 + .../Views/Sidebar/DatabaseTreeNode.swift | 28 +- ...seTreeOutlineCoordinator+Connections.swift | 275 +++++++++++++++ ...baseTreeOutlineCoordinator+Expansion.swift | 44 ++- .../DatabaseTreeOutlineCoordinator+Menu.swift | 1 + ...DatabaseTreeOutlineCoordinator+Nodes.swift | 28 ++ .../DatabaseTreeOutlineCoordinator.swift | 38 +- .../Sidebar/DatabaseTreeOutlineView.swift | 3 +- .../Views/Sidebar/DatabaseTreeRowView.swift | 39 ++- .../Views/Sidebar/DatabaseTreeSelection.swift | 6 +- .../Sidebar/DatabaseTreeTypeSelect.swift | 4 + .../Views/Sidebar/DatabaseTreeView.swift | 32 +- .../Sidebar/Menu/DatabaseTreeMenuSpec.swift | 4 + .../Views/Sidebar/SidebarPersistenceKey.swift | 7 + .../DatabaseTreeConnectionRowsTests.swift | 214 ++++++++++++ .../DatabaseTreeConnectionsInTreeTests.swift | 324 ++++++++++++++++++ .../Sidebar/DatabaseTreeMenuSpecTests.swift | 25 +- 21 files changed, 1200 insertions(+), 51 deletions(-) create mode 100644 apple/TablePro/Views/Sidebar/DatabaseTreeConnectionRows.swift create mode 100644 apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Connections.swift create mode 100644 apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionRowsTests.swift create mode 100644 apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionsInTreeTests.swift diff --git a/apple/TablePro/ViewModels/SidebarViewModel.swift b/apple/TablePro/ViewModels/SidebarViewModel.swift index 67e1dbbdd7..5134583dbe 100644 --- a/apple/TablePro/ViewModels/SidebarViewModel.swift +++ b/apple/TablePro/ViewModels/SidebarViewModel.swift @@ -173,6 +173,14 @@ final class SidebarViewModel: ObservableObject { ) } } + @Published var isOwnConnectionExpanded: Bool { + didSet { + defaults.set( + isOwnConnectionExpanded, + forKey: SidebarPersistenceKey.ownConnectionExpanded(connectionId: connectionId) + ) + } + } @Published var isFoldersExpanded: Bool { didSet { defaults.set( @@ -276,6 +284,11 @@ final class SidebarViewModel: ObservableObject { defaultValue: true, defaults: defaults ) + self.isOwnConnectionExpanded = Self.loadExpansion( + perConnectionKey: SidebarPersistenceKey.ownConnectionExpanded(connectionId: connectionId), + defaultValue: true, + defaults: defaults + ) self.isFoldersExpanded = Self.loadExpansion( perConnectionKey: SidebarPersistenceKey.foldersExpanded(connectionId: connectionId), defaultValue: true, diff --git a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift index b40393fa65..589493859d 100644 --- a/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift +++ b/apple/TablePro/Views/ConnectionNavigator/ConnectionNavigatorRowView.swift @@ -41,7 +41,8 @@ internal struct ConnectionNavigatorRowView: View { } } -private struct ConnectionNavigatorGroupLabel: View { +/// Shared with the database tree, which lists the same rows above its own connection's databases. +internal struct ConnectionNavigatorGroupLabel: View { let group: ConnectionNavigatorGroupRow var body: some View { @@ -61,7 +62,7 @@ private struct ConnectionNavigatorGroupLabel: View { } } -private struct ConnectionNavigatorConnectionLabel: View { +internal struct ConnectionNavigatorConnectionLabel: View { let row: ConnectionNavigatorConnectionRow let glyphSide: CGFloat diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift index 9387d48087..315ff71ee4 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift @@ -38,8 +38,10 @@ final class DatabaseTreeCellView: RenamableSidebarCellView return SidebarPartitionRow.iconName case .database(let metadata): return metadata.isSystemDatabase ? "gearshape" : "cylinder" - case .schema, .tableFolder: + case .schema, .tableFolder, .connectionGroup: return "folder" + case .savedConnection: + return "server.rack" case .routine, .trigger, .userType, .status, .recentSection, .favoritesSection, .temporarySection, .foldersSection, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeConnectionRows.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeConnectionRows.swift new file mode 100644 index 0000000000..01305c392d --- /dev/null +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeConnectionRows.swift @@ -0,0 +1,153 @@ +// +// DatabaseTreeConnectionRows.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit + +/// A saved connection's row in the database tree. The tree's own connection holds everything the +/// tree lists without connections; every other one is a row to switch to or open. +internal struct DatabaseTreeSavedConnectionRef: Equatable { + internal let row: ConnectionNavigatorConnectionRow + internal let ownsTree: Bool + + internal var id: UUID { row.id } +} + +/// What a double click or Return on a saved connection's row does. +internal enum DatabaseTreeConnectionActivation: Equatable { + case toggleDisclosure + case switchTo(UUID) + case open(UUID) +} + +/// The saved connections the database tree lists above its own connection's databases, so the +/// sidebar reads as one tree: group, connection, database, objects. +/// +/// Each workspace owns its sidebar, so each tree lists the same connections and opens only its own. +/// The rows come from the navigator's builder, so the tree and the connections column agree on +/// grouping and order. +internal enum DatabaseTreeConnectionRows { + /// Only the database tree has a level above its containers for a connection to sit at. The flat + /// list and the schema list are one container's objects. + internal static func applies(settingEnabled: Bool, rootShape: SidebarRootShape) -> Bool { + settingEnabled && rootShape == .databaseTree + } + + @MainActor + internal static func applies(settingEnabled: Bool, databaseType: DatabaseType, layout: SidebarLayout) -> Bool { + guard settingEnabled else { return false } + let plugins = PluginManager.shared + return applies( + settingEnabled: settingEnabled, + rootShape: SidebarRootShapeResolver.resolve( + groupingStrategy: plugins.databaseGroupingStrategy(for: databaseType), + sidebarLayout: layout, + supportsDatabaseTree: plugins.supportsDatabaseTree(for: databaseType) + ) + ) + } + + /// The rows the tree lists at its top. + /// + /// The sidebar filter searches the tree's objects, so the tree's own connection always stays, with + /// the groups above it: hiding it would hide every object the filter found. Any other connection + /// stays while its name matches. A connection the library does not hold, one opened from a file + /// or a link, is listed first, so its databases still have a row to hang from. + nonisolated internal static func rows( + from library: [ConnectionNavigatorRow], + ownId: UUID, + unsavedOwnRow: ConnectionNavigatorConnectionRow? = nil, + filterText: String + ) -> [ConnectionNavigatorRow] { + let term = filterText.trimmingCharacters(in: .whitespacesAndNewlines) + var rows = term.isEmpty ? library : filtered(library, term: term, keeping: ownId) + if let unsavedOwnRow, unsavedOwnRow.id == ownId, !contains(ownId, in: library) { + rows.insert(.connection(unsavedOwnRow), at: 0) + } + return rows + } + + /// While the filter runs every group it leaves is open, since each one holds a match or the + /// tree's own connection. The user's own choice comes back with the filter cleared. + nonisolated private static func filtered( + _ rows: [ConnectionNavigatorRow], + term: String, + keeping ownId: UUID? + ) -> [ConnectionNavigatorRow] { + rows.compactMap { row -> ConnectionNavigatorRow? in + switch row { + case .connection(let connection): + let keeps = connection.id == ownId || connection.connection.name.localizedCaseInsensitiveContains(term) + return keeps ? row : nil + case .group(let group): + let children = filtered(group.children, term: term, keeping: ownId) + guard !children.isEmpty else { return nil } + return .group(ConnectionNavigatorGroupRow( + id: group.id, + name: group.name, + color: group.color, + iconName: group.iconName, + connectionCount: connectionCount(in: children), + isExpanded: true, + children: children + )) + } + } + } + + nonisolated private static func connectionCount(in rows: [ConnectionNavigatorRow]) -> Int { + rows.reduce(0) { count, row in + switch row { + case .connection: return count + 1 + case .group(let group): return count + connectionCount(in: group.children) + } + } + } + + nonisolated internal static func contains(_ connectionId: UUID, in rows: [ConnectionNavigatorRow]) -> Bool { + groupIds(above: connectionId, in: rows) != nil + } + + /// The groups holding a connection, outermost first, or nil when the rows do not hold it. + nonisolated internal static func groupIds(above connectionId: UUID, in rows: [ConnectionNavigatorRow]) -> [UUID]? { + for row in rows { + switch row { + case .connection(let connection): + if connection.id == connectionId { return [] } + case .group(let group): + if let inner = groupIds(above: connectionId, in: group.children) { + return [group.id] + inner + } + } + } + return nil + } + + /// The tree's own row discloses its databases. Another connection this window hosts is a + /// switch; one it does not host opens through the router, which raises a window already showing + /// it and otherwise opens it here. + nonisolated internal static func activation( + of ref: DatabaseTreeSavedConnectionRef, + hostedHere: Set + ) -> DatabaseTreeConnectionActivation { + if ref.ownsTree { return .toggleDisclosure } + return hostedHere.contains(ref.id) ? .switchTo(ref.id) : .open(ref.id) + } + + /// A click that lands on another connection this window hosts switches to it, as a click in the + /// connections column does. Only a click: arrowing down the tree must not hop between workspaces + /// row by row, and a click on a connection nobody hosts never dials one by accident. + nonisolated internal static func clickSwitchTarget( + selected kinds: [DatabaseTreeNode.Kind], + hostedHere: Set, + isPointerClick: Bool + ) -> UUID? { + guard isPointerClick, kinds.count == 1, case .savedConnection(let ref) = kinds[0], + !ref.ownsTree, hostedHere.contains(ref.id) + else { return nil } + return ref.id + } +} diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift index 85756ee4fa..6e4fdcced7 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeDoubleClickIntent.swift @@ -19,6 +19,8 @@ internal enum DatabaseTreeDoubleClickIntent: Equatable { case openObjectSource(DatabaseObjectRef) /// A column, index, foreign key or check is read in its table's Structure tab. case showStructure(DatabaseTreeTableRef) + /// Switch to or open a saved connection other than the tree's own. + case activateConnection(DatabaseTreeSavedConnectionRef) /// Expand or collapse a container row. case toggleDisclosure case ignore @@ -41,6 +43,8 @@ internal enum DatabaseTreeDoubleClickResolver { return .openObjectSource(ref.objectRef) case .tableDetail(let ref): return .showStructure(ref.table) + case .savedConnection(let ref) where !ref.ownsTree: + return .activateConnection(ref) default: return node.isExpandable ? .toggleDisclosure : .ignore } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift index 92afb7d37e..d43c3463ec 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeNode.swift @@ -76,6 +76,10 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { } enum Kind { + /// A group of saved connections, at the top of a tree that lists them. + case connectionGroup(ConnectionNavigatorGroupRow) + /// A saved connection. The tree's own one holds everything the tree lists without connections. + case savedConnection(DatabaseTreeSavedConnectionRef) case recentSection case recentTable(DatabaseTreeTableRef) /// The browsed database's favorite tables, above Recent. Each table also keeps its own row. @@ -137,6 +141,10 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { case .redisNode(let node): guard case .namespace = node else { return false } return true + case .connectionGroup(let group): + return !group.children.isEmpty + case .savedConnection(let ref): + return ref.ownsTree case .recentTable, .favoriteTable, .temporaryTable, .routine, .trigger, .userType, .status, .tableDetail: return false } @@ -167,7 +175,11 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return !showsTableDetails case .tableDetailGroup: return false - case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + // Opening a group with Option held must not open every database of the connection inside it, + // each of which reads its schemas as it opens. + case .savedConnection: + return false + case .connectionGroup, .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .database, .schema, .partition, .tableDetail, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: @@ -198,6 +210,11 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return nil } + var savedConnectionRef: DatabaseTreeSavedConnectionRef? { + if case .savedConnection(let ref) = kind { return ref } + return nil + } + var temporaryTableRef: DatabaseTreeTableRef? { if case .temporaryTable(let ref) = kind { return ref } return nil @@ -214,7 +231,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { case .recentSection, .favoritesSection, .temporarySection, .foldersSection, .objectKindSection, .redisKeysSection: return true - case .database, .schema, .containerObjectKindSection, .tableFolder, + case .connectionGroup, .savedConnection, .database, .schema, .containerObjectKindSection, .tableFolder, .hierarchicalSchemaSection, .recentTable, .favoriteTable, .temporaryTable, .table, .partition, .routine, .trigger, .userType, .status, .redisNode, .tableDetailGroup, .tableDetail: return false @@ -225,7 +242,8 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { switch kind { case .database, .schema: return true - case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .connectionGroup, .savedConnection, .recentSection, .recentTable, .favoritesSection, .favoriteTable, + .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: @@ -239,7 +257,7 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return .database(metadata.name, isSystem: metadata.isSystemDatabase) case .schema(let database, let schema): return .schema(database: database, schema: schema, isSystem: systemSchemas.contains(schema)) - case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .connectionGroup, .savedConnection, .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: @@ -252,6 +270,8 @@ final class DatabaseTreeNode: NSObject, SidebarOutlineNode { return nil } + static func connectionGroupId(_ groupId: UUID) -> String { "conngroup\u{1}\(groupId.uuidString)" } + static func savedConnectionId(_ connectionId: UUID) -> String { "savedconn\u{1}\(connectionId.uuidString)" } static let recentSectionId = "recent-section" static let favoritesSectionId = "favorites-section" /// The flat shape's root, which has no row of its own; its status row hangs off this id. diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Connections.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Connections.swift new file mode 100644 index 0000000000..5ff83af816 --- /dev/null +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Connections.swift @@ -0,0 +1,275 @@ +// +// DatabaseTreeOutlineCoordinator+Connections.swift +// TablePro +// + +import AppKit +import Combine +import SwiftUI +import TableProConnectionLibrary + +/// The saved connections the tree lists above its own connection's databases: their rows, which of +/// them are open, and what a click, Return or the menu does on one. +/// +/// The data, the commands and the menu are the connections column's own (`ConnectionNavigatorModel`, +/// `ConnectionNavigatorMenu`), so opening a connection from either list takes the same route and +/// never hosts a connection twice. +extension DatabaseTreeOutlineCoordinator { + // MARK: - Model + + /// Starts listening the first time the tree lists the connections and stops when it no longer + /// does, so a tree that never lists them reads no library and observes no event. + internal func syncConnectionsModel() { + guard listsConnections else { + guard !connectionsModelObservations.isEmpty else { return } + connectionsModelObservations.removeAll() + connectionsModel?.stop() + return + } + let model = connectionsModel ?? ConnectionNavigatorModel() + connectionsModel = model + // The window sets itself on the coordinator once it appears, which can be after the first reload. + if model.host == nil { + model.host = mainCoordinator?.splitViewController + } + guard connectionsModelObservations.isEmpty else { return } + model.onOpenFailure = { [weak self] error in + AlertHelper.showErrorSheet( + title: String(localized: "Connection Failed"), + message: error.localizedDescription, + window: self?.outlineView?.window + ) + } + model.start() + /// Subscribed after the first build, which this reload already draws. The model writes its + /// rows before it moves either revision, so a sink reads the new rows. + connectionsModelObservations = [ + model.$revision.dropFirst().sink { [weak self] _ in + self?.scheduleReconcile(forcing: true) + }, + model.$presentationRevision.dropFirst().sink { [weak self] _ in + self?.applyConnectionMarks() + }, + ] + } + + /// A status or a window moved, which changes how a row is marked and never which rows exist, so + /// the rows are reconfigured in place rather than reloaded. + private func applyConnectionMarks() { + guard listsConnections, let model = connectionsModel else { return } + func apply(_ rows: [ConnectionNavigatorRow]) { + for row in rows { + switch row { + case .group(let group): + apply(group.children) + case .connection(let connection): + guard let node = nodeCache[DatabaseTreeNode.savedConnectionId(connection.id)], + let ref = node.savedConnectionRef + else { continue } + node.kind = .savedConnection(DatabaseTreeSavedConnectionRef(row: connection, ownsTree: ref.ownsTree)) + } + } + } + apply(model.rows) + refreshVisibleRows() + } + + // MARK: - Rows + + internal func connectionTreeRows() -> [ConnectionNavigatorRow] { + let library = connectionsModel?.rows ?? [] + return DatabaseTreeConnectionRows.rows( + from: library, + ownId: connectionId, + unsavedOwnRow: DatabaseTreeConnectionRows.contains(connectionId, in: library) ? nil : unsavedOwnRow(), + filterText: searchText + ) + } + + /// A connection opened from a file or a link is in no group and in no saved list, yet its + /// databases still need the row they hang from. + private func unsavedOwnRow() -> ConnectionNavigatorConnectionRow? { + guard let connection = DatabaseManager.shared.session(for: connectionId)?.connection else { return nil } + return ConnectionNavigatorConnectionRow( + connection: connection, + groupPath: [], + isDriverRejected: false, + status: ConnectionStatusResolver.status(for: connectionId), + placement: .shownHere + ) + } + + internal func connectionLevelNodes(_ rows: [ConnectionNavigatorRow]) -> [DatabaseTreeNode] { + rows.map { row in + switch row { + case .group(let group): + return node(id: DatabaseTreeNode.connectionGroupId(group.id), kind: .connectionGroup(group)) + case .connection(let connection): + return node( + id: DatabaseTreeNode.savedConnectionId(connection.id), + kind: .savedConnection(DatabaseTreeSavedConnectionRef( + row: connection, + ownsTree: connection.id == connectionId + )) + ) + } + } + } + + // MARK: - Expansion + + /// Opens the groups the user left open, the ones above this tree's own connection once, and the + /// own connection's row unless the user closed it. A search opens every group it left, since + /// each holds a match or the tree's own connection. + /// + /// Returns the own connection's row when it is open on screen, so the caller restores what + /// hangs under it. + internal func applyConnectionExpansion(under parent: DatabaseTreeNode?) -> DatabaseTreeNode? { + guard let outlineView else { return nil } + revealOwnConnectionIfNeeded() + let searching = !searchText.isEmpty + var ownConnection: DatabaseTreeNode? + func walk(_ nodes: [DatabaseTreeNode]) { + for node in nodes { + switch node.kind { + case .connectionGroup(let group): + let open = searching + || revealedConnectionGroupIds.contains(group.id) + || connectionsModel?.isGroupExpanded(group) == true + setExpanded(node, open) + if outlineView.isItemExpanded(node) { walk(resolvedChildren(of: node)) } + case .savedConnection(let ref) where ref.ownsTree: + setExpanded(node, searching || (viewModel?.isOwnConnectionExpanded ?? true)) + if outlineView.isItemExpanded(node) { ownConnection = node } + default: + continue + } + } + } + walk(resolvedChildren(of: parent)) + return ownConnection + } + + /// Once per tree, so a group the user closes over the connection stays closed. A filter is not + /// a reveal: it opens its own groups and gives them back when it clears. + private func revealOwnConnectionIfNeeded() { + guard !hasRevealedOwnConnection, searchText.isEmpty else { return } + let rows = resolvedChildren(of: nil).compactMap { node -> ConnectionNavigatorRow? in + switch node.kind { + case .connectionGroup(let group): return .group(group) + case .savedConnection(let ref): return .connection(ref.row) + default: return nil + } + } + guard let groupIds = DatabaseTreeConnectionRows.groupIds(above: connectionId, in: rows) else { return } + hasRevealedOwnConnection = true + revealedConnectionGroupIds.formUnion(groupIds) + } + + // MARK: - Interaction + + /// The connection a click switches the window to, if the selection change came from one. + internal func connectionClickTarget(selected nodes: [DatabaseTreeNode]) -> UUID? { + guard listsConnections, let model = connectionsModel else { return nil } + return DatabaseTreeConnectionRows.clickSwitchTarget( + selected: nodes.map(\.kind), + hostedHere: Set(model.host?.hostedConnectionIds ?? []), + isPointerClick: Self.isPointerClick(NSApp.currentEvent) + ) + } + + /// `NSTableView` moves the selection on mouse down, so a click is still the current event when + /// the selection change arrives. A key press, type-select or a reload is not a click. + internal static func isPointerClick(_ event: NSEvent?) -> Bool { + guard let event else { return false } + return event.type == .leftMouseDown || event.type == .leftMouseUp + } + + /// Double click and Return on a saved connection other than the tree's own. + internal func activateConnection(_ ref: DatabaseTreeSavedConnectionRef) { + guard let model = connectionsModel else { return } + let window = outlineView?.window + switch DatabaseTreeConnectionRows.activation(of: ref, hostedHere: Set(model.host?.hostedConnectionIds ?? [])) { + case .toggleDisclosure: + guard let outlineView, let node = nodeCache[DatabaseTreeNode.savedConnectionId(ref.id)] else { return } + if outlineView.isItemExpanded(node) { + outlineView.collapseItem(node) + } else { + outlineView.expandItem(node) + } + case .switchTo(let id): + model.perform(.switchTo(id), presentingWindow: window) + case .open(let id): + model.perform(.open(id), presentingWindow: window) + } + } + + // MARK: - Menu + + /// A group or connection row takes the connections column's menu. Returns false for any other + /// row, which keeps the tree's own menu. + internal func fillConnectionMenu(_ menu: NSMenu, clicked: DatabaseTreeNode?) -> Bool { + guard let model = connectionsModel, let clicked else { return false } + let row: ConnectionNavigatorRowID + switch clicked.kind { + case .connectionGroup(let group): + row = .group(group.id) + case .savedConnection(let ref): + row = .connection(ref.id) + default: + return false + } + SidebarMenuBuilder.fill( + menu, + with: ConnectionNavigatorMenu.sections(for: model.menuTarget(for: row)), + target: self, + action: #selector(performConnectionMenuCommand(_:)) + ) + return true + } + + @objc + internal func performConnectionMenuCommand(_ sender: NSMenuItem) { + guard let model = connectionsModel, + let box = sender.representedObject as? SidebarMenuCommandBox + else { return } + guard case .newGroup(let parentId) = box.command else { + model.perform(box.command, presentingWindow: outlineView?.window) + return + } + presentNewGroupSheet(parentId: parentId) + } + + /// The group sheet the Welcome window and the connections column use, saving through the same + /// store. It is presented from the view controller hosting this outline, since SwiftUI's + /// `dismiss` does not reach a sheet AppKit presents. + private func presentNewGroupSheet(parentId: UUID?) { + guard connectionGroupSheet == nil, let model = connectionsModel, let presenter = hostingViewController else { + return + } + let sheet = GroupEditorSheet( + mode: .create(parentId: parentId), + groups: model.groups, + onDismiss: { [weak self] in self?.dismissNewGroupSheet() }, + onSave: { [weak model] fields in try model?.createGroup(fields) } + ) + let controller = NSHostingController(rootView: sheet) + connectionGroupSheet = controller + presenter.presentAsSheet(controller) + } + + private func dismissNewGroupSheet() { + guard let sheet = connectionGroupSheet else { return } + connectionGroupSheet = nil + sheet.presentingViewController?.dismiss(sheet) + } + + private var hostingViewController: NSViewController? { + var responder = outlineView?.nextResponder + while let current = responder { + if let controller = current as? NSViewController { return controller } + responder = current.nextResponder + } + return nil + } +} diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift index 0f2b2188d8..fd594a11a1 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Expansion.swift @@ -10,12 +10,24 @@ import TableProUtilities /// Which rows are disclosed, where that is remembered, and the loads a disclosure triggers. extension DatabaseTreeOutlineCoordinator { internal func applyDesiredExpansion() { - guard let outlineView = self.outlineView else { return } + guard self.outlineView != nil else { return } seedExpansionFromSession() isApplyingExpansion = true defer { isApplyingExpansion = false } + guard listsConnections else { + applyShapeExpansion(roots: resolvedChildren(of: nil)) + return + } + // Rows under a closed connection or group are restored when it opens. + guard let ownConnection = applyConnectionExpansion(under: nil) else { return } + applyShapeExpansion(roots: resolvedChildren(of: ownConnection)) + } + + /// The rows the shape lists at its top, wherever they hang: the root, or the own connection. + private func applyShapeExpansion(roots: [DatabaseTreeNode]) { + guard let outlineView = self.outlineView else { return } let searching = !searchText.isEmpty - for rootNode in resolvedChildren(of: nil) { + for rootNode in roots { switch rootNode.kind { case .recentSection: setExpanded(rootNode, searching || (viewModel?.isRecentsExpanded ?? true)) @@ -27,7 +39,7 @@ extension DatabaseTreeOutlineCoordinator { break } } - for sectionNode in resolvedChildren(of: nil) { + for sectionNode in roots { switch sectionNode.kind { case .objectKindSection(let kind): let hasMatches = flatItemCount(for: kind) > 0 @@ -66,7 +78,7 @@ extension DatabaseTreeOutlineCoordinator { break } } - for databaseNode in resolvedChildren(of: nil) { + for databaseNode in roots { guard case .database(let metadata) = databaseNode.kind else { continue } let want = searching ? databaseMatchesSearch(metadata) @@ -156,7 +168,8 @@ extension DatabaseTreeOutlineCoordinator { case .table, .partition, .tableDetailGroup: triggerLoad(for: node) readOpenDetailRows(under: node) - case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .connectionGroup, .savedConnection, .recentSection, .recentTable, .favoritesSection, .favoriteTable, + .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .database, .schema, .tableDetail, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode: continue @@ -220,6 +233,11 @@ extension DatabaseTreeOutlineCoordinator { isApplyingExpansion = true defer { isApplyingExpansion = wasApplyingExpansion } switch node.kind { + case .connectionGroup: + guard let ownConnection = applyConnectionExpansion(under: node) else { break } + applyShapeExpansion(roots: resolvedChildren(of: ownConnection)) + case .savedConnection(let ref) where ref.ownsTree: + applyShapeExpansion(roots: resolvedChildren(of: node)) case .database where !supportsSchemaLevel: restoreObjectGroupExpansion(under: node) case .schema, .hierarchicalSchemaSection: @@ -228,13 +246,14 @@ extension DatabaseTreeOutlineCoordinator { restoreFolderExpansion(under: node) case .objectKindSection, .containerObjectKindSection, .tableFolder, .table, .partition, .tableDetailGroup: restoreTableExpansion(under: node) - case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .database, .routine, .trigger, - .userType, .status, .redisKeysSection, .redisNode, .tableDetail: + case .savedConnection, .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, + .temporaryTable, .database, .routine, .trigger, .userType, .status, .redisKeysSection, .redisNode, + .tableDetail: break } } - private func setExpanded(_ node: DatabaseTreeNode, _ expanded: Bool) { + internal func setExpanded(_ node: DatabaseTreeNode, _ expanded: Bool) { guard let outlineView = self.outlineView else { return } if expanded, !outlineView.isItemExpanded(node) { outlineView.expandItem(node) @@ -245,6 +264,12 @@ extension DatabaseTreeOutlineCoordinator { internal func recordExpansion(_ node: DatabaseTreeNode, expanded: Bool) { switch node.kind { + case .connectionGroup(let group): + if !expanded { revealedConnectionGroupIds.remove(group.id) } + connectionsModel?.setGroupExpanded(group.id, expanded) + case .savedConnection(let ref): + guard ref.ownsTree else { break } + viewModel?.isOwnConnectionExpanded = expanded case .recentSection: viewModel?.isRecentsExpanded = expanded case .favoritesSection: @@ -330,7 +355,8 @@ extension DatabaseTreeOutlineCoordinator { || !hierarchicalSearchSkipsRead(schema) else { return } loadHierarchicalSchemaObjects(schema) - case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .connectionGroup, .savedConnection, .recentSection, .recentTable, .favoritesSection, .favoriteTable, + .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .routine, .trigger, .userType, .status, .objectKindSection, .containerObjectKindSection, .redisKeysSection, .redisNode, .tableDetail: break diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift index 2fbf7dd547..2896a575ea 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Menu.swift @@ -14,6 +14,7 @@ import TableProPluginKit /// replaced, never let the table see the click at all. extension DatabaseTreeOutlineCoordinator: NSMenuDelegate { internal func menuNeedsUpdate(_ menu: NSMenu) { + if fillConnectionMenu(menu, clicked: clickedNode()) { return } SidebarMenuBuilder.fill( menu, with: DatabaseTreeMenuSpec.sections(for: menuContext()), diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift index 219a83237b..c9e16bcaaf 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Nodes.swift @@ -44,6 +44,10 @@ extension DatabaseTreeOutlineCoordinator { private func buildChildren(of node: DatabaseTreeNode?) -> [DatabaseTreeNode] { guard let node else { return rootNodes() } switch node.kind { + case .connectionGroup(let group): + return connectionLevelNodes(group.children) + case .savedConnection(let ref): + return ref.ownsTree ? shapeRootNodes() : [] case .recentSection: return recentTableRefs().map { self.node(id: DatabaseTreeNode.recentTableId($0), kind: .recentTable($0)) @@ -145,6 +149,12 @@ extension DatabaseTreeOutlineCoordinator { } private func rootNodes() -> [DatabaseTreeNode] { + listsConnections ? connectionLevelNodes(connectionTreeRows()) : shapeRootNodes() + } + + /// What the shape lists at its top: the root itself, or the own connection's row when the tree + /// lists the saved connections above it. + internal func shapeRootNodes() -> [DatabaseTreeNode] { switch rootShape { case .databaseTree: return databaseTreeRootNodes() case .flat: return flatRootNodes() @@ -166,9 +176,27 @@ extension DatabaseTreeOutlineCoordinator { nodes += matched .filter { seen.insert($0.id).inserted } .map { node(id: DatabaseTreeNode.databaseId($0.name), kind: .database($0)) } + if matched.isEmpty, let status = ownDatabaseListStatus() { + nodes.append(statusNode(parentId: DatabaseTreeNode.savedConnectionId(connectionId), status: status)) + } return nodes } + /// Under its connection's row the tree stands whatever the database list is doing, so the + /// connections above stay on screen. The states the view showed in the outline's place say + /// themselves here. A search that matches nothing lists nothing, as it does without the row. + private func ownDatabaseListStatus() -> DatabaseTreeNode.Status? { + guard listsConnections, searchText.isEmpty else { return nil } + switch service.databaseListState(for: connectionId) { + case .idle, .loading: + return .loading + case .failed(let message): + return .error(message) + case .loaded: + return .empty + } + } + internal var browsingDatabase: String? { let name = mainCoordinator?.browseDatabaseName ?? activeDatabase ?? "" return name.isEmpty ? nil : name diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 277a6cb0e2..267a2154cc 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -38,6 +38,20 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { private var pendingDeletes: Set = [] internal var showRecentTables = true internal var showsFavoritesSection = false + /// The setting as the view passes it. `listsConnections` is what the outline draws from, since + /// only the database tree takes the connections. + internal var showsConnectionsInTree = false + /// Settled once per reload, because AppKit asks `isGroupItem` of every row it lays out. + internal private(set) var listsConnections = false + /// The saved connections and what a row of them does. Built when the tree first lists them, or + /// handed in by a test, and kept while it does. + internal var connectionsModel: ConnectionNavigatorModel? + internal var connectionsModelObservations: [AnyCancellable] = [] + /// Groups opened to show this tree's own connection. The outline holds them open and the stored + /// expansion never hears of them, as the connections column treats its reveal. + internal var revealedConnectionGroupIds: Set = [] + internal var hasRevealedOwnConnection = false + internal var connectionGroupSheet: NSViewController? internal var showSystemContainers = false internal var showsPartitions = true /// Off, no row draws a detail list, so the loaded ones go and nothing reads them again: the @@ -232,6 +246,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { || pendingDeletes != view.pendingDeletes || showRecentTables != view.showRecentTables || showsFavoritesSection != view.showsFavoritesSection + || showsConnectionsInTree != view.showsConnectionsInTree || showSystemContainers != view.showSystemContainers || showsPartitions != view.showsPartitions || showsTableDetails != view.showsTableDetails @@ -245,6 +260,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { pendingDeletes = view.pendingDeletes showRecentTables = view.showRecentTables showsFavoritesSection = view.showsFavoritesSection + showsConnectionsInTree = view.showsConnectionsInTree showSystemContainers = view.showSystemContainers showsPartitions = view.showsPartitions showsTableDetails = view.showsTableDetails @@ -294,7 +310,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { ].compactMap { $0 } } - private func scheduleReconcile(forcing: Bool = false) { + internal func scheduleReconcile(forcing: Bool = false) { isReconcileForced = isReconcileForced || forcing guard !reconcileScheduled else { return } reconcileScheduled = true @@ -331,6 +347,8 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { return } isReloading = true + listsConnections = DatabaseTreeConnectionRows.applies(settingEnabled: showsConnectionsInTree, rootShape: rootShape) + syncConnectionsModel() renderedInputs = currentRenderInputs() dropUnusedMemos() childrenCache.removeAll() @@ -672,7 +690,8 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { }, showsPartitions: showsPartitions, listsAttachedSchemas: listsAttachedSchemas, - tableDetailCount: { [weak self] group in self?.tableDetailCount(group) } + tableDetailCount: { [weak self] group in self?.tableDetailCount(group) }, + drawsSectionsAsRows: listsConnections ) } @@ -804,6 +823,8 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { mainCoordinator?.showObjectSource(objectRef) case .showStructure(let ref): perform(SidebarMenuCommand.showStructure(ref)) + case .activateConnection(let ref): + activateConnection(ref) case .toggleDisclosure: if outlineView.isItemExpanded(node) { outlineView.collapseItem(node) @@ -913,8 +934,12 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { /// 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. + /// + /// Under a saved connection's row nothing is a group row: AppKit lays a group out at its own depth + /// and would pull a section out from under the connection that holds it. func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool { - (item as? DatabaseTreeNode)?.isGroupRow ?? false + guard !listsConnections else { return false } + return (item as? DatabaseTreeNode)?.isGroupRow ?? false } func outlineView( @@ -1009,6 +1034,13 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { func outlineViewSelectionDidChange(_ notification: Notification) { guard !isSyncingSelection, !isReloading, !isCollapsingItem else { return } let nodes = selectedNodes() + /// A click on another connection open here moves the window to it. The highlight goes back to + /// what this tree had, so the row is not left selected for when the user comes back. + if let target = connectionClickTarget(selected: nodes) { + scheduleSelectionSync(force: true) + connectionsModel?.perform(.switchTo(target), presentingWindow: outlineView?.window) + return + } lastSelectedNodeIds = nodes.map(\.id) let refs = Set(DatabaseTreeSelection.openableRefs(of: nodes)) let target = DatabaseTreeSelection.navigationTarget( diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift index 155416750a..67691ea391 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineView.swift @@ -34,6 +34,7 @@ struct DatabaseTreeOutlineView: NSViewRepresentable { let showsTableDetails: Bool let rowSizePreference: SidebarRowSizePreference var showsFavoritesSection = false + var showsConnectionsInTree = false /// The size the rows are actually drawn at, which is the system's unless the user overrode it. var resolvedRowSize: SidebarRowSize { @@ -60,7 +61,7 @@ struct DatabaseTreeOutlineView: NSViewRepresentable { outlineView.target = context.coordinator /// No `action`: it arrives on mouse up, a whole gesture after the selection the user can /// already see. Opening follows the selection instead, so `doubleAction` is free to mean - /// "keep this one" on a table row and to disclose on a container. + /// "keep this one" on a table row, to disclose on a container and to open a saved connection. outlineView.doubleAction = #selector(DatabaseTreeOutlineCoordinator.handleDoubleClick) outlineView.selectionClearing = context.coordinator outlineView.primaryActionTarget = context.coordinator diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift index 93b6e636a6..ab10a2505e 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift @@ -57,6 +57,9 @@ struct DatabaseTreeRowContext { var listsAttachedSchemas: Bool = false /// A group's count comes from the list its table read, which only the coordinator holds. var tableDetailCount: @MainActor (DatabaseTreeTableDetailGroupRef) -> Int? = { _ in nil } + /// Under a saved connection's row the sections are ordinary rows: AppKit lays a source list group + /// out at the root's own depth, which would pull them out from under the connection. + var drawsSectionsAsRows = false } struct DatabaseTreeRowView: View { @@ -87,14 +90,18 @@ struct DatabaseTreeRowView: View { @ViewBuilder private var rowContent: some View { switch node.kind { + case .connectionGroup(let group): + ConnectionNavigatorGroupLabel(group: group) + case .savedConnection(let ref): + ConnectionNavigatorConnectionLabel(row: ref.row, glyphSide: context.rowSize.iconPointSize) case .recentSection: - sectionHeader(String(localized: "Recent")) + sectionHeader(String(localized: "Recent"), systemImage: "clock") case .recentTable(let ref), .favoriteTable(let ref): tableRow(ref) case .favoritesSection: - sectionHeader(String(localized: "Favorites")) + sectionHeader(String(localized: "Favorites"), systemImage: "star") case .temporarySection: - sectionHeader(String(localized: "Temporary")) + sectionHeader(String(localized: "Temporary"), systemImage: "hourglass") case .temporaryTable(let ref): TableRow( table: ref.table, @@ -104,7 +111,7 @@ struct DatabaseTreeRowView: View { accessibilityKind: String(localized: "Temporary Table") ) case .foldersSection: - sectionHeader(String(localized: "Folders")) + sectionHeader(String(localized: "Folders"), systemImage: "folder") case .tableFolder(let ref): folderRow(ref) case .database(let metadata): @@ -136,7 +143,7 @@ struct DatabaseTreeRowView: View { case .status(let status): statusRow(status) case .objectKindSection(let kind): - sectionHeader(context.objectKindTitle(kind)) + sectionHeader(context.objectKindTitle(kind), systemImage: kind.iconName) case .containerObjectKindSection(let group): objectGroupRow(group.kind) case .hierarchicalSchemaSection(let schema): @@ -147,7 +154,7 @@ struct DatabaseTreeRowView: View { isSystem: false ) case .redisKeysSection: - sectionHeader(String(localized: "Keys")) + sectionHeader(String(localized: "Keys"), systemImage: "key") case .redisNode(let redisNode): redisRow(redisNode) } @@ -155,12 +162,20 @@ 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. - private func sectionHeader(_ text: String) -> some View { - Text(text) - .font(.caption.weight(.semibold)) - .foregroundStyle(.secondary) - .lineLimit(1) + /// competing with the one on every object below it. Drawn as an ordinary row it takes the icon + /// every other row at its depth has. + @ViewBuilder + private func sectionHeader(_ text: String, systemImage: String) -> some View { + if context.drawsSectionsAsRows { + Label(text, systemImage: systemImage) + .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .lineLimit(1) + } else { + Text(text) + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + .lineLimit(1) + } } private func folderRow(_ ref: DatabaseTreeFolderRef) -> some View { diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift index cc8475d715..19ec1674dd 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeSelection.swift @@ -18,8 +18,8 @@ internal enum DatabaseTreeSelection { case .status, .recentSection, .favoritesSection, .temporarySection, .foldersSection, .objectKindSection, .redisKeysSection: return false - case .database, .schema, .hierarchicalSchemaSection, .table, .partition, .routine, .trigger, .userType, - .recentTable, .favoriteTable, .temporaryTable, .containerObjectKindSection, .tableFolder, .redisNode, + case .connectionGroup, .savedConnection, .database, .schema, .hierarchicalSchemaSection, .table, .partition, + .routine, .trigger, .userType, .recentTable, .favoriteTable, .temporaryTable, .containerObjectKindSection, .tableFolder, .redisNode, .tableDetailGroup, .tableDetail: return true } @@ -84,7 +84,7 @@ internal enum DatabaseTreeSelection { return DatabaseTreeObjectGroup(database: hierarchicalDatabase, schema: schema, kind: .table) case .containerObjectKindSection(let group): return group - case .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, + case .connectionGroup, .savedConnection, .recentSection, .recentTable, .favoritesSection, .favoriteTable, .temporarySection, .temporaryTable, .foldersSection, .tableFolder, .table, .partition, .tableDetailGroup, .tableDetail, .routine, .trigger, .userType, .status, .objectKindSection, .redisKeysSection, .redisNode: return nil diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift index 11d4e63c89..c473b9a5f4 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeTypeSelect.swift @@ -55,6 +55,10 @@ internal enum DatabaseTreeTypeSelect { case .recentSection, .favoritesSection, .temporarySection, .foldersSection, .status, .objectKindSection, .redisKeysSection: return nil + case .connectionGroup(let group): + return group.name + case .savedConnection(let ref): + return ref.row.connection.name case .tableFolder(let ref): return ref.folder.name case .containerObjectKindSection(let group): diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift index f3c03b99df..ff87764285 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift @@ -123,7 +123,32 @@ struct DatabaseTreeView: View { } } + /// Listing the saved connections, the outline stands whatever the database list is doing, so + /// the connections above it stay on screen. Its own connection's row says loading, failed or + /// empty in the states that replace the outline otherwise. + private var listsConnections: Bool { + settingsManager.general.showsConnectionsInTree + } + var body: some View { + Group { + if listsConnections { + VStack(spacing: 0) { + filterBanner + outline + } + } else { + databaseListContent + } + } + .loadingRevealGate(isActive: isLoadingDatabases && !listsConnections, isRevealed: $showsDatabaseProgress) + .task(id: isConnected) { + await treeService.loadDatabases(connectionId: connectionId, databaseType: databaseType) + } + } + + @ViewBuilder + private var databaseListContent: some View { Group { switch treeService.databaseListState(for: connectionId) { case .failed(let message): @@ -145,10 +170,6 @@ struct DatabaseTreeView: View { } } } - .loadingRevealGate(isActive: isLoadingDatabases, isRevealed: $showsDatabaseProgress) - .task(id: isConnected) { - await treeService.loadDatabases(connectionId: connectionId, databaseType: databaseType) - } } @ViewBuilder @@ -193,7 +214,8 @@ struct DatabaseTreeView: View { showsPartitions: settingsManager.general.showPartitions, showsTableDetails: settingsManager.general.showTableDetails, rowSizePreference: settingsManager.general.sidebarRowSize, - showsFavoritesSection: settingsManager.general.showsFavoritesSection + showsFavoritesSection: settingsManager.general.showsFavoritesSection, + showsConnectionsInTree: listsConnections ) } diff --git a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift index 7f00637e83..b990be98b2 100644 --- a/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/DatabaseTreeMenuSpec.swift @@ -72,6 +72,10 @@ internal enum DatabaseTreeMenuSpec { // sidebar's own menu, as a status row does. case .status, .recentSection, .favoritesSection, .temporarySection, .tableDetailGroup: return backgroundSections(context) + // A saved connection's menu is the connections column's, which the coordinator fills before this + // spec is asked. Nothing here acts on a connection, so none of the sidebar's own items apply. + case .connectionGroup, .savedConnection: + return [] } } diff --git a/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift b/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift index cf9ccc8ebf..2d9900ce1e 100644 --- a/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift +++ b/apple/TablePro/Views/Sidebar/SidebarPersistenceKey.swift @@ -20,6 +20,11 @@ enum SidebarPersistenceKey { "sidebar.\(connectionId.uuidString).favorites.expanded" } + /// The connection's own row in a tree that lists the saved connections above its databases. + static func ownConnectionExpanded(connectionId: UUID) -> String { + "sidebar.\(connectionId.uuidString).connection.expanded" + } + static func foldersExpanded(connectionId: UUID) -> String { "sidebar.\(connectionId.uuidString).folders.expanded" } @@ -57,6 +62,8 @@ enum SidebarPersistenceKey { tablesExpanded(connectionId: connectionId), redisKeysExpanded(connectionId: connectionId), recentsExpanded(connectionId: connectionId), + favoritesExpanded(connectionId: connectionId), + ownConnectionExpanded(connectionId: connectionId), foldersExpanded(connectionId: connectionId), temporaryExpanded(connectionId: connectionId), selectedTab(connectionId: connectionId), diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionRowsTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionRowsTests.swift new file mode 100644 index 0000000000..5e1ecbd1f3 --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionRowsTests.swift @@ -0,0 +1,214 @@ +// +// DatabaseTreeConnectionRowsTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import Testing + +/// The saved connections at the top of the tree: which rows stand, and what a click, a double +/// click or Return on one does. +struct DatabaseTreeConnectionRowsTests { + private static func connectionRow(_ name: String, id: UUID = UUID()) -> ConnectionNavigatorConnectionRow { + ConnectionNavigatorConnectionRow( + connection: DatabaseConnection(id: id, name: name), + groupPath: [], + isDriverRejected: false, + status: .notConnected, + placement: .notOpen + ) + } + + private static func group( + _ name: String, + id: UUID = UUID(), + isExpanded: Bool = false, + _ children: [ConnectionNavigatorRow] + ) -> ConnectionNavigatorRow { + .group(ConnectionNavigatorGroupRow( + id: id, + name: name, + color: .none, + iconName: nil, + connectionCount: children.count, + isExpanded: isExpanded, + children: children + )) + } + + /// Depth first, the order the outline draws them in when every group is open. + private static func names(_ rows: [ConnectionNavigatorRow]) -> [String] { + rows.flatMap { [$0.name] + names($0.children) } + } + + private static func ref(_ row: ConnectionNavigatorConnectionRow, ownsTree: Bool) -> DatabaseTreeSavedConnectionRef { + DatabaseTreeSavedConnectionRef(row: row, ownsTree: ownsTree) + } + + // MARK: - Shape + + @Test("Only the database tree lists the saved connections") + func onlyTheDatabaseTreeListsConnections() { + #expect(DatabaseTreeConnectionRows.applies(settingEnabled: true, rootShape: .databaseTree)) + #expect(!DatabaseTreeConnectionRows.applies(settingEnabled: true, rootShape: .flat)) + #expect(!DatabaseTreeConnectionRows.applies(settingEnabled: true, rootShape: .hierarchicalSchema)) + #expect(!DatabaseTreeConnectionRows.applies(settingEnabled: false, rootShape: .databaseTree)) + } + + // MARK: - Rows + + @Test("With no filter the tree lists the library as the connections column builds it") + func noFilterKeepsTheLibrary() { + let own = Self.connectionRow("Shop") + let library = [Self.group("Work", [.connection(own), .connection(Self.connectionRow("Billing"))]), + .connection(Self.connectionRow("Local"))] + + let rows = DatabaseTreeConnectionRows.rows(from: library, ownId: own.id, filterText: "") + + #expect(rows == library) + } + + @Test("A filter keeps the tree's own connection and the connections whose names match, in their groups") + func filterKeepsOwnAndMatches() throws { + let own = Self.connectionRow("Shop") + let groupId = UUID() + let library = [ + Self.group("Work", id: groupId, [ + .connection(own), + .connection(Self.connectionRow("Billing")), + .connection(Self.connectionRow("Reports")), + ]), + Self.group("Empty", [.connection(Self.connectionRow("Archive"))]), + .connection(Self.connectionRow("Local Billing")), + ] + + let rows = DatabaseTreeConnectionRows.rows(from: library, ownId: own.id, filterText: " bill ") + + #expect(Self.names(rows) == ["Work", "Shop", "Billing", "Local Billing"]) + guard case .group(let work) = try #require(rows.first) else { + Issue.record("The group holding a match stays") + return + } + #expect(work.id == groupId) + #expect(work.isExpanded, "A filter opens every group it leaves") + #expect(work.connectionCount == 2) + } + + @Test("A connection the library does not hold is listed first, and only when it is missing") + func unsavedOwnConnectionIsListedFirst() { + let unsaved = Self.connectionRow("From a file") + let saved = Self.connectionRow("Saved") + let library: [ConnectionNavigatorRow] = [.connection(saved)] + + let withUnsaved = DatabaseTreeConnectionRows.rows( + from: library, ownId: unsaved.id, unsavedOwnRow: unsaved, filterText: "" + ) + let withSaved = DatabaseTreeConnectionRows.rows( + from: library, ownId: saved.id, unsavedOwnRow: saved, filterText: "" + ) + + #expect(Self.names(withUnsaved) == ["From a file", "Saved"]) + #expect(withSaved == library) + } + + @Test("The groups above a connection are found outermost first") + func groupsAboveAConnection() { + let own = Self.connectionRow("Shop") + let outer = UUID() + let inner = UUID() + let library = [ + Self.group("Outer", id: outer, [Self.group("Inner", id: inner, [.connection(own)])]), + .connection(Self.connectionRow("Local")), + ] + + #expect(DatabaseTreeConnectionRows.groupIds(above: own.id, in: library) == [outer, inner]) + #expect(DatabaseTreeConnectionRows.groupIds(above: UUID(), in: library) == nil) + #expect(DatabaseTreeConnectionRows.contains(own.id, in: library)) + } + + // MARK: - Interaction + + @Test("Return on the tree's own connection opens or closes it, on another one switches or opens") + func activationOfEachKindOfRow() { + let own = Self.connectionRow("Shop") + let hosted = Self.connectionRow("Billing") + let closed = Self.connectionRow("Local") + let hostedHere: Set = [own.id, hosted.id] + + #expect(DatabaseTreeConnectionRows.activation(of: Self.ref(own, ownsTree: true), hostedHere: hostedHere) + == .toggleDisclosure) + #expect(DatabaseTreeConnectionRows.activation(of: Self.ref(hosted, ownsTree: false), hostedHere: hostedHere) + == .switchTo(hosted.id)) + #expect(DatabaseTreeConnectionRows.activation(of: Self.ref(closed, ownsTree: false), hostedHere: hostedHere) + == .open(closed.id)) + } + + @Test("A click switches only to another connection open in this window") + func clickSwitchesOnlyBetweenHostedConnections() { + let own = Self.connectionRow("Shop") + let hosted = Self.connectionRow("Billing") + let closed = Self.connectionRow("Local") + let hostedHere: Set = [own.id, hosted.id] + func target(_ kinds: [DatabaseTreeNode.Kind], click: Bool = true) -> UUID? { + DatabaseTreeConnectionRows.clickSwitchTarget(selected: kinds, hostedHere: hostedHere, isPointerClick: click) + } + let hostedKind = DatabaseTreeNode.Kind.savedConnection(Self.ref(hosted, ownsTree: false)) + + #expect(target([hostedKind]) == hosted.id) + #expect(target([hostedKind], click: false) == nil, "Arrowing down the tree does not hop between workspaces") + #expect(target([.savedConnection(Self.ref(own, ownsTree: true))]) == nil) + #expect(target([.savedConnection(Self.ref(closed, ownsTree: false))]) == nil, "A click never dials") + #expect(target([hostedKind, .recentSection]) == nil, "Extending a selection is not a pick") + } + + // MARK: - Nodes + + @Test("Only the tree's own connection discloses, and no connection row is a source list group") + func nodeRules() { + let own = DatabaseTreeNode( + id: "own", kind: .savedConnection(Self.ref(Self.connectionRow("Shop"), ownsTree: true)) + ) + let other = DatabaseTreeNode( + id: "other", kind: .savedConnection(Self.ref(Self.connectionRow("Local"), ownsTree: false)) + ) + let group = DatabaseTreeNode(id: "group", kind: Self.group("Work", [.connection(Self.connectionRow("A"))]).treeKind) + let emptyGroup = DatabaseTreeNode(id: "empty", kind: Self.group("Empty", []).treeKind) + + #expect(own.isExpandable) + #expect(!other.isExpandable) + #expect(group.isExpandable) + #expect(!emptyGroup.isExpandable) + for node in [own, other, group] { + #expect(!node.isGroupRow) + #expect(!node.isContainer) + #expect(DatabaseTreeSelection.isSelectable(node.kind)) + #expect(DatabaseTreeSelection.tableRef(of: node) == nil) + } + #expect(!own.opensWithAncestor(showsTableDetails: false), "Option-opening a group does not open every database") + #expect(DatabaseTreeTypeSelect.matchString(for: own.kind) == "Shop") + #expect(DatabaseTreeTypeSelect.matchString(for: group.kind) == "Work") + } + + @Test("A double click opens another connection and discloses the tree's own") + func doubleClickIntent() { + let otherRef = Self.ref(Self.connectionRow("Local"), ownsTree: false) + let own = DatabaseTreeNode( + id: "own", kind: .savedConnection(Self.ref(Self.connectionRow("Shop"), ownsTree: true)) + ) + + #expect(DatabaseTreeDoubleClickResolver.resolve(node: DatabaseTreeNode(id: "other", kind: .savedConnection(otherRef))) + == .activateConnection(otherRef)) + #expect(DatabaseTreeDoubleClickResolver.resolve(node: own) == .toggleDisclosure) + } +} + +private extension ConnectionNavigatorRow { + var treeKind: DatabaseTreeNode.Kind { + switch self { + case .group(let group): return .connectionGroup(group) + case .connection(let connection): return .savedConnection(DatabaseTreeSavedConnectionRef(row: connection, ownsTree: false)) + } + } +} diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionsInTreeTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionsInTreeTests.swift new file mode 100644 index 0000000000..050b43bdc4 --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeConnectionsInTreeTests.swift @@ -0,0 +1,324 @@ +// +// DatabaseTreeConnectionsInTreeTests.swift +// TableProTests +// + +import AppKit +import Combine +import Foundation +import SwiftUI +@testable import TablePro +import TableProConnectionLibrary +import TableProPluginKit +import TableProTestSupport +import Testing + +/// The tree with the saved connections at its top: groups, then connections, with the tree's own +/// connection opened to its databases. The library, events, window and router are the connections +/// column's test doubles, so nothing reaches the app's real library or opens a window. The tree's +/// own connection is a PGlite session, so every read stays on the injected driver. +@MainActor +struct DatabaseTreeConnectionsInTreeTests { + private struct Fixture { + let library: ConnectionNavigatorFixture + let own: DatabaseConnection + let billing: DatabaseConnection + let local: DatabaseConnection + let work: ConnectionGroup + let coordinator: DatabaseTreeOutlineCoordinator + let outlineView: NSOutlineView + let scrollView: NSScrollView + let viewModel: SidebarViewModel + let defaults: EphemeralDefaults + } + + private let service = DatabaseTreeMetadataService.shared + + /// "Work" holds this tree's own connection, Shop, and Billing, which this window also hosts. + /// Local sits outside any group and nobody hosts it. + private func makeFixture( + showsConnections: Bool = true, + layout: SidebarLayout = .tree, + searchText: String = "" + ) async throws -> Fixture { + let library = try ConnectionNavigatorFixture() + let work = ConnectionGroup(name: "Work") + try library.groupStorage.addGroup(work) + var own = TestFixtures.makeConnection(name: "Shop", database: "shop", type: .pglite) + own.groupId = work.id + var billing = TestFixtures.makeConnection(name: "Billing", database: "billing", type: .mysql) + billing.groupId = work.id + let local = TestFixtures.makeConnection(name: "Local", database: "local", type: .postgresql) + library.save([own, billing, local]) + library.host.hosted = [own.id, billing.id] + library.host.selected = own.id + library.statuses[own.id] = .connected + + let driver = MockDatabaseDriver(connection: own) + driver.databasesToReturn = ["shop", "analytics"] + var session = ConnectionSession(connection: own, driver: driver) + session.status = .connected + DatabaseManager.shared.injectSession(session, for: own.id) + await service.loadDatabases(connectionId: own.id, databaseType: .pglite) + + let scrollView = SidebarOutlineScaffold.makeScrollView( + outlineView: NSOutlineView(), + configuration: SidebarOutlineScaffold.Configuration( + columnIdentifier: "ConnectionsInTreeColumn", + allowsMultipleSelection: true, + rowSizePreference: .medium + ) + ) + scrollView.frame = NSRect(x: 0, y: 0, width: 280, height: 800) + let outlineView = try #require(scrollView.documentView as? NSOutlineView) + let sidebarState = SharedSidebarState.forConnection(own.id) + sidebarState.sidebarLayout = layout + let defaults = try EphemeralDefaults() + let viewModel = SidebarViewModel( + selectedTables: .constant([]), + pendingTruncates: .constant([]), + pendingDeletes: .constant([]), + tableOperationOptions: .constant([:]), + databaseType: .pglite, + connectionId: own.id, + defaults: defaults.defaults + ) + let coordinator = DatabaseTreeOutlineCoordinator() + coordinator.connectionId = own.id + coordinator.databaseType = .pglite + coordinator.sidebarState = sidebarState + coordinator.windowState = WindowSidebarState() + coordinator.viewModel = viewModel + coordinator.activeDatabase = "shop" + coordinator.showRecentTables = false + coordinator.searchText = searchText + coordinator.showsConnectionsInTree = showsConnections + coordinator.connectionsModel = library.makeModel() + outlineView.dataSource = coordinator + outlineView.delegate = coordinator + coordinator.attach(outlineView: outlineView) + coordinator.refresh() + return Fixture( + library: library, + own: own, + billing: billing, + local: local, + work: work, + coordinator: coordinator, + outlineView: outlineView, + scrollView: scrollView, + viewModel: viewModel, + defaults: defaults + ) + } + + private func tearDown(_ fixture: Fixture) async { + fixture.coordinator.connectionsModel?.stop() + await service.handleDisconnect(connectionId: fixture.own.id) + ExternalSchemaTracker.shared.reset(connectionId: fixture.own.id) + DatabaseManager.shared.removeSession(for: fixture.own.id) + SharedSidebarState.removeConnection(fixture.own.id) + _ = fixture.scrollView + _ = fixture.viewModel + _ = fixture.defaults + } + + private func roots(_ fixture: Fixture) -> [DatabaseTreeNode] { + fixture.coordinator.resolvedChildren(of: nil) + } + + private func rowNodes(_ fixture: Fixture) -> [DatabaseTreeNode] { + (0.. DatabaseTreeNode? { + rowNodes(fixture).first { $0.savedConnectionRef?.id == id } + } + + private func groupNode(_ fixture: Fixture) -> DatabaseTreeNode? { + roots(fixture).first { node in + guard case .connectionGroup(let group) = node.kind else { return false } + return group.id == fixture.work.id + } + } + + private func databaseNames(under node: DatabaseTreeNode, in fixture: Fixture) -> [String] { + fixture.coordinator.resolvedChildren(of: node).compactMap { node in + guard case .database(let metadata) = node.kind else { return nil } + return metadata.name + } + } + + // MARK: - Shape + + @Test("The tree lists the saved connections in their groups, with its own opened to its databases") + func connectionsAboveTheDatabases() async throws { + let fixture = try await makeFixture() + + let group = try #require(groupNode(fixture)) + #expect(roots(fixture).contains { $0.savedConnectionRef?.id == fixture.local.id }) + #expect(fixture.outlineView.isItemExpanded(group), "The group holding the tree's own connection opens") + + let own = try #require(connectionNode(fixture.own.id, in: fixture)) + #expect(own.savedConnectionRef?.ownsTree == true) + #expect(fixture.outlineView.isItemExpanded(own)) + #expect(Set(databaseNames(under: own, in: fixture)) == ["shop", "analytics"]) + #expect(fixture.outlineView.parent(forItem: own) as? DatabaseTreeNode === group) + + for other in [fixture.billing.id, fixture.local.id] { + let node = try #require(connectionNode(other, in: fixture)) + #expect(node.savedConnectionRef?.ownsTree == false) + #expect(!fixture.outlineView.isExpandable(node)) + #expect(fixture.coordinator.resolvedChildren(of: node).isEmpty) + } + await tearDown(fixture) + } + + @Test("With the setting off the databases are the tree's top rows, as before") + func settingOffKeepsDatabasesAtTheTop() async throws { + let fixture = try await makeFixture(showsConnections: false) + + #expect(!roots(fixture).contains { $0.savedConnectionRef != nil }) + let databases = roots(fixture).compactMap { node -> String? in + guard case .database(let metadata) = node.kind else { return nil } + return metadata.name + } + #expect(Set(databases) == ["shop", "analytics"]) + #expect(fixture.coordinator.connectionsModel?.rows.isEmpty == true, "A tree that lists no connections reads no library") + await tearDown(fixture) + } + + @Test("The flat layout lists no connections even with the setting on") + func flatLayoutListsNoConnections() async throws { + let fixture = try await makeFixture(layout: .flat) + + #expect(!roots(fixture).contains { $0.savedConnectionRef != nil }) + await tearDown(fixture) + } + + /// AppKit lays a source list group out at the root's own depth, so a Recent or Favorites section + /// under the connection would be pulled out from under it. + @Test("Under a connection no section is a source list group") + func sectionsAreOrdinaryRowsUnderAConnection() async throws { + let listing = try await makeFixture() + let flat = try await makeFixture(showsConnections: false) + let section = DatabaseTreeNode(id: DatabaseTreeNode.recentSectionId, kind: .recentSection) + + #expect(!listing.coordinator.outlineView(listing.outlineView, isGroupItem: section)) + #expect(flat.coordinator.outlineView(flat.outlineView, isGroupItem: section)) + await tearDown(listing) + await tearDown(flat) + } + + // MARK: - Filter + + @Test("The filter keeps the tree's own connection and the connections whose names match") + func filterNarrowsTheConnections() async throws { + let fixture = try await makeFixture(searchText: "bill") + + #expect(connectionNode(fixture.own.id, in: fixture) != nil, "The objects the filter finds hang from it") + #expect(connectionNode(fixture.billing.id, in: fixture) != nil) + #expect(!roots(fixture).contains { $0.savedConnectionRef?.id == fixture.local.id }) + await tearDown(fixture) + } + + // MARK: - Expansion + + @Test("Closing the group and the own connection is remembered, and survives a reload") + func closingIsRemembered() async throws { + let fixture = try await makeFixture() + let own = try #require(connectionNode(fixture.own.id, in: fixture)) + let group = try #require(groupNode(fixture)) + + fixture.outlineView.collapseItem(own) + #expect(!fixture.viewModel.isOwnConnectionExpanded) + + fixture.outlineView.collapseItem(group) + fixture.coordinator.refresh() + + #expect(!fixture.outlineView.isItemExpanded(group)) + #expect(!fixture.library.expansionStore.load(keeping: [fixture.work.id]).contains(fixture.work.id)) + + fixture.outlineView.expandItem(group) + #expect(fixture.library.expansionStore.load(keeping: [fixture.work.id]) == [fixture.work.id]) + #expect(!fixture.outlineView.isItemExpanded(own), "The own connection stays as the user left it") + await tearDown(fixture) + } + + // MARK: - Interaction + + @Test("Opening another connection this window hosts switches to it") + func activatingAHostedConnectionSwitches() async throws { + let fixture = try await makeFixture() + let billing = try #require(connectionNode(fixture.billing.id, in: fixture)?.savedConnectionRef) + + fixture.coordinator.activateConnection(billing) + + #expect(fixture.library.host.selected == fixture.billing.id) + #expect(fixture.library.router.openedConnections.isEmpty) + await tearDown(fixture) + } + + @Test("Opening a connection nobody hosts goes through the router") + func activatingAClosedConnectionRoutes() async throws { + let fixture = try await makeFixture() + let local = try #require(connectionNode(fixture.local.id, in: fixture)?.savedConnectionRef) + + fixture.coordinator.activateConnection(local) + + try await waitUntil { fixture.library.router.openedConnections == [fixture.local.id] } + #expect(fixture.library.host.selected == fixture.own.id) + await tearDown(fixture) + } + + @Test("A connection row takes the connections column's menu, and the tree's own needs no way to reach it") + func connectionRowsTakeTheNavigatorMenu() async throws { + let fixture = try await makeFixture() + let menu = NSMenu() + let titles = { menu.items.filter { !$0.isSeparatorItem }.map(\.title) } + + #expect(fixture.coordinator.fillConnectionMenu(menu, clicked: connectionNode(fixture.local.id, in: fixture))) + #expect(titles().first == ConnectionNavigatorMenu.Titles.connect) + #expect(titles().contains(ConnectionNavigatorMenu.Titles.editConnection)) + + #expect(fixture.coordinator.fillConnectionMenu(menu, clicked: connectionNode(fixture.billing.id, in: fixture))) + #expect(titles().first == ConnectionNavigatorMenu.Titles.switchTo) + + #expect(fixture.coordinator.fillConnectionMenu(menu, clicked: connectionNode(fixture.own.id, in: fixture))) + #expect(!titles().contains(ConnectionNavigatorMenu.Titles.switchTo)) + #expect(!titles().contains(ConnectionNavigatorMenu.Titles.connect)) + + let database = try #require(fixture.coordinator.resolvedChildren( + of: try #require(connectionNode(fixture.own.id, in: fixture)) + ).first) + #expect(!fixture.coordinator.fillConnectionMenu(menu, clicked: database), "Other rows keep the tree's own menu") + await tearDown(fixture) + } + + // MARK: - Library and status + + @Test("A connection saved elsewhere appears in the tree") + func libraryChangeRebuildsTheRows() async throws { + let fixture = try await makeFixture() + let added = TestFixtures.makeConnection(name: "Added") + + fixture.library.save([fixture.own, fixture.billing, fixture.local, added]) + fixture.library.events.connectionUpdated.send(nil) + + try await waitUntil { roots(fixture).contains { $0.savedConnectionRef?.id == added.id } } + await tearDown(fixture) + } + + @Test("A status change re-marks a connection's row in place") + func statusChangeReMarksTheRow() async throws { + let fixture = try await makeFixture() + let node = try #require(connectionNode(fixture.local.id, in: fixture)) + + fixture.library.statuses[fixture.local.id] = .connecting + fixture.library.events.connectionPhaseChanged.send(fixture.local.id) + + try await waitUntil { node.savedConnectionRef?.row.status == .connecting } + #expect(connectionNode(fixture.local.id, in: fixture) === node, "The row is the same node, reconfigured") + await tearDown(fixture) + } +} diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift index 8775f70d48..33b86812ef 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeMenuSpecTests.swift @@ -972,17 +972,20 @@ struct DatabaseTreeMenuSpecTests { table: TableInfo(name: "orders", type: .table, rowCount: nil, schema: "public") ) - private static let everyKind: [DatabaseTreeNode.Kind?] = [ - nil, - .table(DatabaseTreeMenuSpecTests.sampleRef), - .recentTable(DatabaseTreeMenuSpecTests.sampleRef), - .schema(database: "app", schema: "billing"), - .database(DatabaseMetadata.minimal(name: "app", isSystem: false)), - .objectKindSection(.table), - .objectKindSection(.type), - .hierarchicalSchemaSection(schema: "billing"), - .status(.loading) - ] + // Computed: a saved connection's kind carries a `DatabaseConnection`, which is not `Sendable`. + private static var everyKind: [DatabaseTreeNode.Kind?] { + [ + nil, + .table(DatabaseTreeMenuSpecTests.sampleRef), + .recentTable(DatabaseTreeMenuSpecTests.sampleRef), + .schema(database: "app", schema: "billing"), + .database(DatabaseMetadata.minimal(name: "app", isSystem: false)), + .objectKindSection(.table), + .objectKindSection(.type), + .hierarchicalSchemaSection(schema: "billing"), + .status(.loading) + ] + } /// The Keys section's error row said what went wrong but left nothing to do about it, since the /// tree only loaded again on a database switch. From 4b07cc9932c30dbb037c6b73ffdfad29325b184b Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:56:34 +0700 Subject: [PATCH 079/123] feat(sidebar): keep the sidebar to one tree while it lists connections While the shown connection's tree lists the saved connections and Tables is selected, the Tables and Favorites switcher stands aside, so the sidebar is the filter field and the tree. Favorites keeps the switcher as the way back, and View > Show Favorites still reaches it. The connections strip yields to that tree too, since the tree already names every connection the window has. A pane with no content draws no tree, so the strip comes back there as before. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ConnectionWindowPaneResolver.swift | 9 +- .../MainSplitViewController.swift | 8 +- .../SidebarContainerViewController.swift | 64 +++++++++- .../ConnectionWindowPaneResolverTests.swift | 29 +++++ ...debarContainerConnectionsInTreeTests.swift | 115 ++++++++++++++++++ 5 files changed, 220 insertions(+), 5 deletions(-) create mode 100644 apple/TableProTests/Core/Services/Infrastructure/SidebarContainerConnectionsInTreeTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift index 786e01ff21..1387260cda 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionWindowPaneResolver.swift @@ -118,14 +118,19 @@ internal enum ConnectionWindowPaneResolver { /// with no renderable session behind it, so `empty` cannot be asked which of those it is. /// Laying a switcher over a window that is going away and stranding a window that is not are /// the same mistake read from the same value. + /// + /// A tree that lists the saved connections already names every connection the window has, so + /// the preference yields to it and the sidebar stays one tree. A pane with no content draws no + /// tree, which brings the strip back as it does for the preference. internal static func showsWorkspaceRail( preferenceEnabled: Bool, workspaceCount: Int, pane: ConnectionWindowPane, - isClosing: Bool + isClosing: Bool, + treeListsConnections: Bool = false ) -> Bool { guard workspaceCount > 1, !isClosing else { return false } - return preferenceEnabled || !pane.hasContent + return (preferenceEnabled && !treeListsConnections) || !pane.hasContent } /// Whether the column stands when it holds the navigator instead of the strip. diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index 13f48d5296..3f76a9527f 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -326,6 +326,11 @@ internal final class MainSplitViewController: NSSplitViewController { navigationSidebar.objectBrowser.onScopeSelection = { [weak self] tab in self?.setSidebarTab(tab) } + /// The layout and the setting move without the pane moving, so the strip is settled again + /// whenever the tree starts or stops listing the connections. + navigationSidebar.objectBrowser.onTreeListsConnectionsChange = { [weak self] in + self?.applyPaneChrome() + } sidebarSplitItem = NSSplitViewItem(sidebarWithViewController: navigationSidebar) sidebarSplitItem.canCollapse = true sidebarSplitItem.minimumThickness = Self.resolveSidebarMinimumThickness(railAllowance: 0) @@ -1241,7 +1246,8 @@ internal final class MainSplitViewController: NSSplitViewController { preferenceEnabled: general.showWorkspaceRail, workspaceCount: workspaceCount, pane: currentPane, - isClosing: phase == .closing + isClosing: phase == .closing, + treeListsConnections: navigationSidebar?.objectBrowser.treeListsConnections ?? false ) ) applyChromeStandingOnRail() diff --git a/apple/TablePro/Core/Services/Infrastructure/SidebarContainerViewController.swift b/apple/TablePro/Core/Services/Infrastructure/SidebarContainerViewController.swift index ae3c2dce75..c040fec6e1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/SidebarContainerViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/SidebarContainerViewController.swift @@ -31,7 +31,16 @@ internal final class SidebarContainerViewController: NSViewController { /// alone would leave the list standing under their height. private var listBelowChrome: NSLayoutConstraint? private var listAtTop: NSLayoutConstraint? + /// Exactly one of these is active, for the reason the two above are. + private var filterBelowScope: NSLayoutConstraint? + private var filterAtTop: NSLayoutConstraint? private var chromeHidden = false + private var settingsObservation: AnyCancellable? + private var reportedTreeListsConnections = false + + /// Whether the shown connection's tree lists the saved connections moved: the window keeps its + /// connections strip away while it does. + internal var onTreeListsConnectionsChange: (() -> Void)? /// A list the user picked, reported to the window, which owns the sidebar and whether it is /// open. @@ -60,6 +69,29 @@ internal final class SidebarContainerViewController: NSViewController { chromeHidden } + internal var isScopeHidden: Bool { + scopeControl.isHidden + } + + /// Whether the connection on screen draws the saved connections in its tree, whichever list the + /// switcher has selected. + internal var treeListsConnections: Bool { + guard let sidebarState, + let type = DatabaseManager.shared.session(for: sidebarState.connectionId)?.connection.type + else { return false } + return DatabaseTreeConnectionRows.applies( + settingEnabled: AppSettingsManager.shared.general.showsConnectionsInTree, + databaseType: type, + layout: sidebarState.sidebarLayout + ) + } + + /// The tree is then the whole sidebar under the filter. Favorites keeps the switcher, which is + /// the way back to Tables, and View > Show Favorites still reaches Favorites from Tables. + private var hidesScopeForTree: Bool { + treeListsConnections && sidebarState?.selectedSidebarTab == .tables + } + /// Agent mode puts its session rail where the object list goes, and neither row above it has /// anything there to act on: the scope would switch a list that is not drawn, and the field /// would filter one. Both go, and the rail takes their height. @@ -73,8 +105,17 @@ internal final class SidebarContainerViewController: NSViewController { /// one the view comes up in. private func applyChromeVisibility() { guard isViewLoaded else { return } - scopeControl.isHidden = chromeHidden + let hidesScope = chromeHidden || hidesScopeForTree + scopeControl.isHidden = hidesScope filterRow.isHidden = chromeHidden + if hidesScope { + filterBelowScope?.isActive = false + filterAtTop?.isActive = true + } else { + filterAtTop?.isActive = false + filterBelowScope?.isActive = true + } + reportTreeListsConnections() if chromeHidden { listBelowChrome?.isActive = false listAtTop?.isActive = true @@ -160,10 +201,13 @@ internal final class SidebarContainerViewController: NSViewController { let listBelowChrome = hostingView.topAnchor.constraint(equalTo: filterRow.bottomAnchor, constant: 5) self.listBelowChrome = listBelowChrome listAtTop = hostingView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) + let filterBelowScope = filterRow.topAnchor.constraint(equalTo: scopeControl.bottomAnchor, constant: 6) + self.filterBelowScope = filterBelowScope + filterAtTop = filterRow.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 5) NSLayoutConstraint.activate(insets + [ scopeControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 5), - filterRow.topAnchor.constraint(equalTo: scopeControl.bottomAnchor, constant: 6), + filterBelowScope, listBelowChrome, hostingView.leadingAnchor.constraint(equalTo: view.leadingAnchor), @@ -171,6 +215,18 @@ internal final class SidebarContainerViewController: NSViewController { hostingView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) applyChromeVisibility() + /// The setting is the app's, not the connection's, so it is watched here rather than through + /// the sidebar state. + settingsObservation = AppSettingsManager.shared.onMainActorChange { [weak self] in + self?.applyChromeVisibility() + } + } + + private func reportTreeListsConnections() { + let lists = treeListsConnections + guard lists != reportedTreeListsConnections else { return } + reportedTreeListsConnections = lists + onTreeListsConnectionsChange?() } /// Asked of the field's ancestors too, because Agent mode hides the row it sits in rather @@ -251,6 +307,7 @@ internal final class SidebarContainerViewController: NSViewController { viewOptionsButton.isHidden = true scopeControl.isEnabled = false scopeControl.selectedTab = nil + applyChromeVisibility() return } searchField.isEnabled = true @@ -262,6 +319,7 @@ internal final class SidebarContainerViewController: NSViewController { viewOptionsButton.isHidden = state.selectedSidebarTab != .tables scopeControl.selectedTab = state.selectedSidebarTab focusScope = state.selectedSidebarTab + applyChromeVisibility() observationTask = Task { @MainActor [weak self] in guard let self else { return } while !Task.isCancelled { @@ -295,6 +353,8 @@ internal final class SidebarContainerViewController: NSViewController { /// Favorites, which write the same state the scope control does, move the control with them. private func syncFromState(_ state: SharedSidebarState) { scopeControl.selectedTab = state.selectedSidebarTab + // The tab and the layout both decide whether the switcher stands aside for the tree. + applyChromeVisibility() let activeText: String let placeholder: String switch state.selectedSidebarTab { diff --git a/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift index 7afde59950..1c85d9dc93 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowPaneResolverTests.swift @@ -134,6 +134,35 @@ struct ConnectionWindowPaneResolverTests { } } + // MARK: - Connections in the tree + + /// The tree names every connection the window has, so a strip beside it would put the window + /// back at two lists of the same connections. + @Test("A tree listing the saved connections keeps the strip away while the pane has content") + func treeListingConnectionsKeepsTheStripAway() { + #expect(!ConnectionWindowPaneResolver.showsWorkspaceRail( + preferenceEnabled: true, + workspaceCount: 2, + pane: .content, + isClosing: false, + treeListsConnections: true + )) + } + + /// A pane with no content draws no tree, and the strip is then the window's way to the others. + @Test("A pane with no content brings the strip back even when the tree lists connections") + func emptyPaneBringsTheStripBackOverTheTree() { + for pane in Self.everyPane where !pane.hasContent { + #expect(ConnectionWindowPaneResolver.showsWorkspaceRail( + preferenceEnabled: true, + workspaceCount: 2, + pane: pane, + isClosing: false, + treeListsConnections: true + )) + } + } + // MARK: - Navigator /// The navigator lists saved connections, not open ones, so a window with one connection still diff --git a/apple/TableProTests/Core/Services/Infrastructure/SidebarContainerConnectionsInTreeTests.swift b/apple/TableProTests/Core/Services/Infrastructure/SidebarContainerConnectionsInTreeTests.swift new file mode 100644 index 0000000000..354626777b --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/SidebarContainerConnectionsInTreeTests.swift @@ -0,0 +1,115 @@ +// +// SidebarContainerConnectionsInTreeTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import Testing + +extension GlobalStateSuites { + /// With the saved connections in the tree, the sidebar is the filter field and the tree: the + /// Tables and Favorites switcher stands aside while Tables shows, and comes back with Favorites + /// so the user has the way back. + @MainActor + struct SidebarContainerConnectionsInTreeTests { + @MainActor + private struct Host { + let controller = SidebarContainerViewController() + let connection: DatabaseConnection + let state: SharedSidebarState + + init(type: DatabaseType = .mysql, layout: SidebarLayout = .tree, tab: SidebarTab = .tables) { + connection = TestFixtures.makeConnection(name: "Shop", type: type) + DatabaseManager.shared.injectSession(ConnectionSession(connection: connection), for: connection.id) + state = SharedSidebarState.forConnection(connection.id) + state.sidebarLayout = layout + state.selectedSidebarTab = tab + controller.loadView() + controller.updateSidebarState(state) + } + + func tearDown() { + controller.updateSidebarState(nil) + DatabaseManager.shared.removeSession(for: connection.id) + SharedSidebarState.removeConnection(connection.id) + SidebarPersistenceKey.removeAll(connectionId: connection.id) + } + } + + @Test( + "Tables in a tree that lists the connections hides the switcher, and Favorites brings it back", + .appSettings { $0.general.showsConnectionsInTree = true } + ) + func switcherStandsAsideForTheTree() async throws { + let host = Host() + defer { host.tearDown() } + + #expect(host.controller.treeListsConnections) + #expect(host.controller.isScopeHidden) + + host.state.selectedSidebarTab = .favorites + + try await waitUntil { !host.controller.isScopeHidden } + #expect(host.controller.treeListsConnections, "The tree still lists them, so the strip still stands aside") + } + + @Test("With the setting off the switcher stands", .appSettings { $0.general.showsConnectionsInTree = false }) + func settingOffKeepsTheSwitcher() { + let host = Host() + defer { host.tearDown() } + + #expect(!host.controller.treeListsConnections) + #expect(!host.controller.isScopeHidden) + } + + @Test( + "The list layout and an engine with no database tree keep the switcher", + .appSettings { $0.general.showsConnectionsInTree = true } + ) + func onlyTheDatabaseTreeHidesTheSwitcher() { + let list = Host(layout: .flat) + let file = Host(type: .sqlite) + defer { + list.tearDown() + file.tearDown() + } + + #expect(!list.controller.isScopeHidden) + #expect(!file.controller.isScopeHidden) + } + + @Test( + "Switching the layout to Tree tells the window, which keeps the strip away", + .appSettings { $0.general.showsConnectionsInTree = true } + ) + func layoutChangeIsReported() async throws { + let host = Host(layout: .flat) + defer { host.tearDown() } + var reports = 0 + host.controller.onTreeListsConnectionsChange = { reports += 1 } + + host.state.sidebarLayout = .tree + + try await waitUntil { reports == 1 } + #expect(host.controller.isScopeHidden) + } + + @Test( + "Turning the setting off brings the switcher back", + .appSettings { $0.general.showsConnectionsInTree = true } + ) + func settingChangeIsApplied() async throws { + let host = Host() + defer { host.tearDown() } + #expect(host.controller.isScopeHidden) + + AppSettingsManager.shared.general.showsConnectionsInTree = false + + try await waitUntil { !host.controller.isScopeHidden } + } + } +} From a4179cd5f35c9e3d383c3a2e18cf80744662f067 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 14:56:40 +0700 Subject: [PATCH 080/123] docs(rules): note the tree's connection groups share the navigator's expansion Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index 110d295bd8..0611f9c5b8 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -168,7 +168,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Team library, per team: pull cursor, items, unpushed edits, conflicts (synced with tablepro-cloud's `/v2`, never iCloud) | JSON, one file per team | `TeamLibraryStateStore` through `TeamLibrarySync` | | Sidebar database and schema filters, recent tables | UserDefaults, device-local | `DatabaseTreeFilterStorage`, `RecentTablesStore` | | Objects tab column choices, per object kind | UserDefaults `com.TablePro.objectsList.columns.`, device-local, never synced | `ObjectListingColumnVisibilityStore` | -| Connection navigator group expansion | UserDefaults `com.TablePro.navigator.groupExpansion`, device-local, never synced | `ConnectionNavigatorExpansionStore` | +| Connection navigator group expansion, shared with the database tree's connection groups | UserDefaults `com.TablePro.navigator.groupExpansion`, device-local, never synced | `ConnectionNavigatorExpansionStore` | | Connection navigator column width | AppKit split view autosave `com.TablePro.connectionNavigator`, device-local | `NavigationSidebarViewController` through `SplitViewAutosaveName.current(_:)` | | History drawer state | UserDefaults, device-local | `HistoryPanelPreferencesStorage` | | Server Dashboard tiles, per connection | UserDefaults, device-local | `ServerDashboardTileStorage` | From 43f98848de45ef06525554070c5f418798ba8a7c Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 15:11:36 +0700 Subject: [PATCH 081/123] chore(l10n): add the connections-in-tree, Objects list and toolbar strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Resources/Localizable.xcstrings | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index f9c312f246..5bc3032ede 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -56487,6 +56487,9 @@ } } } + }, + "Created Date" : { + }, "Created the database %@." : { "localizations" : { @@ -58455,6 +58458,9 @@ "Data Grid Text" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Data Length" : { + }, "Data loss" : { "localizations" : { @@ -93245,6 +93251,9 @@ } } } + }, + "In the Tree layout, lists every saved connection in its groups at the top of the sidebar, with the connection on screen opened to its databases. Double-click another one to open it." : { + }, "In-memory data store and cache" : { "localizations" : { @@ -111172,6 +111181,9 @@ } } } + }, + "Modified Date" : { + }, "Modified:" : { "extractionState" : "stale", @@ -113735,6 +113747,9 @@ }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { @@ -166870,6 +166885,9 @@ }, "Show rows in %@" : { + }, + "Show saved connections in the database tree" : { + }, "Show Sidebar" : { "localizations" : { From e72c5414d32e424e073ca349d9b69479425e6943 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 15:28:32 +0700 Subject: [PATCH 082/123] feat(toolbar): give the connection room once the toolbar shows labels With labels the window title stops drawing, the Objects buttons give way to the overflow menu before the connection and the commands, and a space parts the four kinds from Query and Backup. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Items.swift | 16 +++++- .../Infrastructure/MainWindowToolbar.swift | 37 ++++++++++++- .../ObjectKindsToolbarTests.swift | 54 +++++++++++++++++-- .../Infrastructure/ToolbarLabelsTests.swift | 6 +++ .../MainWindowToolbarIdentifierTests.swift | 1 + 5 files changed, 107 insertions(+), 7 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift index 7aa3d7cee1..2f32569dde 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift @@ -533,7 +533,21 @@ extension MainWindowToolbar { /// menu. A truncated container name is a worse loss than Refresh and Save. func applyVisibilityPriority(to item: NSToolbarItem) { guard item.itemIdentifier != Self.connection, item.itemIdentifier != Self.database else { return } - item.visibilityPriority = .high + item.visibilityPriority = Self.visibilityPriority(for: item.itemIdentifier) + } + + /// The Objects buttons are the widest items once labels show, and each one reaches something the sidebar + /// or a menu also reaches, so they give way first: Query and Backup, which repeat New Tab and Backup, then the + /// four kinds, which give way before the connection and its container. + nonisolated static func visibilityPriority(for identifier: NSToolbarItem.Identifier) -> NSToolbarItem.VisibilityPriority { + switch identifier { + case objectQuery, objectBackup: + return .low + case objectTables, objectViews, objectFunctions, objectUsers: + return NSToolbarItem.VisibilityPriority(rawValue: NSToolbarItem.VisibilityPriority.low.rawValue / 2) + default: + return .high + } } } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index f43fcf5aaf..dbcfb7c6df 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -535,7 +535,12 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { /// Every identifier here must be one the delegate can build. Asked for one it cannot, the /// delegate answers nil, and with `autosavesConfiguration` on AppKit prunes it from the saved /// arrangement. + /// + /// `.space` is here for the Objects buttons, which are inserted with one: toolbars sharing the identifier replay + /// each other's edits by index, and one that refused the space would hold an item fewer and fault on the next + /// removal. nonisolated internal static let allowedItemIdentifiers: [NSToolbarItem.Identifier] = defaultItemIdentifiers + [ + .space, backForwardGroup, previewSQL, results, @@ -607,6 +612,19 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } } + // Only the space that sits where the Objects buttons put it, so a space the user placed elsewhere stays. + nonisolated internal static func isObjectKindsSpace(at index: Int, in items: [NSToolbarItem.Identifier]) -> Bool { + items[index] == .space && index > 0 && index + 1 < items.count + && items[index - 1] == objectUsers && items[index + 1] == objectQuery + } + + /// With labels the titlebar has no room for the window title as well. It names the front tab, which the + /// tab strip and the selected Objects button already show, and it pushed the connection and its container + /// into the overflow menu. The title stays set for the Window menu and VoiceOver; it only stops drawing. + nonisolated internal static func titleVisibility(showsLabels: Bool) -> NSWindow.TitleVisibility { + showsLabels ? .hidden : .visible + } + nonisolated internal static func displayMode(showsLabels: Bool) -> NSToolbar.DisplayMode { showsLabels ? .iconAndLabel : .iconOnly } @@ -618,6 +636,13 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal func reconcileDisplayMode() { guard windowController?.view.window != nil || isInWindow() else { return } let wanted = labelsEnabled() + // Follows the setting every time, unlike the mode, which the user can still pick from the toolbar's menu. + if let window = windowController?.view.window { + let visibility = Self.titleVisibility(showsLabels: wanted) + if window.titleVisibility != visibility { + window.titleVisibility = visibility + } + } guard labelsRecord.isApplied != wanted else { return } labelsRecord.record(wanted) managedToolbar.displayMode = Self.displayMode(showsLabels: wanted) @@ -661,12 +686,20 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { let separator = managedToolbar.items.firstIndex { $0.itemIdentifier == .sidebarTrackingSeparator } var index = separator.map { $0 + 1 } ?? 0 for identifier in Self.objectKindItemIdentifiers where !present.contains(identifier) { + // Tables, Views, Functions and Users pick what the tab shows; Query and Backup start something. + // A space keeps the two runs apart, so the actions do not read as two more kinds. + if identifier == Self.objectQuery, index > 0, + managedToolbar.items[index - 1].itemIdentifier == Self.objectUsers { + managedToolbar.insertItem(withItemIdentifier: .space, at: index) + index += 1 + } managedToolbar.insertItem(withItemIdentifier: identifier, at: index) index += 1 } } else { - for index in managedToolbar.items.indices.reversed() - where objectKinds.contains(managedToolbar.items[index].itemIdentifier) { + let items = managedToolbar.items.map(\.itemIdentifier) + for index in items.indices.reversed() + where objectKinds.contains(items[index]) || Self.isObjectKindsSpace(at: index, in: items) { managedToolbar.removeItem(at: index) } } diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index 4964448504..038c7fdb6f 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -73,7 +73,10 @@ struct ObjectKindsToolbarTests { #expect(item.image != nil, "\(name) names no symbol that exists") #expect(item.target === owner, "\(name) must route through the toolbar") #expect(item.action != nil, "\(name) has no action") - #expect(item.visibilityPriority == .high, "\(name) leaves the titlebar before the commands") + #expect( + item.visibilityPriority == MainWindowToolbar.visibilityPriority(for: item.itemIdentifier), + "\(name) leaves the titlebar before the commands" + ) #expect(!item.isBordered, "\(name) must match the selectable buttons, which AppKit draws without a bezel") } } @@ -549,6 +552,12 @@ struct ObjectKindsToolbarTests { return (owner, toolbar) } + // The six buttons as a change of the setting inserts them, with the space that parts the kinds from the actions. + static let insertedRun: [NSToolbarItem.Identifier] = [ + MainWindowToolbar.objectTables, MainWindowToolbar.objectViews, MainWindowToolbar.objectFunctions, + MainWindowToolbar.objectUsers, .space, MainWindowToolbar.objectQuery, MainWindowToolbar.objectBackup, + ] + private static func identifiers(of toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { toolbar.items.map { $0.itemIdentifier } } @@ -569,6 +578,10 @@ struct ObjectKindsToolbarTests { #expect(Self.buttons(in: toolbar) == MainWindowToolbar.objectKindItemIdentifiers) #expect(ToolbarObjectKindsRecord(defaults: storage.defaults).isApplied) + let placed = Self.identifiers(of: toolbar) + let query = try #require(placed.firstIndex(of: MainWindowToolbar.objectQuery)) + #expect(placed[query - 1] == .space, "A space parts the four kinds from Query and Backup") + #expect(placed[query - 2] == MainWindowToolbar.objectUsers) let (laterOwner, laterToolbar) = Self.restoredToolbar(settingOn: true, record: record) laterOwner.reconcileObjectKindItems() @@ -608,6 +621,39 @@ struct ObjectKindsToolbarTests { #expect(!record.isApplied) } + @Test("Turning the setting off takes out the space the buttons came with, and only that one") + func turningOffRemovesOnlyTheButtonsSpace() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + record.record(true) + let (owner, toolbar) = Self.restoredToolbar( + including: [.space, MainWindowToolbar.objectTables, MainWindowToolbar.objectViews, + MainWindowToolbar.objectFunctions, MainWindowToolbar.objectUsers, .space, + MainWindowToolbar.objectQuery, MainWindowToolbar.objectBackup], + settingOn: false, + record: record + ) + + owner.reconcileObjectKindItems() + + #expect(Self.buttons(in: toolbar).isEmpty) + #expect(Self.identifiers(of: toolbar).filter { $0 == .space }.count == 1, "The user's own space stays") + } + + @Test("Query and Backup give way first, then the four kinds, before the connection and the commands") + func objectButtonsGiveWayFirst() { + func priority(_ identifier: NSToolbarItem.Identifier) -> Int { + MainWindowToolbar.visibilityPriority(for: identifier).rawValue + } + #expect(priority(MainWindowToolbar.objectQuery) == NSToolbarItem.VisibilityPriority.low.rawValue) + #expect(priority(MainWindowToolbar.objectBackup) == NSToolbarItem.VisibilityPriority.low.rawValue) + for kind in MainWindowToolbar.selectableObjectKindItemIdentifiers { + #expect(priority(kind) > priority(MainWindowToolbar.objectQuery)) + #expect(priority(kind) < NSToolbarItem.VisibilityPriority.standard.rawValue, "The connection stays longer") + } + #expect(priority(MainWindowToolbar.refresh) == NSToolbarItem.VisibilityPriority.high.rawValue) + } + @Test("Buttons the user took out with Customize Toolbar stay out") func removedButtonsStayRemoved() throws { let storage = try EphemeralDefaults() @@ -674,7 +720,7 @@ struct ObjectKindsToolbarTests { let identifiers = Self.identifiers(of: owner.managedToolbar) let separator = try #require(identifiers.firstIndex(of: .sidebarTrackingSeparator)) - #expect(Array(identifiers.dropFirst(separator + 1).prefix(6)) == MainWindowToolbar.objectKindItemIdentifiers) + #expect(Array(identifiers.dropFirst(separator + 1).prefix(7)) == Self.insertedRun) #expect(Self.buttons(in: owner.managedToolbar) == MainWindowToolbar.objectKindItemIdentifiers) } @@ -727,7 +773,7 @@ struct ObjectKindsToolbarTests { owner.reconcileObjectKindItems() - #expect(Array(Self.identifiers(of: toolbar).prefix(6)) == MainWindowToolbar.objectKindItemIdentifiers) + #expect(Array(Self.identifiers(of: toolbar).prefix(7)) == Self.insertedRun) } /// The pass a window update runs is what keeps the selection on the front tab's kind. @@ -799,7 +845,7 @@ extension GlobalStateSuites { #expect(buttons().count == objectKinds.count, "Turning the setting on reaches the open window") let identifiers = toolbar.items.map { $0.itemIdentifier } let separator = try #require(identifiers.firstIndex(of: .sidebarTrackingSeparator)) - #expect(Array(identifiers.dropFirst(separator + 1).prefix(6)) == MainWindowToolbar.objectKindItemIdentifiers) + #expect(Array(identifiers.dropFirst(separator + 1).prefix(7)) == ObjectKindsToolbarTests.insertedRun) // This window has no connection, so the buttons arrive dimmed rather than live until the next update. for button in buttons() { #expect(!button.isEnabled, "\(button.itemIdentifier.rawValue) is live with no connection") diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift index 87ea348e3c..44e7e5d13f 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift @@ -109,6 +109,12 @@ struct ToolbarLabelsTests { #expect(record.isApplied) } + @Test("With labels the window title stops drawing, and without them it draws again") + func labelsHideTheTitle() { + #expect(MainWindowToolbar.titleVisibility(showsLabels: true) == .hidden) + #expect(MainWindowToolbar.titleVisibility(showsLabels: false) == .visible) + } + @Test("The record sits beside the toolbar's arrangement, which keeps its v4 identifier") func recordKeyFollowsTheArrangement() { #expect(ToolbarLabelsRecord.key == "com.TablePro.main.toolbar.v4.labels") diff --git a/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift b/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift index 1515a06687..f235d678ba 100644 --- a/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift +++ b/apple/TableProTests/Views/Toolbar/MainWindowToolbarIdentifierTests.swift @@ -109,6 +109,7 @@ struct MainWindowToolbarIdentifierTests { } let allowed = owner.toolbarAllowedItemIdentifiers(owner.managedToolbar) #expect(Array(allowed.suffix(objectKinds.count)) == objectKinds) + #expect(MainWindowToolbar.allowedItemIdentifiers.contains(.space), "The space the buttons come with") #expect(owner.toolbarDefaultItemIdentifiers(owner.managedToolbar) == defaultsWhileOff) #expect(Set(defaultsWhileOff).isDisjoint(with: objectKinds)) #expect(MainWindowToolbar.toolbarIdentifier == "com.TablePro.main.toolbar.v4") From 4f3d9e623bd355161bf3666e22eb3896356d027c Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 17:10:24 +0700 Subject: [PATCH 083/123] feat(grid): show column types under the column names Add the Data Grid setting "Show column types in the header", off by default. With it on, a data tab's header grows by one line: the column name stays as it was, and under it the engine's type (varchar(255), bigint(20)) in the secondary label color, led by a glyph for its category: text, number, date and time, boolean, binary, document, spatial or other. A column with no type leaves the line empty. Both panes' headers change height together and the first visible row stays in place. Automatic widths are measured again with the type line, and widths the user set stay. The tooltip is unchanged; VoiceOver reads the type while the line shows. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-grid.md | 1 + apple/TablePro/Core/Services/ColumnType.swift | 4 +- .../Core/Services/ColumnTypeCategory.swift | 49 +++ .../Models/Settings/AppSettings.swift | 11 +- .../Models/UI/DataGridConfiguration.swift | 3 + apple/TablePro/Theme/ThemeTableHeader.swift | 25 +- .../Cells/DataGridColumnWidthCalculator.swift | 4 + .../DataGrid/DataGridHeaderTypeLine.swift | 118 +++++++ .../Views/DataGrid/DataGridHeaderView.swift | 48 ++- .../DataGridViewController+Columns.swift | 3 +- .../DataGridViewController+Header.swift | 40 ++- .../DataGrid/DataGridViewController.swift | 1 + .../MainContentCoordinator+GridModels.swift | 1 + .../Settings/Sections/DataGridSection.swift | 1 + .../Services/ColumnTypeCategoryTests.swift | 213 ++++++++++++ .../Settings/SettingsFieldDecodingTests.swift | 17 + .../DataGridHeaderTypeLineTests.swift | 306 ++++++++++++++++++ .../Main/DataTabColumnTypesSettingTests.swift | 36 +++ 18 files changed, 869 insertions(+), 12 deletions(-) create mode 100644 apple/TablePro/Core/Services/ColumnTypeCategory.swift create mode 100644 apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift create mode 100644 apple/TableProTests/Core/Services/ColumnTypeCategoryTests.swift create mode 100644 apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift create mode 100644 apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift diff --git a/.claude/rules/data-grid.md b/.claude/rules/data-grid.md index e86d304b26..7debabba59 100644 --- a/.claude/rules/data-grid.md +++ b/.claude/rules/data-grid.md @@ -52,6 +52,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode - **AppKit's header behavior in the theme's colors.** `DataGridHeaderView` is a `ThemeTableHeaderView` and every column a `ThemeTableHeaderCell` (`.claude/rules/theme.md`); it adds `menu(for:)` and a `viewWillDraw` that repaints the body on each step of a column drag. AppKit draws the title and the primary sort arrow; the controller sets each header cell's `accessibilitySortDirection`, which AppKit leaves unknown. - **The model's sort is the source.** `tableView.sortDescriptors` is written from `store.sortState` under `isApplyingSortDescriptors`, because an assignment inside the callback fires it again. A plain click keeps only the clicked key and flips it on a repeat; an Option-click keeps the key AppKit appended (`HeaderSortCycle`). Shift-click reaches no sort callback, and Command-click selects the column. - **Header text is the column name.** The type, the comment and, while several keys sort, the sort order go in `headerToolTip`; an active value filter adds a funnel symbol attachment to the title, in the header text color. +- **`configuration.showsColumnTypes` adds a type line under every title**, in both panes' headers at once (the data tabs follow the Data Grid setting). The cell holds no object references, since AppKit copies it, so `DataGridHeaderView` lays the line out through `ThemeTableHeaderView`'s `contentRect(forCellFrame:)` and `drawBelowTitle`, and reads the type from the model at draw time. Turning it on or off measures automatic widths again; a width the user set stays. ## Keyboard, mouse and menus diff --git a/apple/TablePro/Core/Services/ColumnType.swift b/apple/TablePro/Core/Services/ColumnType.swift index 63145b21f9..f743ceb614 100644 --- a/apple/TablePro/Core/Services/ColumnType.swift +++ b/apple/TablePro/Core/Services/ColumnType.swift @@ -120,7 +120,7 @@ enum ColumnType: Equatable, Sendable { } /// Whether this type is a very large text type that should be excluded from browse queries. - /// Only MEDIUMTEXT (16MB), LONGTEXT (4GB), and CLOB — not plain TEXT (65KB) or TINYTEXT (255B). + /// Only MEDIUMTEXT (16MB), LONGTEXT (4GB) and CLOB, not plain TEXT (65KB) or TINYTEXT (255B). var isVeryLongText: Bool { guard let raw = rawType?.uppercased() else { return false } return raw == "MEDIUMTEXT" || raw == "LONGTEXT" || raw == "CLOB" @@ -206,7 +206,7 @@ enum ColumnType: Equatable, Sendable { private static let uuidTypeNames: Set = ["UUID", "UNIQUEIDENTIFIER", "TIMEUUID"] /// `Nullable(UUID)`, `year(4)` and `INTERVAL DAY TO SECOND` all name their type in the first word. - private static func baseTypeName(_ rawType: String?) -> String { + static func baseTypeName(_ rawType: String?) -> String { guard var name = rawType?.uppercased() else { return "" } while let wrapper = ["NULLABLE(", "LOWCARDINALITY("].first(where: { name.hasPrefix($0) }) { name.removeFirst(wrapper.count) diff --git a/apple/TablePro/Core/Services/ColumnTypeCategory.swift b/apple/TablePro/Core/Services/ColumnTypeCategory.swift new file mode 100644 index 0000000000..bb1bad5cf4 --- /dev/null +++ b/apple/TablePro/Core/Services/ColumnTypeCategory.swift @@ -0,0 +1,49 @@ +// +// ColumnTypeCategory.swift +// TablePro +// + +import Foundation + +/// The broad kind of value a column holds, read from its `ColumnType`, so every engine's spelling of a +/// type lands in the same few groups. +enum ColumnTypeCategory: CaseIterable, Sendable { + case text + case number + case dateTime + case boolean + case binary + case document + case spatial + case other + + init(_ type: ColumnType) { + switch type { + case .text(let rawType): + self = Self.nonTextCategories[ColumnType.baseTypeName(rawType)] ?? .text + case .integer, .decimal: + self = .number + case .date, .timestamp, .datetime: + self = .dateTime + case .boolean: + self = .boolean + case .blob: + self = .binary + // An array holds structured values like a JSON document, and PostgreSQL prints it in braces. + case .json, .array: + self = .document + case .spatial: + self = .spatial + case .enumType, .set, .vector: + self = .other + } + } + + /// Types the classifier files under text, since the grid edits them as text, whose values are not free text. + private static let nonTextCategories: [String: ColumnTypeCategory] = [ + "YEAR": .dateTime, + "INTERVAL": .dateTime, + "XML": .document, + "HSTORE": .document, + ] +} diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index a18e4aeb1b..45925a09c8 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -126,6 +126,7 @@ struct DataGridSettings: Codable, Equatable { var defaultSortDirection: SortDirection var rowCopyFormat: RowCopyFormat var showInvisibleCharacters: Bool + var showsColumnTypesInHeader: Bool static let `default` = DataGridSettings( rowHeight: .normal, @@ -142,7 +143,8 @@ struct DataGridSettings: Codable, Equatable { defaultSortBehavior: .none, defaultSortDirection: .ascending, rowCopyFormat: .rows, - showInvisibleCharacters: true + showInvisibleCharacters: true, + showsColumnTypesInHeader: false ) init( @@ -160,7 +162,8 @@ struct DataGridSettings: Codable, Equatable { defaultSortBehavior: DefaultSortBehavior = .none, defaultSortDirection: SortDirection = .ascending, rowCopyFormat: RowCopyFormat = .rows, - showInvisibleCharacters: Bool = true + showInvisibleCharacters: Bool = true, + showsColumnTypesInHeader: Bool = false ) { self.rowHeight = rowHeight self.dateFormat = dateFormat @@ -177,6 +180,7 @@ struct DataGridSettings: Codable, Equatable { self.defaultSortDirection = defaultSortDirection self.rowCopyFormat = rowCopyFormat self.showInvisibleCharacters = showInvisibleCharacters + self.showsColumnTypesInHeader = showsColumnTypesInHeader } init(from decoder: Decoder) throws { @@ -204,6 +208,9 @@ struct DataGridSettings: Codable, Equatable { showInvisibleCharacters = container.decodeSetting( .showInvisibleCharacters, default: fallback.showInvisibleCharacters ) + showsColumnTypesInHeader = container.decodeSetting( + .showsColumnTypesInHeader, default: fallback.showsColumnTypesInHeader + ) } // MARK: - Validated Properties diff --git a/apple/TablePro/Models/UI/DataGridConfiguration.swift b/apple/TablePro/Models/UI/DataGridConfiguration.swift index 3f05e7c2b8..f00b5ddff8 100644 --- a/apple/TablePro/Models/UI/DataGridConfiguration.swift +++ b/apple/TablePro/Models/UI/DataGridConfiguration.swift @@ -13,6 +13,9 @@ struct DataGridConfiguration: Equatable { var primaryKeyColumns: [String] = [] var showRowNumbers: Bool = true + // A second header line under each column name with the column's type; the data tabs follow the Data Grid setting. + var showsColumnTypes = false + // Keyed by index: the column is the grid's own and has no name a table column could share. var checkboxColumns: Set = [] diff --git a/apple/TablePro/Theme/ThemeTableHeader.swift b/apple/TablePro/Theme/ThemeTableHeader.swift index de96571768..787c50e069 100644 --- a/apple/TablePro/Theme/ThemeTableHeader.swift +++ b/apple/TablePro/Theme/ThemeTableHeader.swift @@ -10,6 +10,14 @@ class ThemeTableHeaderView: NSTableHeaderView { // On macOS 26 the header sits in the scroll pocket's vibrant banner, which would blend the band lighter (measured). override var allowsVibrancy: Bool { false } + // The cell holds no object references (AppKit copies it), so a header with a line under the titles lays it out here. + func contentRect(forCellFrame cellFrame: NSRect) -> NSRect { + ThemeTableHeaderCell.interiorRect(in: cellFrame) + } + + // Called after AppKit drew the title, with the part of the content below the title's band. + func drawBelowTitle(of cell: ThemeTableHeaderCell, in rect: NSRect, cellFrame: NSRect) {} + // AppKit bolds the highlighted column's title only in the highlight pass the themed band replaces. override func viewWillDraw() { super.viewWillDraw() @@ -31,17 +39,23 @@ final class ThemeTableHeaderCell: NSTableHeaderCell { override func draw(withFrame cellFrame: NSRect, in controlView: NSView) { let header = controlView as? NSTableHeaderView - let resolved = ((header as? ThemeTableHeaderView)?.themeScope ?? .live).resolved + let themedHeader = header as? ThemeTableHeaderView + let resolved = (themedHeader?.themeScope ?? .live).resolved resolved[.gridHeaderBackground].setFill() cellFrame.fill() - let interior = Self.interiorRect(in: cellFrame) + let content = themedHeader?.contentRect(forCellFrame: cellFrame) ?? Self.interiorRect(in: cellFrame) + let interior = Self.titleRect(in: content) resolved[.gridLine].setFill() Self.bottomLineRect(in: cellFrame).fill(using: .sourceOver) if let tableView = header?.tableView, !Self.isFiller(cellFrame, of: tableView) { - Self.dividerRect(in: cellFrame, interior: interior).fill(using: .sourceOver) + Self.dividerRect(in: cellFrame, interior: content).fill(using: .sourceOver) } drawInterior(withFrame: interior, in: controlView) + if content.maxY > interior.maxY { + let below = NSRect(x: content.minX, y: interior.maxY, width: content.width, height: content.maxY - interior.maxY) + themedHeader?.drawBelowTitle(of: self, in: below, cellFrame: cellFrame) + } } // AppKit's highlight pass draws its own band; the highlighted title is bold instead (`ThemeTableHeaderView`). @@ -71,6 +85,11 @@ final class ThemeTableHeaderCell: NSTableHeaderCell { return NSRect(x: cellFrame.minX, y: cellFrame.midY - height / 2, width: cellFrame.width, height: height) } + // The title and sort arrow keep AppKit's band at the top of the content; a header of one line has no more content. + static func titleRect(in content: NSRect) -> NSRect { + NSRect(x: content.minX, y: content.minY, width: content.width, height: min(interiorHeight, content.height)) + } + static func bottomLineRect(in cellFrame: NSRect) -> NSRect { NSRect(x: cellFrame.minX, y: cellFrame.maxY - lineWidth, width: cellFrame.width, height: lineWidth) } diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift index 88021d9cb7..f3497f99bd 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift @@ -38,6 +38,7 @@ struct DataGridColumnWidthCalculator { let nullDisplayString: String let revealsInvisibleCharacters: Bool let fonts: DataGridFontCache + var showsTypeLine = false static func fitToContentCap(availableWidth: CGFloat) -> CGFloat { let proportional = availableWidth * fitToContentViewportFraction @@ -69,6 +70,9 @@ struct DataGridColumnWidthCalculator { let dataIndex = input.column.dataIndex let headerCharCount = (input.column.name as NSString).length var maxWidth = CGFloat(headerCharCount) * charWidth * Self.headerCharWidthRatio + Self.headerPadding + if showsTypeLine, let typeLine = DataGridHeaderTypeLine(input.column.type) { + maxWidth = max(maxWidth, typeLine.width) + } let totalRows = rows.count let step = max(1, totalRows / max(1, budget.sampledRows)) diff --git a/apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift b/apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift new file mode 100644 index 0000000000..a986560e08 --- /dev/null +++ b/apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift @@ -0,0 +1,118 @@ +// +// DataGridHeaderTypeLine.swift +// TablePro +// + +import AppKit +import TableProTheme + +// The second line of a column heading: the type in the engine's own spelling, led by its category's glyph. +@MainActor +struct DataGridHeaderTypeLine { + let text: String + let category: ColumnTypeCategory + + init?(_ type: ColumnType?) { + guard let type, let text = Self.typeName(of: type) else { return nil } + self.text = text + category = ColumnTypeCategory(type) + } + + // The engine's spelling (`varchar(255)`), else the app's name for the type. + static func typeName(of type: ColumnType?) -> String? { + guard let type else { return nil } + if let raw = type.rawType?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty { + return raw + } + return type.displayName + } + + // MARK: - Metrics + + static let font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize - 1) + static let lineHeight = (font.ascender - font.descender).rounded(.up) + // AppKit starts the title's ink 3 pt into its interior band (measured on macOS 27), so the glyph lines up under it. + static let leadingInset: CGFloat = 3 + static let glyphSpacing: CGFloat = 3 + // Room for the divider and the gap before it. + static let trailingInset: CGFloat = 4 + static let glyphPointSize: CGFloat = 9 + + // The width the line needs inside its cell, insets included. + var width: CGFloat { + let textWidth = (text as NSString).size(withAttributes: [.font: Self.font]).width + let glyphWidth = Self.glyphWidth(category) + let glyphRun = glyphWidth > 0 ? glyphWidth + Self.glyphSpacing : 0 + return (Self.leadingInset + glyphRun + textWidth + Self.trailingInset).rounded(.up) + } + + // The glyph is dropped before the text is when the column is too narrow for both. + func draw(in rect: NSRect, color: NSColor) { + let font = Self.font + let limit = rect.maxX - Self.trailingInset + var x = rect.minX + Self.leadingInset + guard x < limit else { return } + if let glyph = Self.glyph(category, color: color), x + glyph.size.width <= limit { + let size = glyph.size + let capMidY = rect.minY + font.ascender - font.capHeight / 2 + let glyphRect = NSRect(x: x, y: capMidY - size.height / 2, width: size.width, height: size.height) + glyph.draw(in: glyphRect, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil) + x += size.width + Self.glyphSpacing + } + guard x < limit else { return } + let paragraph = NSMutableParagraphStyle() + paragraph.lineBreakMode = .byTruncatingTail + let textRect = NSRect(x: x, y: rect.minY, width: limit - x, height: rect.height) + (text as NSString).draw( + with: textRect, + options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine], + attributes: [.font: font, .foregroundColor: color, .paragraphStyle: paragraph] + ) + } + + // MARK: - Glyph + + private static var glyphWidths: [ColumnTypeCategory: CGFloat] = [:] + + static func glyphWidth(_ category: ColumnTypeCategory) -> CGFloat { + if let width = glyphWidths[category] { return width } + let width = glyph(category, color: nil)?.size.width ?? 0 + glyphWidths[category] = width + return width + } + + // A symbol image keeps the color it was built with, so it takes the line's color here. + static func glyph(_ category: ColumnTypeCategory, color: NSColor?) -> NSImage? { + var configuration = NSImage.SymbolConfiguration(pointSize: glyphPointSize, weight: .regular) + if let color { + configuration = configuration.applying(.init(hierarchicalColor: color)) + } + return NSImage(systemSymbolName: category.symbolName, accessibilityDescription: nil)? + .withSymbolConfiguration(configuration) + } + + // Secondary to the title: the theme's header text faded where a theme sets it, else the system's secondary label. + static func color(in scope: ThemeScope) -> NSColor { + let resolved = scope.resolved + guard resolved.isOverridden(.gridHeaderText) else { return .secondaryLabelColor } + return resolved[.gridHeaderText].withAlphaComponent(secondaryAlpha) + } + + static let secondaryAlpha: CGFloat = 0.6 +} + +extension ColumnTypeCategory { + // SF Symbols that ship with macOS 11, below the deployment target. + var symbolName: String { + switch self { + case .text: return "textformat.abc" + case .number: return "textformat.123" + case .dateTime: return "calendar" + case .boolean: return "checkmark.square" + case .binary: return "doc" + case .document: return "curlybraces" + case .spatial: return "mappin.and.ellipse" + case .other: return "square.on.circle" + } + } +} diff --git a/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift b/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift index 1e0e5c8d5c..d9277ebdff 100644 --- a/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift +++ b/apple/TablePro/Views/DataGrid/DataGridHeaderView.swift @@ -5,11 +5,29 @@ import AppKit -// The menu is resolved from the event, and drawn cells need a repaint on each step of a column drag. +// The menu is resolved from the event, drawn cells need a repaint on each step of a column drag, and a second line can +// show each column's type. @MainActor final class DataGridHeaderView: ThemeTableHeaderView { var paneKind: DataGridPane.Kind = .main private var bodyFollowsColumnDrag = false + private var standardHeight: CGFloat = 0 + + // The type line makes the header one line taller; a column without a type leaves its line empty. + var showsTypeLine = false { + didSet { + guard showsTypeLine != oldValue else { return } + if standardHeight == 0 { + standardHeight = frame.height + } + setFrameSize(NSSize(width: frame.width, height: Self.height(standard: standardHeight, showsTypeLine: showsTypeLine))) + needsDisplay = true + } + } + + static func height(standard: CGFloat, showsTypeLine: Bool) -> CGFloat { + showsTypeLine ? standard + DataGridHeaderTypeLine.lineHeight : standard + } private var controller: DataGridViewController? { (tableView as? DataGridTableView)?.controller @@ -26,6 +44,34 @@ final class DataGridHeaderView: ThemeTableHeaderView { return controller?.headerMenu(forTableColumn: tableView.tableColumns[index], in: paneKind) } + // The title keeps AppKit's band on top and the type line sits under it, the two centered together. + override func contentRect(forCellFrame cellFrame: NSRect) -> NSRect { + guard showsTypeLine else { return super.contentRect(forCellFrame: cellFrame) } + let height = min(ThemeTableHeaderCell.interiorHeight + DataGridHeaderTypeLine.lineHeight, cellFrame.height) + return NSRect(x: cellFrame.minX, y: cellFrame.midY - height / 2, width: cellFrame.width, height: height) + } + + override func drawBelowTitle(of cell: ThemeTableHeaderCell, in rect: NSRect, cellFrame: NSRect) { + guard showsTypeLine, let controller, let tableColumn = tableColumn(drawnBy: cell, in: cellFrame), + let line = controller.headerTypeLine(for: tableColumn, in: paneKind) else { return } + line.draw(in: rect, color: DataGridHeaderTypeLine.color(in: themeScope)) + } + + // AppKit draws past the last column with a copy of a cell, which belongs to no column and gets no type line. + private func tableColumn(drawnBy cell: NSCell, in cellFrame: NSRect) -> NSTableColumn? { + guard let tableView else { return nil } + let columns = tableView.tableColumns + let dragged = draggedColumn + if dragged >= 0, dragged < columns.count, columns[dragged].headerCell === cell { + return columns[dragged] + } + let index = column(at: NSPoint(x: cellFrame.midX, y: cellFrame.midY)) + if index >= 0, index < columns.count, columns[index].headerCell === cell { + return columns[index] + } + return columns.first { $0.headerCell === cell } + } + // AppKit redraws the header on every step of a resize or reorder drag but posts the column notifications only at mouse-up. override func viewWillDraw() { super.viewWillDraw() diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift index d2374ad33b..42902be98a 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift @@ -222,7 +222,8 @@ extension DataGridViewController { databaseType: model.configuration.traits.databaseType, nullDisplayString: presenter.registry.nullDisplayString, revealsInvisibleCharacters: presenter.registry.showsInvisibleCharacters, - fonts: ThemeEngine.shared.dataGridFonts + fonts: ThemeEngine.shared.dataGridFonts, + showsTypeLine: model.configuration.showsColumnTypes ) } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift index f97f1afd0d..0b880264cd 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift @@ -123,6 +123,31 @@ extension DataGridViewController { // MARK: - Header + // Both panes' headers take the type line together: the frozen pane lies over the main one, so their heights match. + // The clip keeps its offset in points, so the first visible row is put back under the new header, and auto widths + // are measured again with or without the line. + func applyHeaderLayout() { + let shows = model.configuration.showsColumnTypes + guard panes.contains(where: { $0.headerView.showsTypeLine != shows }) else { return } + knownWidths.removeAll() + let sample = viewportSample() + for pane in panes { + pane.headerView.showsTypeLine = shows + pane.scrollView.tile() + } + let table = main.tableView + let top = sample.map { table.rect(ofRow: $0.row).minY + $0.offset } ?? 0 + table.scroll(NSPoint(x: main.scrollView.contentView.bounds.origin.x, y: top - headerInset)) + updateFittingHeight() + } + + func headerTypeLine(for tableColumn: NSTableColumn, in kind: DataGridPane.Kind) -> DataGridHeaderTypeLine? { + guard model.configuration.showsColumnTypes, + let id = container.pane(kind).columnID(of: tableColumn), + let column = model.columns.column(id: id) else { return nil } + return DataGridHeaderTypeLine(column.type) + } + // Titles, the value-filter funnel, tooltips and sort accessibility for every column of both panes. func refreshHeaders() { let columns = model.columns @@ -156,7 +181,12 @@ extension DataGridViewController { tableColumn.headerToolTip = tooltip } let cell = tableColumn.headerCell - let label = headerAccessibilityLabel(for: column, showsComment: showsComments, isMasked: isMasked) + let label = headerAccessibilityLabel( + for: column, + showsComment: showsComments, + showsType: model.configuration.showsColumnTypes, + isMasked: isMasked + ) if cell.accessibilityLabel() != label { cell.setAccessibilityLabel(label) } @@ -227,7 +257,7 @@ extension DataGridViewController { sortKeyCount: Int ) -> String { var tooltip: String - if let typeName = column.type?.rawType ?? column.type?.displayName { + if let typeName = DataGridHeaderTypeLine.typeName(of: column.type) { tooltip = column.name + " (" + typeName + ")" } else { tooltip = column.name @@ -249,8 +279,12 @@ extension DataGridViewController { return tooltip } - private func headerAccessibilityLabel(for column: DataGridColumn, showsComment: Bool, isMasked: Bool) -> String { + // The type line is read out while it shows, so VoiceOver hears what the header draws. + private func headerAccessibilityLabel(for column: DataGridColumn, showsComment: Bool, showsType: Bool, isMasked: Bool) -> String { var label = String(format: String(localized: "Column: %@"), column.name) + if showsType, let typeName = DataGridHeaderTypeLine.typeName(of: column.type) { + label += ", " + typeName + } if isMasked { label += ", " + String(localized: "masked") } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController.swift b/apple/TablePro/Views/DataGrid/DataGridViewController.swift index dd7176f7af..37363a6f4c 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController.swift @@ -311,6 +311,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { main.scrollView.fitsRows = configuration.fitsRows container.followsPageScroll = configuration.fitsRows applyRowHeight() + applyHeaderLayout() } private func applyRowReorder(_ reorder: DataGridRowReorder, to table: DataGridTableView) { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift index 6cce31bb76..549eb1de45 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift @@ -178,6 +178,7 @@ extension MainContentCoordinator { var configuration = DataGridConfiguration() configuration.primaryKeyColumns = tab.tableContext.primaryKeyColumns configuration.showRowNumbers = AppSettingsManager.shared.dataGrid.showRowNumbers + configuration.showsColumnTypes = AppSettingsManager.shared.dataGrid.showsColumnTypesInHeader configuration.appliesRowSortPreferences = true configuration.appliesRowCopyFormat = true configuration.supportsColumnSort = tab.tabType != .table || supportsColumnSort diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 38533e8a2b..30415b6c75 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -34,6 +34,7 @@ struct DataGridSection: View { Toggle("Show alternate row backgrounds", isOn: $settings.showAlternateRows) Toggle("Show row numbers", isOn: $settings.showRowNumbers) + Toggle("Show column types in the header", isOn: $settings.showsColumnTypesInHeader) Toggle("Auto-show inspector on row select", isOn: $settings.autoShowInspector) Toggle("Smart value detection", isOn: $settings.enableSmartValueDetection) Toggle("Show invisible characters", isOn: $settings.showInvisibleCharacters) diff --git a/apple/TableProTests/Core/Services/ColumnTypeCategoryTests.swift b/apple/TableProTests/Core/Services/ColumnTypeCategoryTests.swift new file mode 100644 index 0000000000..f4a3abf0fa --- /dev/null +++ b/apple/TableProTests/Core/Services/ColumnTypeCategoryTests.swift @@ -0,0 +1,213 @@ +// +// ColumnTypeCategoryTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import Testing + +@MainActor +struct ColumnTypeCategoryTests { + private func expectCategories( + _ family: SQLTypeFamily?, + _ cases: KeyValuePairs, + sourceLocation: SourceLocation = #_sourceLocation + ) { + let classifier = ColumnTypeClassifier(family: family) + for (rawType, expected) in cases { + let category = ColumnTypeCategory(classifier.classify(rawTypeName: rawType)) + #expect(category == expected, "\(rawType)", sourceLocation: sourceLocation) + } + } + + // MARK: - Engine families + + @Test("MySQL's common types land in their categories") + func mysql() { + expectCategories(.mysql, [ + "varchar(255)": .text, + "char(36)": .text, + "longtext": .text, + "int(11)": .number, + "bigint(20) unsigned": .number, + "decimal(10,2)": .number, + "double": .number, + "tinyint(1)": .boolean, + "bit(1)": .boolean, + "datetime": .dateTime, + "timestamp": .dateTime, + "date": .dateTime, + "time": .dateTime, + "year(4)": .dateTime, + "json": .document, + "blob": .binary, + "varbinary(16)": .binary, + "geometry": .spatial, + "point": .spatial, + "enum('draft','sent')": .other, + "set('red','blue')": .other, + ]) + } + + @Test("PostgreSQL's common types land in their categories") + func postgres() { + expectCategories(.postgres, [ + "character varying(255)": .text, + "text": .text, + "uuid": .text, + "integer": .number, + "bigint": .number, + "numeric(10,2)": .number, + "double precision": .number, + "boolean": .boolean, + "timestamp with time zone": .dateTime, + "time without time zone": .dateTime, + "date": .dateTime, + "interval": .dateTime, + "bytea": .binary, + "jsonb": .document, + "xml": .document, + "hstore": .document, + "integer[]": .document, + "text[]": .document, + "geometry": .spatial, + "geography(Point,4326)": .spatial, + "vector(3)": .other, + ]) + } + + @Test("SQLite's common types land in their categories") + func sqlite() { + expectCategories(.sqlite, [ + "TEXT": .text, + "VARCHAR(50)": .text, + "INTEGER": .number, + "REAL": .number, + "NUMERIC": .number, + "BOOLEAN": .boolean, + "DATETIME": .dateTime, + "BLOB": .binary, + ]) + } + + @Test("SQL Server's common types land in their categories") + func mssql() { + expectCategories(.mssql, [ + "nvarchar(50)": .text, + "uniqueidentifier": .text, + "int": .number, + "decimal(18,2)": .number, + "money": .number, + "bit": .boolean, + "datetime2(7)": .dateTime, + "datetimeoffset": .dateTime, + "varbinary(max)": .binary, + "xml": .document, + "geography": .spatial, + ]) + } + + @Test("Oracle's common types land in their categories") + func oracle() { + expectCategories(.oracle, [ + "VARCHAR2(100)": .text, + "CLOB": .text, + "NUMBER(10,2)": .number, + "BINARY_DOUBLE": .number, + "DATE": .dateTime, + "TIMESTAMP(6)": .dateTime, + "TIMESTAMP(6) WITH TIME ZONE": .dateTime, + "INTERVAL DAY(2) TO SECOND(6)": .dateTime, + "BLOB": .binary, + "RAW(16)": .binary, + "SDO_GEOMETRY": .spatial, + ]) + } + + @Test("ClickHouse's common types land in their categories, through Nullable and LowCardinality") + func clickhouse() { + expectCategories(.clickhouse, [ + "String": .text, + "Nullable(String)": .text, + "LowCardinality(String)": .text, + "UUID": .text, + "UInt64": .number, + "Float64": .number, + "Decimal(18, 4)": .number, + "Bool": .boolean, + "Date32": .dateTime, + "DateTime64(3)": .dateTime, + "Array(String)": .document, + "Map(String, UInt64)": .document, + "Point": .spatial, + "Enum8('a' = 1, 'b' = 2)": .other, + ]) + } + + @Test("DuckDB's common types land in their categories") + func duckdb() { + expectCategories(.duckdb, [ + "VARCHAR": .text, + "HUGEINT": .number, + "DOUBLE": .number, + "BOOLEAN": .boolean, + "TIMESTAMPTZ": .dateTime, + "INTERVAL": .dateTime, + "BLOB": .binary, + "JSON": .document, + "INTEGER[]": .document, + "STRUCT(a INTEGER)": .document, + ]) + } + + @Test("A document store's sampled types land in their categories") + func documentStore() { + expectCategories(nil, [ + "VARCHAR": .text, + "ObjectId": .text, + "INTEGER": .number, + "BIGINT": .number, + "FLOAT": .number, + "BOOLEAN": .boolean, + "TIMESTAMP": .dateTime, + "JSON": .document, + "BLOB": .binary, + ]) + } + + // MARK: - Every case + + @Test("Each column type falls in one category, with no raw type as well as with one") + func everyColumnTypeHasACategory() { + let cases: [(ColumnType, ColumnTypeCategory)] = [ + (.text(rawType: nil), .text), + (.integer(rawType: nil), .number), + (.decimal(rawType: nil), .number), + (.date(rawType: nil), .dateTime), + (.timestamp(rawType: nil), .dateTime), + (.datetime(rawType: nil), .dateTime), + (.boolean(rawType: nil), .boolean), + (.blob(rawType: nil), .binary), + (.json(rawType: nil), .document), + (.array(rawType: nil, element: .integer(rawType: nil)), .document), + (.spatial(rawType: nil), .spatial), + (.enumType(rawType: nil, values: ["a"]), .other), + (.set(rawType: nil, values: nil), .other), + (.vector(rawType: nil), .other), + ] + for (type, expected) in cases { + #expect(ColumnTypeCategory(type) == expected, "\(type)") + } + } + + @Test("Every category has its own glyph, and the system has each one") + func everyCategoryHasAGlyph() { + let names = ColumnTypeCategory.allCases.map { $0.symbolName } + + #expect(Set(names).count == ColumnTypeCategory.allCases.count) + for name in names { + #expect(NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil, "\(name)") + } + } +} diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index 56e576b32f..0b869457cf 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -66,6 +66,23 @@ struct SettingsFieldDecodingTests { #expect(decoded.rowCopyFormat == .csvWithHeaders) } + @Test("Data Grid settings saved before column types in the header load with them off, and an explicit on round-trips") + func columnTypesInHeaderDefaultsOff() throws { + #expect(DataGridSettings.default.showsColumnTypesInHeader == false) + let legacy = try decode(DataGridSettings.self, #"{"showRowNumbers":false}"#) + #expect(legacy.showsColumnTypesInHeader == false) + #expect(legacy.showRowNumbers == false) + + let malformed = try decode(DataGridSettings.self, #"{"showsColumnTypesInHeader":"yes","showRowNumbers":false}"#) + #expect(malformed.showsColumnTypesInHeader == false) + #expect(malformed.showRowNumbers == false) + + var chosen = DataGridSettings.default + chosen.showsColumnTypesInHeader = true + let decoded = try decode(DataGridSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.showsColumnTypesInHeader == true) + } + @Test("A bad MCP value falls back alone and keeps the secure default") func mcpKeepsOtherFields() throws { let settings = try decode( diff --git a/apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift b/apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift new file mode 100644 index 0000000000..3c57974e1b --- /dev/null +++ b/apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift @@ -0,0 +1,306 @@ +// +// DataGridHeaderTypeLineTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct DataGridHeaderTypeLineTests { + // `loose` has no type: the result named three columns and typed two. + private static func typedRows(rowCount: Int = 5) -> TableRows { + TableRows.from( + queryRows: (0.. DataGridConfiguration { + var configuration = DataGridConfiguration() + configuration.showsColumnTypes = showsColumnTypes + return configuration + } + + private func grid(showsColumnTypes: Bool, rows: TableRows = typedRows()) -> HostedDataGrid { + HostedDataGrid(rows: rows, configuration: Self.configuration(showsColumnTypes: showsColumnTypes)) + } + + private func setShowsColumnTypes(_ shows: Bool, on grid: HostedDataGrid) { + grid.model.configuration.showsColumnTypes = shows + grid.layout() + } + + private func headerHeights(_ grid: HostedDataGrid) -> [CGFloat] { + grid.controller.panes.map { $0.headerView.frame.height } + } + + private func standardHeight() -> CGFloat { + let plain = grid(showsColumnTypes: false) + defer { plain.close() } + return plain.controller.main.headerView.frame.height + } + + // MARK: - Height + + @Test("The header is one line tall by default and one type line taller with column types, in both panes") + func headerHeightFollowsTheSetting() { + let standard = standardHeight() + let typed = grid(showsColumnTypes: true) + defer { typed.close() } + + #expect(standard > 0) + #expect(headerHeights(typed) == [standard + DataGridHeaderTypeLine.lineHeight, standard + DataGridHeaderTypeLine.lineHeight]) + #expect(typed.controller.headerInset == standard + DataGridHeaderTypeLine.lineHeight) + } + + @Test("Turning column types off restores today's header height and keeps the first row under it") + func turningTypesOffRestoresTheHeight() throws { + let standard = standardHeight() + let grid = grid(showsColumnTypes: false) + defer { grid.close() } + + setShowsColumnTypes(true, on: grid) + #expect(headerHeights(grid) == [standard + DataGridHeaderTypeLine.lineHeight, standard + DataGridHeaderTypeLine.lineHeight]) + var sample = try #require(grid.controller.viewportSample()) + #expect(sample.row == 0 && sample.offset == 0) + + setShowsColumnTypes(false, on: grid) + #expect(headerHeights(grid) == [standard, standard]) + #expect(grid.controller.headerInset == standard) + sample = try #require(grid.controller.viewportSample()) + #expect(sample.row == 0 && sample.offset == 0) + } + + @Test("A grid scrolled down keeps its first visible row when the header grows") + func scrolledGridKeepsItsFirstRow() throws { + let grid = grid(showsColumnTypes: false, rows: Self.typedRows(rowCount: 80)) + defer { grid.close() } + let table = grid.main + table.scroll(NSPoint(x: 0, y: table.rect(ofRow: 30).minY - grid.controller.headerInset)) + #expect(try #require(grid.controller.viewportSample()).row == 30) + + setShowsColumnTypes(true, on: grid) + + let sample = try #require(grid.controller.viewportSample()) + #expect(sample.row == 30) + #expect(sample.offset == 0) + } + + // MARK: - Layout + + @Test("With column types the title keeps AppKit's band on top and the type line sits under it, centered together") + func contentPutsTheTitleOnTop() { + let grid = grid(showsColumnTypes: true) + defer { grid.close() } + let header = grid.controller.main.headerView + let frame = NSRect(x: 10, y: 0, width: 120, height: header.frame.height) + + let content = header.contentRect(forCellFrame: frame) + let title = ThemeTableHeaderCell.titleRect(in: content) + + #expect(content.height == ThemeTableHeaderCell.interiorHeight + DataGridHeaderTypeLine.lineHeight) + #expect(content.midY == frame.midY) + #expect(title == NSRect(x: 10, y: content.minY, width: 120, height: ThemeTableHeaderCell.interiorHeight)) + #expect(content.maxY - title.maxY == DataGridHeaderTypeLine.lineHeight) + } + + @Test("Without column types a heading is the one centered band it always was") + func contentWithoutTypesIsTheBand() { + let grid = grid(showsColumnTypes: false) + defer { grid.close() } + let header = grid.controller.main.headerView + let frame = NSRect(x: 10, y: 0, width: 120, height: header.frame.height) + + let content = header.contentRect(forCellFrame: frame) + + #expect(content == ThemeTableHeaderCell.interiorRect(in: frame)) + #expect(ThemeTableHeaderCell.titleRect(in: content) == content) + } + + // MARK: - Type line + + @Test("The type line is the engine's spelling with its category, and nothing for an untyped or row-number column") + func typeLineReadsTheEnginesType() throws { + let grid = grid(showsColumnTypes: true) + defer { grid.close() } + let controller = grid.controller + + let idColumn = try #require(grid.tableColumn(named: "id")) + let labelColumn = try #require(grid.tableColumn(named: "label")) + let looseColumn = try #require(grid.tableColumn(named: "loose")) + let rowNumber = try #require(controller.main.rowNumberTableColumn) + + let id = try #require(controller.headerTypeLine(for: idColumn, in: .main)) + #expect(id.text == "bigint(20)") + #expect(id.category == .number) + let label = try #require(controller.headerTypeLine(for: labelColumn, in: .main)) + #expect(label.text == "character varying(255)") + #expect(label.category == .text) + #expect(controller.headerTypeLine(for: looseColumn, in: .main) == nil) + #expect(controller.headerTypeLine(for: rowNumber, in: .main) == nil) + } + + @Test("No type line is offered while column types are off") + func noTypeLineWhileOff() throws { + let grid = grid(showsColumnTypes: false) + defer { grid.close() } + + let column = try #require(grid.tableColumn(named: "id")) + + #expect(grid.controller.headerTypeLine(for: column, in: .main) == nil) + } + + @Test("A type with no spelling from the engine reads as the app's name for it") + func typeNameFallsBackToTheDisplayName() { + #expect(DataGridHeaderTypeLine.typeName(of: .integer(rawType: "int4")) == "int4") + #expect(DataGridHeaderTypeLine.typeName(of: .integer(rawType: nil)) == "Integer") + #expect(DataGridHeaderTypeLine.typeName(of: .json(rawType: " ")) == "JSON") + #expect(DataGridHeaderTypeLine.typeName(of: nil) == nil) + #expect(DataGridHeaderTypeLine(nil) == nil) + } + + @Test("The tooltip keeps the name and type, and VoiceOver hears the type only while the line shows") + func tooltipAndAccessibilityLabel() throws { + let grid = grid(showsColumnTypes: false) + defer { grid.close() } + let column = try #require(grid.tableColumn(named: "id")) + + #expect(column.headerToolTip == "id (bigint(20))") + #expect(column.headerCell.accessibilityLabel() == String(format: String(localized: "Column: %@"), "id")) + + setShowsColumnTypes(true, on: grid) + + #expect(column.headerToolTip == "id (bigint(20))") + #expect(column.headerCell.accessibilityLabel() == String(format: String(localized: "Column: %@"), "id") + ", bigint(20)") + } + + // MARK: - Width + + @Test("An automatic width makes room for a type line wider than the name and the values") + func automaticWidthHoldsTheTypeLine() throws { + let rows = Self.typedRows() + let column = DataGridColumn( + id: DataGridColumnID(name: "label", occurrence: 0), + dataIndex: 1, + type: rows.columnTypes[1], + comment: nil + ) + let input = DataGridColumnWidthCalculator.Input(column: column, accessory: .none, displayFormat: nil) + var calculator = DataGridColumnWidthCalculator( + rows: rows, + databaseType: nil, + nullDisplayString: "NULL", + revealsInvisibleCharacters: false, + fonts: ThemeEngine.shared.dataGridFonts + ) + let without = calculator.automaticWidth(input) + let line = try #require(DataGridHeaderTypeLine(column.type)) + + calculator.showsTypeLine = true + let with = calculator.automaticWidth(input) + + #expect(line.width > without) + #expect(with >= line.width) + #expect(calculator.fittedWidth(input, availableWidth: 1_000) >= line.width) + } + + @Test("The type line's width counts the glyph, the text and the insets") + func typeLineWidthCountsItsParts() throws { + let line = try #require(DataGridHeaderTypeLine(.text(rawType: "character varying(255)"))) + let text = ("character varying(255)" as NSString).size(withAttributes: [.font: DataGridHeaderTypeLine.font]).width + let glyph = DataGridHeaderTypeLine.glyphWidth(.text) + + #expect(glyph > 0) + #expect(line.width >= text + glyph + DataGridHeaderTypeLine.glyphSpacing + + DataGridHeaderTypeLine.leadingInset + DataGridHeaderTypeLine.trailingInset) + } + + @Test("Turning column types on widens an automatic width to its type line and turning them off narrows it back") + func togglingMeasuresAutomaticWidthsAgain() throws { + let grid = grid(showsColumnTypes: false) + defer { grid.close() } + let column = try #require(grid.tableColumn(named: "label")) + let before = column.width + let line = try #require(DataGridHeaderTypeLine(.text(rawType: "character varying(255)"))) + #expect(before < line.width) + + setShowsColumnTypes(true, on: grid) + #expect(column.width >= line.width) + + setShowsColumnTypes(false, on: grid) + #expect(column.width == before) + } + + @Test("A width the user set stays when column types are turned on") + func userWidthSurvivesTheToggle() throws { + let grid = grid(showsColumnTypes: false) + defer { grid.close() } + let column = try #require(grid.tableColumn(named: "label")) + column.width = 90 + grid.controller.columnDidResize(column, in: grid.controller.main) + + setShowsColumnTypes(true, on: grid) + + #expect(column.width == 90) + } + + // MARK: - Drawing + + // Drawn straight into an sRGB bitmap, flipped like the header, so row 0 of the bitmap is the top. + private func raster(size: NSSize, _ draw: () -> Void) throws -> NSBitmapImageRep { + let space = try #require(CGColorSpace(name: CGColorSpace.sRGB)) + let context = try #require(CGContext( + data: nil, + width: Int(size.width), + height: Int(size.height), + bitsPerComponent: 8, + bytesPerRow: 0, + space: space, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + )) + context.translateBy(x: 0, y: size.height) + context.scaleBy(x: 1, y: -1) + let aqua = try #require(NSAppearance(named: .aqua)) + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) + aqua.performAsCurrentDrawingAppearance(draw) + NSGraphicsContext.restoreGraphicsState() + return NSBitmapImageRep(cgImage: try #require(context.makeImage())) + } + + // Pixels in the type line's band that are not the header's own fill. + private func typeLineInk(of name: String, in grid: HostedDataGrid) throws -> Int { + let header = grid.controller.main.headerView + let tableColumn = try #require(grid.tableColumn(named: name)) + let index = try #require(grid.main.tableColumns.firstIndex { $0 === tableColumn }) + let cell = try #require(tableColumn.headerCell as? ThemeTableHeaderCell) + let frame = header.headerRect(ofColumn: index) + let rep = try raster(size: NSSize(width: frame.maxX.rounded(.up), height: frame.height)) { + cell.draw(withFrame: frame, in: header) + } + let content = header.contentRect(forCellFrame: frame) + let band = ThemeTableHeaderCell.titleRect(in: content).maxY ..< content.maxY + let fill = try #require(rep.colorAt(x: Int(frame.minX) + 1, y: 1)) + var ink = 0 + for y in Int(band.lowerBound) ..< Int(band.upperBound) { + for x in Int(frame.minX) ..< Int(frame.maxX) - 2 { + guard let color = rep.colorAt(x: x, y: y) else { continue } + if !ThemeTestFixture.matches(color, fill, tolerance: 0.05) { ink += 1 } + } + } + return ink + } + + @Test("A typed column draws its type line under the title and an untyped one leaves the line empty") + func headerDrawsTheTypeLine() throws { + let grid = grid(showsColumnTypes: true) + defer { grid.close() } + + #expect(try typeLineInk(of: "id", in: grid) > 0) + #expect(try typeLineInk(of: "loose", in: grid) == 0) + } +} diff --git a/apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift b/apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift new file mode 100644 index 0000000000..6c63e5acc6 --- /dev/null +++ b/apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift @@ -0,0 +1,36 @@ +// +// DataTabColumnTypesSettingTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +extension GlobalStateSuites { + @MainActor + struct DataTabColumnTypesSettingTests { + private func configuration() -> DataGridConfiguration { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(QueryTab(title: "orders", query: "SELECT * FROM orders", tabType: .table, tableName: "orders")) + return fixture.coordinator.gridConfiguration(for: tab) + } + + @Test("A data tab's grid shows column types while the Data Grid setting is on", + .appSettings { $0.dataGrid.showsColumnTypesInHeader = true }) + func settingOnShowsTypes() { + #expect(configuration().showsColumnTypes) + } + + @Test("A data tab's grid has one header line while the setting is off", + .appSettings { $0.dataGrid.showsColumnTypesInHeader = false }) + func settingOffHidesTypes() { + #expect(!configuration().showsColumnTypes) + } + + @Test("A grid no setting reaches keeps one header line") + func plainGridHasNoTypes() { + #expect(!DataGridConfiguration().showsColumnTypes) + } + } +} From 2c9c27c5ed4da1b5c7fdd0efda8d36719e011d54 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 17:09:28 +0700 Subject: [PATCH 084/123] feat(tabs): name the database and connection in table tab titles Settings > General > Tabs gets "Show database and connection in table tab titles", off by default. On, a table or view tab reads `orders@shop_demo (Shop Demo)`, or `reporting.orders@shop_demo (...)` outside the default schema, with the object's sidebar glyph before it. Query tabs and every other kind keep their titles. The located title is resolved for drawing by EditorTabLabelResolver and never written to QueryTab.title, so turning the setting off restores every open tab and nothing reaches saved tabs. A missing database or connection name is left out. The tooltip and VoiceOver label follow the drawn text, and a located title is not qualified again by its database. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../EditorTabLabelResolver.swift | 96 ++++++++++-- ...plitViewController+TabStripAccessory.swift | 12 +- .../Models/Settings/AppSettings.swift | 11 +- .../TablePro/Views/Main/EditorTabStrip.swift | 15 +- .../Views/Main/EditorTabStripLayout.swift | 1 + .../Views/Settings/GeneralSettingsView.swift | 3 + .../Settings/SettingsFieldDecodingTests.swift | 17 +++ .../Main/EditorTabLabelResolverTests.swift | 138 ++++++++++++++++++ 8 files changed, 277 insertions(+), 16 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift index 57012883e1..f594e9cb98 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift @@ -5,6 +5,21 @@ import Foundation +/// How a tab that shows a table or view names it. Any other tab keeps its title in both styles. +internal enum EditorTabTitleStyle: Equatable { + /// The object's name alone, as it was opened: `orders`, or `reporting.orders` outside the + /// engine's default schema. + case name + /// The name, the database and the connection: `orders@shop_demo (Shop Demo)`, for a reader + /// moving between several databases and connections who wants each tab to say where its rows + /// come from without hovering it. + case location(connectionName: String) + + internal init(showsLocation: Bool, connectionName: String) { + self = showsLocation ? .location(connectionName: connectionName) : .name + } +} + /// What the editor tab strip draws on each tab, and what it says about that tab on hover and to /// VoiceOver. /// @@ -25,44 +40,103 @@ import Foundation /// Resolved for rendering rather than written into `QueryTab.title`, because qualification is a /// function of what else is open: baked into the tab it would outlive the sibling that caused it, /// follow the tab into persistence, and come back out of Recently Closed long after it meant -/// anything. +/// anything. A located title is resolved here too: it is a preference, so turning it off has to +/// bring every open tab back to its name at once, and a saved tab must never carry it. internal enum EditorTabLabelResolver { internal struct Label: Equatable { /// What the strip draws, and what VoiceOver reads. internal let text: String /// What hovering says. internal let description: String + /// The object's glyph, drawn before the text. Only a located title carries one: it is long + /// and mostly the same from tab to tab, so the glyph is what still tells a table from a + /// view at a glance. + internal let symbolName: String? - internal init(text: String, description: String) { + internal init(text: String, description: String, symbolName: String? = nil) { self.text = text self.description = description + self.symbolName = symbolName } } - internal static func resolve(tabs: [QueryTab], target: ContainerSwitchTarget?) -> [UUID: Label] { + internal static func resolve( + tabs: [QueryTab], + target: ContainerSwitchTarget?, + style: EditorTabTitleStyle = .name + ) -> [UUID: Label] { + var titles: [UUID: String] = [:] var containers: [UUID: String] = [:] var containersByTitle: [String: Set] = [:] for tab in tabs { - let container = tab.tableContext.tableName == nil - ? "" - : WorkspaceAnchoring.containerName(of: tab, target: target) ?? "" + let title = title(of: tab, style: style) + let container = qualifyingContainer(of: tab, target: target, style: style) + titles[tab.id] = title containers[tab.id] = container - containersByTitle[tab.title, default: []].insert(container) + containersByTitle[title, default: []].insert(container) } return tabs.reduce(into: [:]) { result, tab in + let title = titles[tab.id] ?? tab.title /// More than one container behind one title is the whole test. Two tabs sharing a title /// inside one container are not told apart by naming that container, so they stay bare. - let isAmbiguous = (containersByTitle[tab.title]?.count ?? 0) > 1 - let qualified = qualify(tab.title, with: containers[tab.id]) + let isAmbiguous = (containersByTitle[title]?.count ?? 0) > 1 + let qualified = qualify(title, with: containers[tab.id]) result[tab.id] = Label( - text: isAmbiguous ? qualified : tab.title, - description: qualified + text: isAmbiguous ? qualified : title, + description: qualified, + symbolName: symbolName(of: tab, style: style) ) } } + /// `orders@shop_demo (Shop Demo)`. A part with no value is left out rather than drawn empty, + /// so a tab whose database is not known reads `orders (Shop Demo)`. The `@` joins two + /// identifiers, so it is not localized; the parentheses go through the catalog, where a locale + /// can set them its own way. + internal static func locationTitle(object: String, database: String, connectionName: String) -> String { + let located = database.isEmpty ? object : "\(object)@\(database)" + guard !connectionName.isBlank else { return located } + return String(format: String(localized: "%1$@ (%2$@)"), located, connectionName) + } + + /// The object's title is reused rather than rebuilt from its name, because it already carries + /// the schema exactly when the engine needs it named. + private static func title(of tab: QueryTab, style: EditorTabTitleStyle) -> String { + guard case let .location(connectionName) = style, showsObject(tab) else { return tab.title } + return locationTitle( + object: tab.title, + database: tab.tableContext.databaseName, + connectionName: connectionName + ) + } + + private static func symbolName(of tab: QueryTab, style: EditorTabTitleStyle) -> String? { + guard case .location = style, showsObject(tab) else { return nil } + return TableRowLogic.iconName(for: tab.tableContext.resolvedObjectKind()) + } + + /// A located title already names its database, so on an engine whose containers are databases + /// qualifying it again would read `shop_demo.orders@shop_demo`. A schema still qualifies it, + /// since the title leaves the default schema out. + private static func qualifyingContainer( + of tab: QueryTab, + target: ContainerSwitchTarget?, + style: EditorTabTitleStyle + ) -> String { + guard tab.tableContext.tableName != nil, + let container = WorkspaceAnchoring.containerName(of: tab, target: target) else { return "" } + if case .location = style, showsObject(tab), container == tab.tableContext.databaseName { + return "" + } + return container + } + + private static func showsObject(_ tab: QueryTab) -> Bool { + tab.tabType == .table && tab.tableContext.tableName != nil + } + /// On an engine whose containers are schemas, a table tab outside the default schema is already /// titled `reporting.orders`, so prefixing the container again would read `reporting.reporting.orders`. private static func qualify(_ title: String, with container: String?) -> String { diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift index 06e7a84ac3..c08c0833da 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift @@ -103,6 +103,7 @@ internal extension MainSplitViewController { containerTarget: workspace.connection.flatMap { PluginManager.shared.containerSwitchTarget(for: $0.type) }, + connectionName: workspace.connection?.name ?? "", execution: TabExecutionObservation(owner: sessionState.coordinator), onNewTab: { [weak workspace] in workspace?.sessionState?.coordinator.commandActions?.newTab() @@ -185,10 +186,15 @@ internal extension MainSplitViewController { /// The resolver's description, not the drawn title: a table tab carries its database /// and schema there even when the short title is unique, and the tooltip is where a /// truncated or duplicated name is told apart. - tooltip: { [weak manager] id in + tooltip: { [weak manager, weak workspace] id in guard let manager, let tab = manager.tabs.first(where: { $0.id == id }) else { return "" } - let description = EditorTabLabelResolver.resolve(tabs: manager.visibleTabs, target: target)[id]? - .description ?? tab.title + let style = EditorTabTitleStyle( + showsLocation: AppSettingsManager.shared.tabs.titleShowsLocation, + connectionName: workspace?.connection?.name ?? "" + ) + let description = EditorTabLabelResolver.resolve( + tabs: manager.visibleTabs, target: target, style: style + )[id]?.description ?? tab.title guard tab.isPreview else { return description } return String( format: String(localized: "%@\nPreview tab. Double-click to keep it open."), diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index 45925a09c8..8d88433061 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -350,11 +350,19 @@ struct TabSettings: Codable, Equatable { /// What the strip does once the tabs stop fitting. `scroll` is the system's answer and the /// default: every tab bar Apple ships keeps one row and scrolls it. var overflow: EditorTabStripOverflow = .scroll + /// Off by default: the location makes a table tab's title several times longer than the + /// table's name, and a tab at its minimum width then truncates it. + var titleShowsLocation: Bool = false static let `default` = TabSettings() - init(enablePreviewTabs: Bool = true, overflow: EditorTabStripOverflow = .scroll) { + init( + enablePreviewTabs: Bool = true, + overflow: EditorTabStripOverflow = .scroll, + titleShowsLocation: Bool = false + ) { self.enablePreviewTabs = enablePreviewTabs self.overflow = overflow + self.titleShowsLocation = titleShowsLocation } init(from decoder: Decoder) throws { @@ -362,5 +370,6 @@ struct TabSettings: Codable, Equatable { let fallback = Self.default enablePreviewTabs = container.decodeSetting(.enablePreviewTabs, default: fallback.enablePreviewTabs) overflow = container.decodeSetting(.overflow, default: fallback.overflow) + titleShowsLocation = container.decodeSetting(.titleShowsLocation, default: fallback.titleShowsLocation) } } diff --git a/apple/TablePro/Views/Main/EditorTabStrip.swift b/apple/TablePro/Views/Main/EditorTabStrip.swift index da6a9ffbf6..9ae5884984 100644 --- a/apple/TablePro/Views/Main/EditorTabStrip.swift +++ b/apple/TablePro/Views/Main/EditorTabStrip.swift @@ -39,6 +39,9 @@ internal struct EditorTabStrip: View { /// shares a title with. Resolved by the window, because a view has no business asking the /// plugin registry what kind of container a connection has. internal let containerTarget: ContainerSwitchTarget? + /// Named in a table tab's title when Settings asks for the location. Passed in rather than read + /// from the session, for the reason `containerTarget` is. + internal var connectionName = "" /// Which tabs are running something. Observed rather than pushed in, so a claim opening or /// settling redraws this strip the same way it redraws the result pane. A tab that is not the /// selected one has no status bar on screen, and its progress used to show as the window-wide @@ -157,7 +160,11 @@ internal struct EditorTabStrip: View { } private var labels: [UUID: EditorTabLabelResolver.Label] { - EditorTabLabelResolver.resolve(tabs: displayedTabs, target: containerTarget) + EditorTabLabelResolver.resolve(tabs: displayedTabs, target: containerTarget, style: titleStyle) + } + + private var titleStyle: EditorTabTitleStyle { + EditorTabTitleStyle(showsLocation: settings.tabs.titleShowsLocation, connectionName: connectionName) } @ViewBuilder @@ -344,6 +351,12 @@ private struct EditorTabStripItem: View { .foregroundStyle(titleColor) .accessibilityHidden(true) } + if let symbolName = label.symbolName { + Image(systemName: symbolName) + .font(.system(size: EditorTabStripLayout.objectGlyphSize)) + .foregroundStyle(titleColor) + .accessibilityHidden(true) + } Text(label.text) .lineLimit(1) .truncationMode(.tail) diff --git a/apple/TablePro/Views/Main/EditorTabStripLayout.swift b/apple/TablePro/Views/Main/EditorTabStripLayout.swift index 1f712426c8..306bfd9591 100644 --- a/apple/TablePro/Views/Main/EditorTabStripLayout.swift +++ b/apple/TablePro/Views/Main/EditorTabStripLayout.swift @@ -30,6 +30,7 @@ internal enum EditorTabStripLayout { internal static let accessoryInset: CGFloat = 5 internal static let fontSize: CGFloat = 11 internal static let pinGlyphSize: CGFloat = 9 + internal static let objectGlyphSize: CGFloat = 10 internal static let pinSpacing: CGFloat = 3 /// One device pixel on the 2x displays this chrome is drawn for, which is what the system uses diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index c6b819c4ae..786bc8d2fa 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -58,6 +58,9 @@ struct GeneralSettingsView: View { } } .help("Scrolling keeps one row of tabs, the way every macOS tab bar does. Rows wraps them so nothing is off screen.") + + Toggle("Show database and connection in table tab titles", isOn: $tabSettings.titleShowsLocation) + .help("Titles a table tab orders@shop (Shop Demo), with a table or view icon, so each tab says where its rows come from. Query tabs keep their names.") } Section { diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index 0b869457cf..d8a2412ad7 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -83,6 +83,23 @@ struct SettingsFieldDecodingTests { #expect(decoded.showsColumnTypesInHeader == true) } + @Test("Tab settings saved before located titles keep bare table names, and the choice round-trips") + func titleShowsLocationDefaultsOff() throws { + let legacy = try decode(TabSettings.self, #"{"enablePreviewTabs":false,"overflow":"rows"}"#) + #expect(legacy.titleShowsLocation == false) + #expect(legacy.enablePreviewTabs == false) + #expect(legacy.overflow == .rows) + #expect(TabSettings.default.titleShowsLocation == false) + + let bad = try decode(TabSettings.self, #"{"titleShowsLocation":3,"enablePreviewTabs":false}"#) + #expect(bad.titleShowsLocation == false) + #expect(bad.enablePreviewTabs == false) + + let chosen = TabSettings(titleShowsLocation: true) + let decoded = try decode(TabSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.titleShowsLocation == true) + } + @Test("A bad MCP value falls back alone and keeps the secure default") func mcpKeepsOtherFields() throws { let settings = try decode( diff --git a/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift b/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift index 646553e89d..844c15e9f4 100644 --- a/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift @@ -95,4 +95,142 @@ struct EditorTabLabelResolverTests { #expect(labels[tabs[0].id]?.text == "app.orders") #expect(labels[tabs[1].id]?.text == "orders") } + + // MARK: - Located titles + + private let shop = EditorTabTitleStyle.location(connectionName: "Shop Demo") + + @Test("The setting picks the style, and off keeps the bare name") + func styleFollowsTheSetting() { + #expect(EditorTabTitleStyle(showsLocation: false, connectionName: "Shop Demo") == .name) + #expect(EditorTabTitleStyle(showsLocation: true, connectionName: "Shop Demo") == shop) + } + + @Test("A table tab names its database and connection") + func locatesATableTab() { + let tabs = [tableTab("orders", database: "shop_demo")] + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: .database, style: shop) + + #expect(labels[tabs[0].id]?.text == "orders@shop_demo (Shop Demo)") + #expect(labels[tabs[0].id]?.description == "orders@shop_demo (Shop Demo)") + #expect(labels[tabs[0].id]?.symbolName == "tablecells") + } + + @Test("A table outside the default schema keeps its schema in front of the name") + func locatesASchemaQualifiedTable() { + var reporting = tableTab("orders", database: "shop_demo", schema: "reporting") + reporting.title = "reporting.orders" + let labels = EditorTabLabelResolver.resolve(tabs: [reporting], target: .schema, style: shop) + + #expect(labels[reporting.id]?.text == "reporting.orders@shop_demo (Shop Demo)") + #expect(labels[reporting.id]?.description == "reporting.orders@shop_demo (Shop Demo)") + } + + @Test("A table in the default schema reads bare, and hovering still names the schema") + func describesTheDefaultSchema() { + let tabs = [tableTab("orders", database: "shop_demo", schema: "public")] + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: .schema, style: shop) + + #expect(labels[tabs[0].id]?.text == "orders@shop_demo (Shop Demo)") + #expect(labels[tabs[0].id]?.description == "public.orders@shop_demo (Shop Demo)") + } + + @Test("A missing database or connection name is left out rather than drawn empty") + func leavesOutMissingParts() { + #expect(EditorTabLabelResolver.locationTitle(object: "orders", database: "", connectionName: "Shop Demo") + == "orders (Shop Demo)") + #expect(EditorTabLabelResolver.locationTitle(object: "orders", database: "shop_demo", connectionName: "") + == "orders@shop_demo") + #expect(EditorTabLabelResolver.locationTitle(object: "orders", database: "shop_demo", connectionName: " ") + == "orders@shop_demo") + #expect(EditorTabLabelResolver.locationTitle(object: "orders", database: "", connectionName: "") == "orders") + + let tabs = [tableTab("orders")] + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: nil, style: shop) + #expect(labels[tabs[0].id]?.text == "orders (Shop Demo)") + } + + @Test("A long title is kept whole with the table name first, so the strip's tail truncation cuts the location") + func keepsLongTitlesWhole() { + let table = String(repeating: "customer_order_line_item_", count: 4) + "archive" + let database = String(repeating: "warehouse_reporting_", count: 3) + "replica" + let connection = "Production Analytics Read Replica (eu-west-1)" + let tabs = [tableTab(table, database: database)] + let labels = EditorTabLabelResolver.resolve( + tabs: tabs, target: .database, style: .location(connectionName: connection) + ) + + let text = labels[tabs[0].id]?.text ?? "" + #expect(text == "\(table)@\(database) (\(connection))") + #expect(text.hasPrefix(table)) + #expect(!text.contains("…")) + } + + @Test("A view tab carries the view glyph, and every other object kind its sidebar glyph") + func locatesAViewWithItsGlyph() { + var view = tableTab("active_orders", database: "shop_demo") + view.tableContext.isView = true + var materialized = tableTab("daily_totals", database: "shop_demo") + materialized.tableContext.objectType = .materializedView + let labels = EditorTabLabelResolver.resolve(tabs: [view, materialized], target: .database, style: shop) + + #expect(labels[view.id]?.text == "active_orders@shop_demo (Shop Demo)") + #expect(labels[view.id]?.symbolName == "eye") + #expect(labels[materialized.id]?.symbolName == TableRowLogic.iconName(for: .materializedView)) + } + + @Test("Query tabs and other kinds keep their titles and draw no glyph") + func leavesOtherKindsAlone() { + var query = QueryTab(title: "Query 1", tabType: .query) + query.tableContext.databaseName = "shop_demo" + var dashboard = QueryTab(title: "Server Dashboard", tabType: .serverDashboard) + dashboard.tableContext.databaseName = "shop_demo" + var listing = QueryTab(title: "Objects", tabType: .tableListing) + listing.tableContext.databaseName = "shop_demo" + let tabs = [query, dashboard, listing] + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: .database, style: shop) + + for tab in tabs { + #expect(labels[tab.id]?.text == tab.title) + #expect(labels[tab.id]?.symbolName == nil) + } + } + + @Test("The bare style draws exactly what it drew before the setting existed") + func bareStyleIsUnchanged() { + let tabs = [ + tableTab("role_ability", database: "banshi_test"), + tableTab("role_ability", database: "banshi_online"), + tableTab("orders", database: "app"), + ] + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: .database) + + #expect(labels[tabs[0].id] == EditorTabLabelResolver.Label( + text: "banshi_test.role_ability", description: "banshi_test.role_ability" + )) + #expect(labels[tabs[2].id] == EditorTabLabelResolver.Label(text: "orders", description: "app.orders")) + #expect(tabs.allSatisfy { labels[$0.id]?.symbolName == nil }) + } + + @Test("The same table in two databases is told apart by the location alone, never qualified again") + func locationDisambiguatesWithoutDoubling() { + let tabs = [ + tableTab("role_ability", database: "banshi_test"), + tableTab("role_ability", database: "banshi_online"), + ] + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: .database, style: shop) + + #expect(labels[tabs[0].id]?.text == "role_ability@banshi_test (Shop Demo)") + #expect(labels[tabs[1].id]?.text == "role_ability@banshi_online (Shop Demo)") + #expect(labels[tabs[0].id]?.description == "role_ability@banshi_test (Shop Demo)") + } + + @Test("A located title never reaches the tab itself, so turning the setting off restores the name") + func locationIsNotWrittenToTheTab() { + let tabs = [tableTab("orders", database: "shop_demo")] + _ = EditorTabLabelResolver.resolve(tabs: tabs, target: .database, style: shop) + + #expect(tabs[0].title == "orders") + #expect(EditorTabLabelResolver.resolve(tabs: tabs, target: .database)[tabs[0].id]?.text == "orders") + } } From 92cbe088b7af123f7567562a03f6c3cf196b9063 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 17:09:33 +0700 Subject: [PATCH 085/123] feat(results): offer to show the result bar above the grid Settings > Data Grid gets "Show the result bar above the grid", off by default. On, the existing ResultStatusBar is drawn above the error banner, the filter panel and the result instead of below them, under the result set tabs that choose what it describes. Nothing in the bar changes. The placement travels as an environment value: the status bar chrome draws its rule on the edge facing the content, and the bar's popovers (columns, highlight rules, pages, timing, selection summary) open toward the content instead of over the editor, tab strip or toolbar. Every other status bar keeps the default bottom placement. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/QueryResultPresentation.swift | 15 +++++++ .../Models/Settings/AppSettings.swift | 9 ++++- .../Components/PaginationControlsView.swift | 9 +++-- .../Main/Child/MainEditorContentView.swift | 30 ++++++++++---- .../Results/ExecutionIndicatorView.swift | 3 +- .../Views/Results/ResultStatusBar.swift | 5 ++- .../Results/SelectionSummaryReadout.swift | 3 +- .../Views/Results/StatusBarChrome.swift | 34 +++++++++++++++- .../Settings/Sections/DataGridSection.swift | 2 + .../Query/QueryResultPresentationTests.swift | 40 +++++++++++++++++++ .../Settings/SettingsFieldDecodingTests.swift | 17 ++++++++ .../Main/ResultStatusBarLayoutTests.swift | 31 ++++++++++++++ 12 files changed, 179 insertions(+), 19 deletions(-) diff --git a/apple/TablePro/Models/Query/QueryResultPresentation.swift b/apple/TablePro/Models/Query/QueryResultPresentation.swift index 89c93b7d56..f099a8e232 100644 --- a/apple/TablePro/Models/Query/QueryResultPresentation.swift +++ b/apple/TablePro/Models/Query/QueryResultPresentation.swift @@ -39,6 +39,13 @@ enum ResultSetChooserPlacement: Equatable { case tabRow } +// Below the result is the window's bottom-bar convention. Above it is a setting, for a reader who wants the +// row count and pages beside the filters rather than at the far end of a tall grid. +enum StatusBarPlacement: Equatable, Sendable { + case top + case bottom +} + // A plain struct, not a `QueryTab`, so tests reach every state without a tab manager, coordinator or session registry. struct QueryResultInputs: Equatable { var tabType: TabType = .query @@ -65,6 +72,7 @@ struct QueryResultInputs: Equatable { var executionStatusMessage: String? var hasAppliedFilters = false var isFilterPanelVisible = false + var prefersStatusBarAtTop = false } // Pure: every branch is decidable from `QueryResultInputs` alone, like `ResultStatusModel` and `ResultSetPolicy`. @@ -74,15 +82,22 @@ struct QueryResultPresentation: Equatable { let showsFilterChrome: Bool // Always: a plan without the bar can't be switched away from or pinned. Its row readout hides via `StatusBarSnapshot.isQueryPlan`. let showsStatusBar: Bool + let statusBarPlacement: StatusBarPlacement let showsErrorBanner: Bool var showsResultSetSelector: Bool { resultSetChooser != .hidden } + // One question per edge, so the pane cannot draw the bar at both or at neither. + func showsStatusBar(at placement: StatusBarPlacement) -> Bool { + showsStatusBar && statusBarPlacement == placement + } + init(inputs: QueryResultInputs) { content = Self.resolveContent(inputs) resultSetChooser = Self.resolveResultSetChooser(inputs) showsFilterChrome = Self.resolvesFilterChrome(inputs) showsStatusBar = true + statusBarPlacement = inputs.prefersStatusBarAtTop ? .top : .bottom showsErrorBanner = Self.resolvedError(inputs) != nil } diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index 8d88433061..acc91b2bfe 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -127,6 +127,7 @@ struct DataGridSettings: Codable, Equatable { var rowCopyFormat: RowCopyFormat var showInvisibleCharacters: Bool var showsColumnTypesInHeader: Bool + var resultBarAtTop: Bool static let `default` = DataGridSettings( rowHeight: .normal, @@ -144,7 +145,8 @@ struct DataGridSettings: Codable, Equatable { defaultSortDirection: .ascending, rowCopyFormat: .rows, showInvisibleCharacters: true, - showsColumnTypesInHeader: false + showsColumnTypesInHeader: false, + resultBarAtTop: false ) init( @@ -163,7 +165,8 @@ struct DataGridSettings: Codable, Equatable { defaultSortDirection: SortDirection = .ascending, rowCopyFormat: RowCopyFormat = .rows, showInvisibleCharacters: Bool = true, - showsColumnTypesInHeader: Bool = false + showsColumnTypesInHeader: Bool = false, + resultBarAtTop: Bool = false ) { self.rowHeight = rowHeight self.dateFormat = dateFormat @@ -181,6 +184,7 @@ struct DataGridSettings: Codable, Equatable { self.rowCopyFormat = rowCopyFormat self.showInvisibleCharacters = showInvisibleCharacters self.showsColumnTypesInHeader = showsColumnTypesInHeader + self.resultBarAtTop = resultBarAtTop } init(from decoder: Decoder) throws { @@ -211,6 +215,7 @@ struct DataGridSettings: Codable, Equatable { showsColumnTypesInHeader = container.decodeSetting( .showsColumnTypesInHeader, default: fallback.showsColumnTypesInHeader ) + resultBarAtTop = container.decodeSetting(.resultBarAtTop, default: fallback.resultBarAtTop) } // MARK: - Validated Properties diff --git a/apple/TablePro/Views/Components/PaginationControlsView.swift b/apple/TablePro/Views/Components/PaginationControlsView.swift index 14db7bf6aa..0428c1f4fe 100644 --- a/apple/TablePro/Views/Components/PaginationControlsView.swift +++ b/apple/TablePro/Views/Components/PaginationControlsView.swift @@ -32,6 +32,7 @@ struct PaginationControlsView: View { @State private var showJumpPopover = false @State private var showCustomPopover = false + @Environment(\.statusBarPlacement) private var placement @State private var jumpPage: Int? @State private var customPageSize: Int? @FocusState private var isJumpFocused: Bool @@ -95,7 +96,7 @@ struct PaginationControlsView: View { .help(String(localized: "Rows per page")) .accessibilityValue(pagination.pageSize.formatted()) .accessibilityIdentifier("pagination-page-size") - .popover(isPresented: $showCustomPopover, arrowEdge: .top) { + .popover(isPresented: $showCustomPopover, arrowEdge: placement.popoverArrowEdge) { customPageSizePopover } } @@ -208,7 +209,7 @@ struct PaginationControlsView: View { .disabled(!pagination.hasRowCountTotal || pagination.isLoading) .help(String(localized: "Go to page")) .pageIndicatorAccessibility(value: pageIndicatorAccessibilityValue) - .popover(isPresented: $showJumpPopover, arrowEdge: .top) { + .popover(isPresented: $showJumpPopover, arrowEdge: placement.popoverArrowEdge) { jumpPopover } } else { @@ -233,10 +234,10 @@ struct PaginationControlsView: View { .disabled(pagination.isLoading) .help(String(localized: "Go to page")) .pageIndicatorAccessibility(value: pageIndicatorAccessibilityValue) - .popover(isPresented: $showJumpPopover, arrowEdge: .top) { + .popover(isPresented: $showJumpPopover, arrowEdge: placement.popoverArrowEdge) { jumpPopover } - .popover(isPresented: $showCustomPopover, arrowEdge: .top) { + .popover(isPresented: $showCustomPopover, arrowEdge: placement.popoverArrowEdge) { customPageSizePopover } } diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index bd33342942..61d57602af 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -710,6 +710,12 @@ struct MainEditorContentView: View { ) } + /// Above the error banner, so a failure appearing or being dismissed moves the grid and + /// never the bar. Below the result set tabs, which choose the result this bar describes. + if presentation.showsStatusBar(at: .top) { + statusBarSection(tab: tab, placement: .top) + } + if presentation.showsErrorBanner { executionErrorBanner(tab: tab) } @@ -721,19 +727,26 @@ struct MainEditorContentView: View { resultContent(presentation.content, tab: tab, rows: rows) .gridStandInBackground(isActive: presentation.content.standsInForGrid) - if presentation.showsStatusBar { - if let model = coordinator.activeGridModel { - DataGridModelReader(model: model) { model in - statusBar(tab: tab, selectedRowCount: model.selection.affectedRows.count) - } - } else { - statusBar(tab: tab, selectedRowCount: 0) - } + if presentation.showsStatusBar(at: .bottom) { + statusBarSection(tab: tab, placement: .bottom) } } .frame(maxWidth: .infinity, maxHeight: .infinity) } + private func statusBarSection(tab: QueryTab, placement: StatusBarPlacement) -> some View { + Group { + if let model = coordinator.activeGridModel { + DataGridModelReader(model: model) { model in + statusBar(tab: tab, selectedRowCount: model.selection.affectedRows.count) + } + } else { + statusBar(tab: tab, selectedRowCount: 0) + } + } + .environment(\.statusBarPlacement, placement) + } + @ViewBuilder private func resultContent( _ content: QueryResultContent, @@ -856,6 +869,7 @@ struct MainEditorContentView: View { inputs.executionStatusMessage = tab.execution.statusMessage inputs.hasAppliedFilters = tab.filterState.hasAppliedFilters inputs.isFilterPanelVisible = tab.filterState.isVisible + inputs.prefersStatusBarAtTop = settingsManager.dataGrid.resultBarAtTop return QueryResultPresentation(inputs: inputs) } diff --git a/apple/TablePro/Views/Results/ExecutionIndicatorView.swift b/apple/TablePro/Views/Results/ExecutionIndicatorView.swift index 9c7c120b3b..ad5ed5d7d4 100644 --- a/apple/TablePro/Views/Results/ExecutionIndicatorView.swift +++ b/apple/TablePro/Views/Results/ExecutionIndicatorView.swift @@ -31,6 +31,7 @@ struct ExecutionIndicatorView: View { var onCancel: (() -> Void)? @State private var showsBreakdown = false + @Environment(\.statusBarPlacement) private var placement /// 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 @@ -102,7 +103,7 @@ struct ExecutionIndicatorView: View { .accessibilityHint(String(localized: "Shows how the time was spent")) .accessibilityIdentifier("execution-duration") .help(breakdown.summary) - .popover(isPresented: $showsBreakdown, arrowEdge: .top) { + .popover(isPresented: $showsBreakdown, arrowEdge: placement.popoverArrowEdge) { QueryTimingPopover( breakdown: breakdown, explanation: timing.server != nil ? Self.serverExplanation : Self.clientExplanation diff --git a/apple/TablePro/Views/Results/ResultStatusBar.swift b/apple/TablePro/Views/Results/ResultStatusBar.swift index 205be5bc3f..9ae54b7a87 100644 --- a/apple/TablePro/Views/Results/ResultStatusBar.swift +++ b/apple/TablePro/Views/Results/ResultStatusBar.swift @@ -60,6 +60,7 @@ struct ResultStatusBar: View { @State private var highlightPopoverTabId: UUID? @State private var revealedExecutionTabId: UUID? @State private var showSelectionSummaryPopover = false + @Environment(\.statusBarPlacement) private var placement var body: some View { ViewThatFits(in: .horizontal) { @@ -343,7 +344,7 @@ struct ResultStatusBar: View { .accessibilityLabel(String(localized: "Columns")) .accessibilityValue(columnsAccessibilityValue) .accessibilityIdentifier("result-status-columns") - .popover(isPresented: $showColumnPopover, arrowEdge: .top) { + .popover(isPresented: $showColumnPopover, arrowEdge: placement.popoverArrowEdge) { ColumnVisibilityPopover( columns: columnState.visibilityColumns, hiddenColumns: columnState.hidden, @@ -382,7 +383,7 @@ struct ResultStatusBar: View { .accessibilityLabel(String(localized: "Highlight Rules")) .accessibilityValue(highlightAccessibilityValue) .accessibilityIdentifier("result-status-highlight") - .popover(isPresented: $showHighlightPopover, arrowEdge: .top) { + .popover(isPresented: $showHighlightPopover, arrowEdge: placement.popoverArrowEdge) { HighlightRulesPopover( columns: highlightState.columns, rules: highlightState.rules, diff --git a/apple/TablePro/Views/Results/SelectionSummaryReadout.swift b/apple/TablePro/Views/Results/SelectionSummaryReadout.swift index a244ccfdf2..bb73c06933 100644 --- a/apple/TablePro/Views/Results/SelectionSummaryReadout.swift +++ b/apple/TablePro/Views/Results/SelectionSummaryReadout.swift @@ -124,6 +124,7 @@ struct SelectionSummaryReadout: View { @ObservedObject var state: SelectionSummaryState let scopeNote: String? @Binding var isPopoverPresented: Bool + @Environment(\.statusBarPlacement) private var placement var body: some View { if let summary = state.summary { @@ -139,7 +140,7 @@ struct SelectionSummaryReadout: View { .accessibilityAddTraits(.updatesFrequently) .accessibilityIdentifier("result-status-selection-summary") .help(sentence(figures)) - .popover(isPresented: $isPopoverPresented, arrowEdge: .top) { + .popover(isPresented: $isPopoverPresented, arrowEdge: placement.popoverArrowEdge) { SelectionSummaryPopover(state: state, scopeNote: scopeNote) } // The flag outlives the button, so a summary that comes back would reopen the popover. diff --git a/apple/TablePro/Views/Results/StatusBarChrome.swift b/apple/TablePro/Views/Results/StatusBarChrome.swift index 4901bbe05d..89968963d3 100644 --- a/apple/TablePro/Views/Results/StatusBarChrome.swift +++ b/apple/TablePro/Views/Results/StatusBarChrome.swift @@ -28,19 +28,51 @@ private struct StatusBarMaterial: NSViewRepresentable { func updateNSView(_ nsView: NSVisualEffectView, context: Context) {} } +extension EnvironmentValues { + /// Set by the host that puts a bar above its content rather than below it. Read by the chrome + /// and by every control in the bar that opens a popover, so the bar never changes its own + /// contents to move. + @Entry var statusBarPlacement: StatusBarPlacement = .bottom +} + +extension StatusBarPlacement { + /// Toward the content the bar describes, so a popover never opens over the chrome on the bar's + /// far side: the editor, the tab strip or the toolbar. + var popoverArrowEdge: Edge { + switch self { + case .top: .bottom + case .bottom: .top + } + } + + /// The rule sits between the bar and the content it borders. + var dividerEdge: VerticalEdge { + switch self { + case .top: .bottom + case .bottom: .top + } + } +} + /// The material does not follow a custom window color, so over a themed backdrop the bar draws none. private struct StatusBarChromeModifier: ViewModifier { @ObservedObject private var themeEngine = ThemeEngine.shared @Environment(\.colorSchemeContrast) private var contrast + @Environment(\.statusBarPlacement) private var placement func body(content: Content) -> some View { let isThemed = ThemeBackdropState.isThemed(highContrast: contrast == .increased) return VStack(spacing: 0) { - Divider() + if placement.dividerEdge == .top { + Divider() + } content .padding(.horizontal, StatusBarChrome.horizontalPadding) .frame(maxWidth: .infinity, alignment: .leading) .frame(height: StatusBarChrome.height) + if placement.dividerEdge == .bottom { + Divider() + } } .background { if !isThemed { diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 30415b6c75..584e0f04a0 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -39,6 +39,8 @@ struct DataGridSection: View { 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("Show the result bar above the grid", isOn: $settings.resultBarAtTop) + .help(String(localized: "Moves the bar with the row count, view switcher and pages from below the results to above them.")) Picker("Default row sort:", selection: $settings.defaultSortBehavior) { ForEach(DefaultSortBehavior.allCases) { behavior in diff --git a/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift b/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift index ee978180f7..05a6453555 100644 --- a/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift +++ b/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift @@ -416,4 +416,44 @@ struct QueryResultPresentationTests { #expect(!seen.isEmpty) } + + @Test("The result bar sits below the result unless the setting moves it") + func statusBarBelowByDefault() { + var inputs = QueryResultInputs() + inputs.tabType = .table + inputs.tableName = "orders" + inputs.isFilterPanelVisible = true + let presentation = QueryResultPresentation(inputs: inputs) + + #expect(presentation.statusBarPlacement == .bottom) + #expect(presentation.showsStatusBar(at: .bottom)) + #expect(!presentation.showsStatusBar(at: .top)) + } + + @Test("Moved above the grid, the result bar is drawn at the top edge only and nothing else changes") + func statusBarMovesAboveTheGrid() { + for tabType in [TabType.table, .query] { + var inputs = QueryResultInputs() + inputs.tabType = tabType + inputs.tableName = "orders" + inputs.hasExecuted = true + inputs.hasActiveResultSet = true + inputs.activeResultHasColumns = true + inputs.loadedColumnCount = 3 + inputs.loadedRowCount = 5 + inputs.resultSetCount = 1 + inputs.isFilterPanelVisible = true + let below = QueryResultPresentation(inputs: inputs) + inputs.prefersStatusBarAtTop = true + let above = QueryResultPresentation(inputs: inputs) + + #expect(above.statusBarPlacement == .top) + #expect(above.showsStatusBar(at: .top)) + #expect(!above.showsStatusBar(at: .bottom)) + #expect(above.content == below.content) + #expect(above.showsFilterChrome == below.showsFilterChrome) + #expect(above.resultSetChooser == below.resultSetChooser) + #expect(above.showsErrorBanner == below.showsErrorBanner) + } + } } diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index d8a2412ad7..42af9af570 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -83,6 +83,23 @@ struct SettingsFieldDecodingTests { #expect(decoded.showsColumnTypesInHeader == true) } + @Test("Data Grid settings saved before the result bar could move keep it below the grid") + func resultBarAtTopDefaultsOff() throws { + let legacy = try decode(DataGridSettings.self, #"{"showRowNumbers":false}"#) + #expect(legacy.resultBarAtTop == false) + #expect(legacy.showRowNumbers == false) + #expect(DataGridSettings.default.resultBarAtTop == false) + + let bad = try decode(DataGridSettings.self, #"{"resultBarAtTop":"yes","showRowNumbers":false}"#) + #expect(bad.resultBarAtTop == false) + #expect(bad.showRowNumbers == false) + + var chosen = DataGridSettings.default + chosen.resultBarAtTop = true + let decoded = try decode(DataGridSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.resultBarAtTop == true) + } + @Test("Tab settings saved before located titles keep bare table names, and the choice round-trips") func titleShowsLocationDefaultsOff() throws { let legacy = try decode(TabSettings.self, #"{"enablePreviewTabs":false,"overflow":"rows"}"#) diff --git a/apple/TableProTests/Views/Main/ResultStatusBarLayoutTests.swift b/apple/TableProTests/Views/Main/ResultStatusBarLayoutTests.swift index 6afd854e6a..6e7bb5e46b 100644 --- a/apple/TableProTests/Views/Main/ResultStatusBarLayoutTests.swift +++ b/apple/TableProTests/Views/Main/ResultStatusBarLayoutTests.swift @@ -103,6 +103,37 @@ struct ResultStatusBarLayoutTests { return host.fittingSize.height } + @Test("A bar above the content draws its rule on its lower edge and opens its popovers downward") + func topBarFacesTheContentBelowIt() { + #expect(StatusBarPlacement.top.dividerEdge == .bottom) + #expect(StatusBarPlacement.top.popoverArrowEdge == .bottom) + #expect(StatusBarPlacement.bottom.dividerEdge == .top) + #expect(StatusBarPlacement.bottom.popoverArrowEdge == .top) + } + + /// Moving the bar moves its rule and nothing else, so the grid below it gets the same height + /// back and the bar drops a tier at the same widths it always did. + @Test("Placed above the grid, the bar keeps its height and its width") + func topPlacementKeepsTheFootprint() { + let bar = makeBar( + rowCount: 1_000, + hasColumns: true, + tabType: .table, + viewMode: .data, + pagination: PaginationState(totalRowCount: 5_000, pageSize: 1_000) + ) + let below = NSHostingView(rootView: bar) + let above = NSHostingView(rootView: bar.environment(\.statusBarPlacement, .top)) + below.frame = NSRect(x: 0, y: 0, width: 900, height: 200) + above.frame = NSRect(x: 0, y: 0, width: 900, height: 200) + below.layoutSubtreeIfNeeded() + above.layoutSubtreeIfNeeded() + + #expect(above.fittingSize.height == below.fittingSize.height) + #expect(above.fittingSize.width == below.fittingSize.width) + #expect(above.fittingSize.height >= StatusBarChrome.height) + } + /// A fresh query tab used to render an 8pt sliver that snapped to 28pt on the first execution, /// shoving the grid up by 20pt every time. @Test("The bar is the same height before and after a result arrives") From a46e72b2b12645f5fc98eecef418930a1d681ee2 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 17:14:50 +0700 Subject: [PATCH 086/123] feat(filter): edit and apply the sort from the table filter panel Two Data Grid settings, both off by default, so the panel stays as it was: - Show sort criteria in the filter panel: a Builder | Text switch where the engine takes a raw SQL filter, a Sort By section seeded from the tab's sort, and Apply Filter & Sort, which runs the rows and the sort in one reload. A Criteria Edited label shows while the draft differs from what the rows on screen were fetched with. A header sort still runs at once and the section follows it. - Open the filter panel with each table: the panel opens when a table opens. Text mode keeps one raw row, so Builder to Text writes the enabled rows' WHERE condition and Text to Builder keeps the text as that row; nothing is parsed. The mode persists with the tab's filter state and the table's saved filters. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Core/Coordinators/FilterCoordinator.swift | 167 ++++++++-- .../Database/TabFilterState+Criteria.swift | 174 +++++++++++ .../Database/TabFilterState+Editing.swift | 8 + .../Models/Database/TableFilter.swift | 20 +- .../Models/Settings/AppSettings.swift | 20 +- apple/TablePro/Models/UI/FilterState.swift | 17 +- .../Views/Filter/FilterPanelHosting.swift | 27 ++ .../Views/Filter/FilterPanelView.swift | 184 +++++++++++- .../Views/Filter/FilterSortSection.swift | 161 ++++++++++ .../Views/Filter/QueryTabFilterPanel.swift | 36 ++- .../Views/Main/MainContentCoordinator.swift | 3 + .../Settings/Sections/DataGridSection.swift | 8 + .../Models/FilterCriteriaStateTests.swift | 275 +++++++++++++++++ .../Views/Filter/FilterSortPanelTests.swift | 284 ++++++++++++++++++ 14 files changed, 1339 insertions(+), 45 deletions(-) create mode 100644 apple/TablePro/Models/Database/TabFilterState+Criteria.swift create mode 100644 apple/TablePro/Views/Filter/FilterSortSection.swift create mode 100644 apple/TableProTests/Models/FilterCriteriaStateTests.swift create mode 100644 apple/TableProTests/Views/Filter/FilterSortPanelTests.swift diff --git a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift index 9c31d291c2..c478bb9343 100644 --- a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift @@ -48,17 +48,22 @@ final class FilterCoordinator: ObservableObject { } /// Builds the query first and writes the filter state only once it exists, so a refusal leaves - /// the panel, the commit and the rows on screen as they were, with the reason in their place. + /// the panel, the commit, the sort and the rows on screen as they were, with the reason in their + /// place. A `sort` is written with the filters, so both land in the one reload or neither does. private func commitFilters( _ filters: [TableFilter], logicMode: FilterLogicMode?, tabIndex: Int, tableName: String, - adopting proposed: TabFilterState? = nil + adopting proposed: TabFilterState? = nil, + sort: SortState? = nil ) { guard tabIndex < parent.tabManager.tabs.count else { return } - let tab = parent.tabManager.tabs[tabIndex] + var tab = parent.tabManager.tabs[tabIndex] + if let sort { + tab.sortState = sort + } var next = proposed ?? tab.filterState if let logicMode { next.filterLogicMode = logicMode @@ -69,18 +74,12 @@ final class FilterCoordinator: ObservableObject { } let queryColumns = parent.queryColumns(for: tab) - guard let newQuery = parent.queryBuilder.buildFilteredQuery( - tableName: tableName, - schemaName: tab.tableContext.schemaName, - filters: filters, + guard let newQuery = filteredOrBaseQuery( + filters, logicMode: next.filterLogicMode, - sortState: querySortState(for: tab), - columns: queryColumns.columns, - columnTypes: queryColumns.columnTypes, - selectColumns: parent.selectColumns(for: tab), - unloadedValues: parent.unloadedValuePlan(for: tab), - limit: tab.pagination.pageSize, - offset: 0 + tab: tab, + tableName: tableName, + queryColumns: queryColumns ) else { let message = FilterSQLGenerator.refusalMessage(for: filters, databaseType: parent.connection.type) ?? String(localized: "This database cannot filter rows with these conditions.") @@ -96,11 +95,97 @@ final class FilterCoordinator: ObservableObject { $0.pagination.reset() $0.content.query = newQuery $0.filterState = next + if let sort { + $0.sortState = sort + $0.hasUserInteraction = true + } + } + if sort != nil { + parent.existingGridModel(forTab: tab.id)?.sortStateDidChange() } saveLastFilters(of: parent.tabManager.tabs[tabIndex]) parent.runQuery(viewport: .firstRow) } + /// No rows to run is the table's plain query, which Apply Filter & Sort reaches to change the + /// sort alone: a driver that builds its own filtered queries may refuse an empty set. + private func filteredOrBaseQuery( + _ filters: [TableFilter], + logicMode: FilterLogicMode, + tab: QueryTab, + tableName: String, + queryColumns: (columns: [String], columnTypes: [ColumnType]) + ) -> String? { + guard !filters.isEmpty else { + return parent.queryBuilder.buildBaseQuery( + tableName: tableName, + schemaName: tab.tableContext.schemaName, + sortState: querySortState(for: tab), + columns: queryColumns.columns, + selectColumns: parent.selectColumns(for: tab), + unloadedValues: parent.unloadedValuePlan(for: tab), + limit: tab.pagination.pageSize, + offset: 0 + ) + } + return parent.queryBuilder.buildFilteredQuery( + tableName: tableName, + schemaName: tab.tableContext.schemaName, + filters: filters, + logicMode: logicMode, + sortState: querySortState(for: tab), + columns: queryColumns.columns, + columnTypes: queryColumns.columnTypes, + selectColumns: parent.selectColumns(for: tab), + unloadedValues: parent.unloadedValuePlan(for: tab), + limit: tab.pagination.pageSize, + offset: 0 + ) + } + + /// Apply Filter & Sort: every enabled, complete row and the Sort By draft, in one reload behind + /// one discard guard. With no row to run, the filters stop and the rows stay in the panel, as + /// Clear leaves them. A draft equal to the tab's sort writes nothing, so a default sort keeps + /// its source. + func applyFiltersAndSort() { + guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, + let tableName = tab.tableContext.tableName else { return } + + let capturedTabIndex = tabIndex + let capturedTableName = tableName + parent.confirmDiscardChangesIfNeeded(action: .filter) { [weak self] confirmed in + guard let self, confirmed else { return } + guard capturedTabIndex < parent.tabManager.tabs.count else { return } + let current = parent.tabManager.tabs[capturedTabIndex] + var next = current.filterState + next.commit = TabFilterState.resolve(.all, in: next.filters).isEmpty ? nil : .all + let sort = sortToApply(next.sortDraft, for: current) + next.sortDraft = nil + commitFilters( + next.appliedFilters, + logicMode: nil, + tabIndex: capturedTabIndex, + tableName: capturedTableName, + adopting: next, + sort: sort + ) + } + } + + /// The sort a draft asks for, or nil when it changes nothing or the engine cannot sort a table. + private func sortToApply(_ draft: [FilterSortCriterion]?, for tab: QueryTab) -> SortState? { + guard let draft, parent.supportsColumnSort else { return nil } + let columns = parent.queryColumns(for: tab).columns + guard draft != TabFilterState.sortCriteria(from: tab.sortState, columns: columns) else { return nil } + return TabFilterState.sortState(from: draft, columns: columns) + } + + /// The tab's sort as the Sort By section shows it. + var selectedTabAppliedSortCriteria: [FilterSortCriterion] { + guard let tab = parent.tabManager.selectedTab else { return [] } + return TabFilterState.sortCriteria(from: tab.sortState, columns: parent.queryColumns(for: tab).columns) + } + /// Stops filtering and keeps the rows in the panel, so Apply brings them back. func clearAppliedFiltersAndReload() { unsetFilters(removingRows: false) @@ -145,6 +230,7 @@ final class FilterCoordinator: ObservableObject { $0.filterState.executedLogicMode = nil if removingRows { $0.filterState.filters = [] + $0.filterState.leaveTextMode() } } /// Saved rather than deleted, because the rows left in the panel are still the table's @@ -530,8 +616,9 @@ final class FilterCoordinator: ObservableObject { } else { saved = PersistedFilterState(filters: [], isApplied: false) } + let opensPanel = AppSettingsManager.shared.dataGrid.opensFilterPanelForTables mutateFilterState(at: index) { state in - state = Self.resolvedRestoredState(settings: settings, saved: saved, current: state) + state = Self.resolvedRestoredState(settings: settings, saved: saved, current: state, opensPanel: opensPanel) } } @@ -540,10 +627,14 @@ final class FilterCoordinator: ObservableObject { /// The commit is never fabricated. Setting it to `.all` regardless of what was saved is what /// made a row the reader typed and did not apply count as applied the moment it became valid, /// so the status bar reported it and the next page turn ran it. + /// + /// `opensPanel` is `DataGridSettings.opensFilterPanelForTables`. This runs as a table opens, never + /// on a tab switch, so the panel opens once and stays closed if the reader closes it. static func resolvedRestoredState( settings: FilterSettings, saved: PersistedFilterState, - current: TabFilterState + current: TabFilterState, + opensPanel: Bool = false ) -> TabFilterState { var state = current let restored = settings.restoreBehavior.savesToDisk ? saved.filters : [] @@ -552,8 +643,11 @@ final class FilterCoordinator: ObservableObject { state.commit = restored.isEmpty || !appliesRestored ? nil : .all state.executedFilters = [] state.executedLogicMode = nil - state.isVisible = settings.alwaysShowPanel || !restored.isEmpty + state.isVisible = settings.alwaysShowPanel || opensPanel || !restored.isEmpty state.filterLogicMode = restored.isEmpty ? state.filterLogicMode : saved.logicMode + state.textModeOrigin = nil + state.editMode = restored.isEmpty ? .builder : saved.editMode + state.sortDraft = nil return state } @@ -567,18 +661,9 @@ final class FilterCoordinator: ObservableObject { func generateFilterPreviewSQL(databaseType: DatabaseType) -> String { let state = selectedTabFilterState - guard let dialect = PluginManager.shared.sqlDialect(for: databaseType) else { + guard let generator = filterSQLGenerator(databaseType: databaseType) else { return "-- Filters are applied natively" } - let queryColumns = parent.tabManager.selectedTab.map { parent.queryColumns(for: $0) } - let generator = FilterSQLGenerator( - dialect: dialect, - columns: queryColumns?.columns ?? [], - columnTypes: queryColumns?.columnTypes ?? [], - stringLiteralPrefix: SQLStringLiteralPrefix.forDatabaseType(databaseType), - databaseType: databaseType, - stringEscapes: SQLLexicalResolver.stringEscapes(for: databaseType, connectionId: parent.connectionId) - ) let filtersToPreview = filtersForPreview(in: state) if filtersToPreview.isEmpty && !state.filters.isEmpty { @@ -601,6 +686,32 @@ final class FilterCoordinator: ObservableObject { state.filters.filter { $0.isEnabled && $0.isValid } } + /// The generator the preview uses, typed from the selected tab's columns. Nil on an engine that + /// does not filter with SQL. + private func filterSQLGenerator(databaseType: DatabaseType) -> FilterSQLGenerator? { + guard let dialect = PluginManager.shared.sqlDialect(for: databaseType) else { return nil } + let queryColumns = parent.tabManager.selectedTab.map { parent.queryColumns(for: $0) } + return FilterSQLGenerator( + dialect: dialect, + columns: queryColumns?.columns ?? [], + columnTypes: queryColumns?.columnTypes ?? [], + stringLiteralPrefix: SQLStringLiteralPrefix.forDatabaseType(databaseType), + databaseType: databaseType, + stringEscapes: SQLLexicalResolver.stringEscapes(for: databaseType, connectionId: parent.connectionId) + ) + } + + /// The preview's WHERE clause for the enabled rows, without its keyword, for Text mode to start from. + func filterConditionText(for filters: [TableFilter], logicMode: FilterLogicMode) -> String? { + guard let generator = filterSQLGenerator(databaseType: parent.connection.type), + let whereClause = generator.generateWhereClause( + from: filters.filter(\.isEnabled), + logicMode: logicMode + ) else { return nil } + let keyword = "WHERE " + return whereClause.hasPrefix(keyword) ? String(whereClause.dropFirst(keyword.count)) : whereClause + } + // MARK: - Private private func mutateSelectedTabFilterState(_ mutate: (inout TabFilterState) -> Void) { @@ -622,6 +733,8 @@ extension FilterCoordinator: FilterPanelActions { } } +extension FilterCoordinator: FilterCriteriaActions {} + extension FilterCoordinator: FilterSQLPreviewing { var filterPreviewDatabaseType: DatabaseType { parent.connection.type diff --git a/apple/TablePro/Models/Database/TabFilterState+Criteria.swift b/apple/TablePro/Models/Database/TabFilterState+Criteria.swift new file mode 100644 index 0000000000..0f51491924 --- /dev/null +++ b/apple/TablePro/Models/Database/TabFilterState+Criteria.swift @@ -0,0 +1,174 @@ +// +// TabFilterState+Criteria.swift +// TablePro +// + +import Foundation + +/// How the filter panel edits its conditions: a row per condition, or one typed WHERE condition. +enum FilterEditMode: String, Codable, Hashable { + case builder + case text +} + +/// One key of the Sort By section. Keyed by column name, because a column sorts once. +struct FilterSortCriterion: Identifiable, Equatable, Hashable { + var columnName: String + var direction: SortDirection + + var id: String { columnName } +} + +/// What the builder held when Text mode replaced it, so a round trip that typed nothing loses nothing. +struct FilterTextModeOrigin: Equatable, Hashable { + let filters: [TableFilter] + let logicMode: FilterLogicMode + let text: String +} + +internal extension TabFilterState { + // MARK: - Builder and Text + + /// Text mode holds exactly one raw row. Anything else put rows in from outside the editor (a + /// cell's Filter menu, a preset, a reference jump), and those rows only make sense as rows. + var effectiveEditMode: FilterEditMode { + guard editMode == .text, filters.count == 1, filters[0].isRawSQL else { return .builder } + return .text + } + + /// The typed condition Text mode edits. + var textCondition: String { + effectiveEditMode == .text ? filters[0].value : "" + } + + mutating func setTextCondition(_ text: String) { + guard effectiveEditMode == .text else { return } + filters[0].value = text + } + + /// Replaces the rows with one raw row holding `condition`, the WHERE text the enabled rows + /// produce. No SQL is parsed either way, so the rows are kept aside for a return that typed + /// nothing. A solo commit names a row that is gone, so what was applied reads as every row. + /// Returns the raw row's id, for the editor to take focus. + @discardableResult + mutating func enterTextMode(condition: String) -> UUID? { + guard effectiveEditMode == .builder else { return filters.first?.id } + let row = TableFilter.rawCondition(condition) + textModeOrigin = FilterTextModeOrigin( + filters: filters, + logicMode: filterLogicMode, + text: condition + ) + filters = [row] + filterLogicMode = .and + if commit != nil { + commit = .all + } + editMode = .text + return row.id + } + + /// Keeps what was typed as one raw-SQL row. Text that is still what the rows produced brings + /// the rows back instead, with their enabled flags and logic mode. The commit stays as it is + /// now: an Apply or Clear in Text mode changed what is running, and a rerun reads that from + /// `executedFilters`, never from the rows. + mutating func enterBuilderMode() { + defer { leaveTextMode() } + guard effectiveEditMode == .text, + let origin = textModeOrigin, + origin.text == textCondition else { return } + filters = origin.filters + filterLogicMode = origin.logicMode + } + + /// Rows put in from outside the editor are builder rows. + mutating func leaveTextMode() { + editMode = .builder + textModeOrigin = nil + } + + // MARK: - Sort draft + + /// What the Sort By section shows: the draft, or the sort the rows were fetched with. + func sortCriteria(applied: [FilterSortCriterion]) -> [FilterSortCriterion] { + sortDraft ?? applied + } + + /// Every edit starts from what the section shows, so the first one seeds the draft from the tab. + mutating func editSortDraft(applied: [FilterSortCriterion], _ edit: (inout [FilterSortCriterion]) -> Void) { + var draft = sortCriteria(applied: applied) + edit(&draft) + sortDraft = draft + } + + /// Adds the first column no key sorts by yet, so a column never sorts twice. + mutating func addSortCriterion( + applied: [FilterSortCriterion], + columns: [String], + direction: SortDirection + ) { + let used = Set(sortCriteria(applied: applied).map(\.columnName)) + guard let column = columns.first(where: { !used.contains($0) }) else { return } + editSortDraft(applied: applied) { $0.append(FilterSortCriterion(columnName: column, direction: direction)) } + } + + mutating func removeSortCriterion(_ columnName: String, applied: [FilterSortCriterion]) { + editSortDraft(applied: applied) { $0.removeAll { $0.columnName == columnName } } + } + + /// A column another key already sorts by is refused, so the keys stay unique. + mutating func updateSortCriterion( + _ columnName: String, + to replacement: FilterSortCriterion, + applied: [FilterSortCriterion] + ) { + editSortDraft(applied: applied) { draft in + guard let index = draft.firstIndex(where: { $0.columnName == columnName }) else { return } + let takenElsewhere = draft.indices.contains { $0 != index && draft[$0].columnName == replacement.columnName } + guard !takenElsewhere else { return } + draft[index] = replacement + } + } + + // MARK: - Edited state + + /// Whether Apply Filter & Sort would fetch rows other than the ones on screen: the rows Apply + /// runs (every enabled, complete row) against the filters the rows were fetched with, and the + /// sort draft against the tab's sort. An incomplete or unchecked row runs nothing, so it edits + /// nothing. + func criteriaDiffer(fromAppliedSort appliedSort: [FilterSortCriterion]) -> Bool { + filterDraftDiffersFromRunning || (sortDraft.map { $0 != appliedSort } ?? false) + } + + var filterDraftDiffersFromRunning: Bool { + let draft = Self.resolve(.all, in: filters) + let running = rerunFilters + guard draft.count == running.filters.count, + zip(draft, running.filters).allSatisfy({ $0.hasSameCondition(as: $1) }) else { return true } + return draft.count > 1 && filterLogicMode != running.logicMode + } + + // MARK: - Sort conversion + + /// The tab's sort as section keys, named from the grid's columns. A key whose column cannot be + /// named, or that repeats a column, has nothing the section could show. + static func sortCriteria(from sortState: SortState, columns: [String]) -> [FilterSortCriterion] { + var seen = Set() + return sortState.columns.compactMap { column in + guard let name = SortColumnResolver.columnName(for: column, displayColumns: columns), + seen.insert(name).inserted else { return nil } + return FilterSortCriterion(columnName: name, direction: column.direction) + } + } + + /// The section's keys as the sort a table query carries, each stamped with its name and its + /// position in `columns`. A key on a column the result no longer has is dropped rather than + /// pointed at another column. + static func sortState(from criteria: [FilterSortCriterion], columns: [String]) -> SortState { + let sortColumns = criteria.compactMap { criterion -> SortColumn? in + guard let index = columns.firstIndex(of: criterion.columnName) else { return nil } + return SortColumn(columnIndex: index, direction: criterion.direction, columnName: criterion.columnName) + } + return SortState(columns: sortColumns, source: .user) + } +} diff --git a/apple/TablePro/Models/Database/TabFilterState+Editing.swift b/apple/TablePro/Models/Database/TabFilterState+Editing.swift index 1a6f82ad6a..733323a00f 100644 --- a/apple/TablePro/Models/Database/TabFilterState+Editing.swift +++ b/apple/TablePro/Models/Database/TabFilterState+Editing.swift @@ -66,6 +66,7 @@ internal extension TabFilterState { filterOperator: settings.defaultOperator.toFilterOperator() )) isVisible = true + leaveTextMode() } static func crossColumnSearchFilters(term: String, columns: [String]) -> [TableFilter] { @@ -79,6 +80,7 @@ internal extension TabFilterState { commit = .all isVisible = true filterLogicMode = .and + leaveTextMode() } mutating func applySingleFilter(_ filter: TableFilter) { @@ -86,6 +88,7 @@ internal extension TabFilterState { filters = [filter] commit = .all isVisible = true + leaveTextMode() } @discardableResult @@ -156,13 +159,17 @@ internal extension TabFilterState { } } + /// The tab moves to another table, so a sort draft on this one's columns goes too. mutating func clearFilters() { filters = [] commit = nil + sortDraft = nil + leaveTextMode() } mutating func loadPreset(_ preset: FilterPreset) { filters = preset.filters + leaveTextMode() } static func filterMove( @@ -247,6 +254,7 @@ internal extension TabFilterState { } next.commit = .all next.isVisible = true + next.leaveTextMode() return next } } diff --git a/apple/TablePro/Models/Database/TableFilter.swift b/apple/TablePro/Models/Database/TableFilter.swift index 87fcaaf900..6a61a0f025 100644 --- a/apple/TablePro/Models/Database/TableFilter.swift +++ b/apple/TablePro/Models/Database/TableFilter.swift @@ -391,6 +391,20 @@ struct TabFilterState: Equatable, Hashable, Codable { /// filtered query, so a tab that restored filters and has not loaded yet reruns those. var executedLogicMode: FilterLogicMode? + /// Whether the panel edits builder rows or one typed condition. Only a panel that also holds the + /// sort offers the switch (`DataGridSettings.showsSortInFilterPanel`); every other panel reads + /// `effectiveEditMode`, which falls back to the rows. + var editMode: FilterEditMode = .builder + + /// The builder rows Text mode replaced, so switching back before typing anything returns them. + /// Deliberately not persisted: a restored tab has no rows to return to. + var textModeOrigin: FilterTextModeOrigin? + + /// The Sort By section's edits, nil while it shows the tab's sort as it is. A header click + /// sorts at once and clears it, so the section follows the header. Not persisted: the sort the + /// rows were fetched with is the tab's `SortState`, and a draft is only what Apply would run. + var sortDraft: [FilterSortCriterion]? + init(isVisible: Bool = false) { self.filters = [] self.commit = nil @@ -401,7 +415,7 @@ struct TabFilterState: Equatable, Hashable, Codable { } enum CodingKeys: String, CodingKey { - case filters, commit, isVisible, filterLogicMode, keyPattern, keyTypeScope + case filters, commit, isVisible, filterLogicMode, keyPattern, keyTypeScope, editMode } init(from decoder: Decoder) throws { @@ -412,6 +426,7 @@ struct TabFilterState: Equatable, Hashable, Codable { self.filterLogicMode = try container.decodeIfPresent(FilterLogicMode.self, forKey: .filterLogicMode) ?? .and self.keyPattern = try container.decodeIfPresent(String.self, forKey: .keyPattern) ?? "" self.keyTypeScope = try container.decodeIfPresent(String.self, forKey: .keyTypeScope) + self.editMode = (try? container.decodeIfPresent(FilterEditMode.self, forKey: .editMode)) ?? .builder } var appliedFilters: [TableFilter] { @@ -449,7 +464,8 @@ struct TabFilterState: Equatable, Hashable, Codable { PersistedFilterState( filters: filters.filter(\.isValid), logicMode: filterLogicMode, - isApplied: commit != nil + isApplied: commit != nil, + editMode: effectiveEditMode ) } diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index acc91b2bfe..7ec75a24b0 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -128,6 +128,10 @@ struct DataGridSettings: Codable, Equatable { var showInvisibleCharacters: Bool var showsColumnTypesInHeader: Bool var resultBarAtTop: Bool + /// The filter panel of a table tab also edits the sort, offers a Text mode and applies both at once. + var showsSortInFilterPanel: Bool + /// A table tab opens with its filter panel showing. + var opensFilterPanelForTables: Bool static let `default` = DataGridSettings( rowHeight: .normal, @@ -146,7 +150,9 @@ struct DataGridSettings: Codable, Equatable { rowCopyFormat: .rows, showInvisibleCharacters: true, showsColumnTypesInHeader: false, - resultBarAtTop: false + resultBarAtTop: false, + showsSortInFilterPanel: false, + opensFilterPanelForTables: false ) init( @@ -166,7 +172,9 @@ struct DataGridSettings: Codable, Equatable { rowCopyFormat: RowCopyFormat = .rows, showInvisibleCharacters: Bool = true, showsColumnTypesInHeader: Bool = false, - resultBarAtTop: Bool = false + resultBarAtTop: Bool = false, + showsSortInFilterPanel: Bool = false, + opensFilterPanelForTables: Bool = false ) { self.rowHeight = rowHeight self.dateFormat = dateFormat @@ -185,6 +193,8 @@ struct DataGridSettings: Codable, Equatable { self.showInvisibleCharacters = showInvisibleCharacters self.showsColumnTypesInHeader = showsColumnTypesInHeader self.resultBarAtTop = resultBarAtTop + self.showsSortInFilterPanel = showsSortInFilterPanel + self.opensFilterPanelForTables = opensFilterPanelForTables } init(from decoder: Decoder) throws { @@ -216,6 +226,12 @@ struct DataGridSettings: Codable, Equatable { .showsColumnTypesInHeader, default: fallback.showsColumnTypesInHeader ) resultBarAtTop = container.decodeSetting(.resultBarAtTop, default: fallback.resultBarAtTop) + showsSortInFilterPanel = container.decodeSetting( + .showsSortInFilterPanel, default: fallback.showsSortInFilterPanel + ) + opensFilterPanelForTables = container.decodeSetting( + .opensFilterPanelForTables, default: fallback.opensFilterPanelForTables + ) } // MARK: - Validated Properties diff --git a/apple/TablePro/Models/UI/FilterState.swift b/apple/TablePro/Models/UI/FilterState.swift index 95cf8b1265..bb2bf030f2 100644 --- a/apple/TablePro/Models/UI/FilterState.swift +++ b/apple/TablePro/Models/UI/FilterState.swift @@ -63,11 +63,20 @@ struct PersistedFilterState: Codable, Equatable { /// Absent in every file written before this existed, which decodes to `true`: only an applied /// set was ever saved. var isApplied: Bool - - init(filters: [TableFilter], logicMode: FilterLogicMode = .and, isApplied: Bool = true) { + /// Whether the rows were saved from the panel's Text mode. Absent in every older file, which + /// decodes to Builder; an older build ignores the key and shows the one raw row it holds. + var editMode: FilterEditMode + + init( + filters: [TableFilter], + logicMode: FilterLogicMode = .and, + isApplied: Bool = true, + editMode: FilterEditMode = .builder + ) { self.filters = filters self.logicMode = logicMode self.isApplied = isApplied + self.editMode = editMode } init(from decoder: Decoder) throws { @@ -76,16 +85,18 @@ struct PersistedFilterState: Codable, Equatable { self.filters = filters self.logicMode = (try? keyed.decode(FilterLogicMode.self, forKey: .logicMode)) ?? .and self.isApplied = (try? keyed.decode(Bool.self, forKey: .isApplied)) ?? true + self.editMode = (try? keyed.decode(FilterEditMode.self, forKey: .editMode)) ?? .builder return } let single = try decoder.singleValueContainer() self.filters = try single.decode([TableFilter].self) self.logicMode = .and self.isApplied = true + self.editMode = .builder } private enum CodingKeys: String, CodingKey { - case filters, logicMode, isApplied + case filters, logicMode, isApplied, editMode } } diff --git a/apple/TablePro/Views/Filter/FilterPanelHosting.swift b/apple/TablePro/Views/Filter/FilterPanelHosting.swift index 1e35f2230f..e3d16e83de 100644 --- a/apple/TablePro/Views/Filter/FilterPanelHosting.swift +++ b/apple/TablePro/Views/Filter/FilterPanelHosting.swift @@ -44,6 +44,31 @@ internal protocol FilterPresetStoring: AnyObject { extension FilterPresetStorage: FilterPresetStoring {} +/// What a panel that holds the sort as well asks of its host. +@MainActor +internal protocol FilterCriteriaActions: AnyObject { + /// Runs the panel's rows and its sort draft in one reload. + func applyFiltersAndSort() + /// The condition these rows produce, without the WHERE keyword: empty when none is complete, + /// nil when one cannot be written for this engine. + func filterConditionText(for filters: [TableFilter], logicMode: FilterLogicMode) -> String? +} + +/// The Builder | Text switch, the Sort By section and the combined Apply, for a table tab under +/// `DataGridSettings.showsSortInFilterPanel`. +internal struct FilterCriteriaConfiguration { + /// Text mode needs a WHERE condition the engine runs as written. + var offersTextMode: Bool + /// Nil on an engine that cannot order a table by a column, which hides the section. + var sortColumns: [String]? + /// The tab's sort, which the section shows until it is edited. + var appliedSort: [FilterSortCriterion] + var newSortDirection: SortDirection + let actions: any FilterCriteriaActions + + var showsSort: Bool { sortColumns != nil } +} + internal struct FilterPanelConfiguration { var columns: [String] var primaryKeyColumn: String? @@ -57,4 +82,6 @@ internal struct FilterPanelConfiguration { var offersMatchAny = true var sqlPreview: (any FilterSQLPreviewing)? var presetStore: (any FilterPresetStoring)? + /// Nil draws the filter-only panel. + var criteria: FilterCriteriaConfiguration? } diff --git a/apple/TablePro/Views/Filter/FilterPanelView.swift b/apple/TablePro/Views/Filter/FilterPanelView.swift index ddb50e4bda..aec35ae3ad 100644 --- a/apple/TablePro/Views/Filter/FilterPanelView.swift +++ b/apple/TablePro/Views/Filter/FilterPanelView.swift @@ -12,19 +12,46 @@ struct FilterPanelView: View { @State private var showSavePresetAlert = false @State private var newPresetName = "" @State private var focusedFilterId: UUID? + @State private var textModeRefusal: String? private let maxFilterListHeight: CGFloat = 200 @State private var filterRowsHeight: CGFloat = 0 + /// Three lines of the value font, so a condition written over several lines stays readable. + private let textConditionHeight: CGFloat = 60 + + private var criteria: FilterCriteriaConfiguration? { + configuration.criteria + } + + /// Text mode only where the host offers it. Any other panel shows the rows, whatever the state + /// says, so turning the setting off brings back the panel as it was. + private var editMode: FilterEditMode { + criteria?.offersTextMode == true ? state.effectiveEditMode : .builder + } + var body: some View { VStack(spacing: 0) { filterHeader Divider() - if !state.filters.isEmpty { + if editMode == .text { + textConditionEditor + } else if !state.filters.isEmpty { filterList } + + if let criteria, let sortColumns = criteria.sortColumns { + Divider() + + FilterSortSection( + state: $state, + columns: sortColumns, + appliedSort: criteria.appliedSort, + newSortDirection: criteria.newSortDirection + ) + } } .paneBarBackground(Color(nsColor: .windowBackgroundColor)) .focusSection() @@ -51,7 +78,7 @@ struct FilterPanelView: View { private var filterHeader: some View { HStack(spacing: 8) { - if !state.filters.isEmpty { + if editMode == .builder, !state.filters.isEmpty { TristateCheckbox( state: TristateCheckbox.State(allEnabled: state.allEnabledState), action: toggleAllFiltersEnabled @@ -77,6 +104,13 @@ struct FilterPanelView: View { Spacer() + if let criteria, state.criteriaDiffer(fromAppliedSort: criteria.appliedSort) { + Text("Criteria Edited") + .font(.caption) + .foregroundStyle(.secondary) + .help(String(localized: "The rows on screen were fetched with different filters or sorting")) + } + filterOptionsMenu Button("Clear") { @@ -88,14 +122,22 @@ struct FilterPanelView: View { .disabled(!state.hasAppliedFilters) .help(String(localized: "Clear applied filters without removing filter rows")) - Button("Apply") { - applyAllValidFilters() + if let criteria { + criteriaApplyButton(criteria) + + if criteria.offersTextMode { + editModePicker(criteria) + } + } else { + Button("Apply") { + applyAllValidFilters() + } + .buttonStyle(.borderedProminent) + .controlSize(.small) + .keyboardShortcut(.return, modifiers: .command) + .disabled(enabledValidFilterCount == 0 && !state.hasAppliedFilters) + .help(String(localized: "Apply active filters (Cmd+Return)")) } - .buttonStyle(.borderedProminent) - .controlSize(.small) - .keyboardShortcut(.return, modifiers: .command) - .disabled(enabledValidFilterCount == 0 && !state.hasAppliedFilters) - .help(String(localized: "Apply active filters (Cmd+Return)")) } .padding(.horizontal, 12) .padding(.vertical, 8) @@ -113,6 +155,123 @@ struct FilterPanelView: View { } } + /// Enabled whenever pressing it would change the rows, and whenever filters run, as the plain Apply is. + private func criteriaApplyButton(_ criteria: FilterCriteriaConfiguration) -> some View { + let changesRows = state.criteriaDiffer(fromAppliedSort: criteria.appliedSort) + return Button { + applyAllValidFilters() + } label: { + if criteria.showsSort { + Text("Apply Filter & Sort") + } else { + Text("Apply") + } + } + .buttonStyle(.borderedProminent) + .controlSize(.small) + .keyboardShortcut(.return, modifiers: .command) + .disabled(!changesRows && enabledValidFilterCount == 0 && !state.hasAppliedFilters) + .help(criteria.showsSort + ? String(localized: "Apply the filters and the sort (Cmd+Return)") + : String(localized: "Apply active filters (Cmd+Return)")) + } + + private func editModePicker(_ criteria: FilterCriteriaConfiguration) -> some View { + Picker(String(localized: "Filter editing mode"), selection: editModeBinding(criteria)) { + Text("Builder").tag(FilterEditMode.builder) + Text("Text").tag(FilterEditMode.text) + } + .pickerStyle(.segmented) + .controlSize(.small) + .labelsHidden() + .fixedSize() + .help(String(localized: "Edit the filter as rows or as one WHERE condition")) + .alert( + String(localized: "Can't Switch to Text"), + isPresented: Binding( + get: { textModeRefusal != nil }, + set: { if !$0 { textModeRefusal = nil } } + ) + ) { + Button("OK", role: .cancel) {} + } message: { + Text(textModeRefusal ?? "") + } + } + + private func editModeBinding(_ criteria: FilterCriteriaConfiguration) -> Binding { + Binding( + get: { editMode }, + set: { switchEditMode(to: $0, criteria: criteria) } + ) + } + + /// Builder to Text starts the editor from the enabled rows' WHERE condition; Text to Builder + /// keeps the text as one raw row. Nothing is parsed, so neither direction can lose a condition. + private func switchEditMode(to mode: FilterEditMode, criteria: FilterCriteriaConfiguration) { + guard mode != editMode else { return } + var next = state + switch mode { + case .text: + let logicMode = configuration.offersMatchAny ? next.filterLogicMode : .and + guard let condition = criteria.actions.filterConditionText(for: next.filters, logicMode: logicMode) else { + textModeRefusal = String(localized: "These filters cannot be written as one condition for this database.") + return + } + focusedFilterId = next.enterTextMode(condition: condition) + case .builder: + next.enterBuilderMode() + focusedFilterId = next.filters.last?.id + } + state = next + } + + @ViewBuilder + private var textConditionEditor: some View { + if let row = state.filters.first { + HStack(alignment: .top, spacing: 8) { + Text(verbatim: "WHERE") + .font(.callout.monospaced()) + .foregroundStyle(.secondary) + .padding(.top, 3) + + FilterValueTextField( + text: textConditionBinding, + focusedId: $focusedFilterId, + identity: row.id, + placeholder: "e.g. id = 1", + completionSource: textCompletionSource, + allowsMultiLine: true, + onSubmit: { applyAllValidFilters() }, + onCancel: { closePanelAndFocusGrid() } + ) + .frame(height: textConditionHeight) + .accessibilityLabel(String(localized: "WHERE clause")) + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + } + + private var textConditionBinding: Binding { + let stateBinding = $state + return Binding( + get: { stateBinding.wrappedValue.textCondition }, + set: { text in + var next = stateBinding.wrappedValue + next.setTextCondition(text) + stateBinding.wrappedValue = next + } + ) + } + + private var textCompletionSource: FilterCompletionSource { + if let provider = configuration.rawSQLCompletionProvider { + return .sqlTokens(provider) + } + return .staticValues(completionItems) + } + private var filterOptionsMenu: some View { Menu { if let sqlPreview = configuration.sqlPreview { @@ -316,8 +475,13 @@ struct FilterPanelView: View { } } + /// Return in a row and Cmd-Return both run what the Apply button runs. private func applyAllValidFilters() { - actions.applyAllFilters() + if let criteria { + criteria.actions.applyFiltersAndSort() + } else { + actions.applyAllFilters() + } actions.focusGrid() } diff --git a/apple/TablePro/Views/Filter/FilterSortSection.swift b/apple/TablePro/Views/Filter/FilterSortSection.swift new file mode 100644 index 0000000000..c2c9abae76 --- /dev/null +++ b/apple/TablePro/Views/Filter/FilterSortSection.swift @@ -0,0 +1,161 @@ +// +// FilterSortSection.swift +// TablePro +// + +import SwiftUI + +/// The filter panel's Sort By section. It edits `TabFilterState.sortDraft`, seeded from the tab's +/// sort, and Apply Filter & Sort runs it with the filters. +struct FilterSortSection: View { + @Binding var state: TabFilterState + let columns: [String] + let appliedSort: [FilterSortCriterion] + let newSortDirection: SortDirection + + private let rowButtonGlyphSize: CGFloat = 14 + + /// Matches the filter rows' column picker, so a long column name truncates instead of widening the panel. + private static let columnPickerMaximumWidth: CGFloat = 160 + + private var criteria: [FilterSortCriterion] { + state.sortCriteria(applied: appliedSort) + } + + private var canAddCriterion: Bool { + let used = Set(criteria.map(\.columnName)) + return columns.contains { !used.contains($0) } + } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Text("Sort By") + .font(.callout.weight(.medium)) + + Spacer() + + Button(action: addCriterion) { + Image(systemName: "plus") + .frame(width: rowButtonGlyphSize, height: rowButtonGlyphSize) + } + .buttonStyle(.bordered) + .controlSize(.small) + .disabled(!canAddCriterion) + .accessibilityLabel(String(localized: "Add sort criterion")) + .help(String(localized: "Add sort criterion")) + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + + if criteria.isEmpty { + Text("Click + to add sort criteria") + .font(.callout) + .foregroundStyle(.secondary) + .padding(.horizontal, 12) + .padding(.bottom, 8) + } else { + VStack(spacing: 0) { + ForEach(criteria) { criterion in + criterionRow(criterion) + } + } + .padding(.bottom, 4) + } + } + .accessibilityElement(children: .contain) + .accessibilityLabel(String(localized: "Sort By")) + } + + private func criterionRow(_ criterion: FilterSortCriterion) -> some View { + HStack(spacing: 4) { + Picker(String(localized: "Sort column"), selection: columnBinding(for: criterion)) { + ForEach(columnChoices(for: criterion), id: \.self) { column in + Text(column).tag(column) + } + } + .pickerStyle(.menu) + .controlSize(.small) + .frame(maxWidth: Self.columnPickerMaximumWidth) + .labelsHidden() + .help(String(localized: "Select sort column")) + + Picker(String(localized: "Sort direction"), selection: directionBinding(for: criterion)) { + ForEach(SortDirection.allCases) { direction in + Text(direction.displayName).tag(direction) + } + } + .pickerStyle(.menu) + .controlSize(.small) + .fixedSize() + .labelsHidden() + + Spacer(minLength: 0) + + Button { + removeCriterion(criterion) + } label: { + Image(systemName: "minus") + .frame(width: rowButtonGlyphSize, height: rowButtonGlyphSize) + } + .buttonStyle(.bordered) + .controlSize(.small) + .accessibilityLabel(String(localized: "Remove sort criterion")) + .help(String(localized: "Remove sort criterion")) + } + .padding(.vertical, 2) + .padding(.horizontal, 12) + .accessibilityElement(children: .contain) + } + + /// Columns no other key sorts by, plus this key's own column even once the result lost it, so the + /// picker never shows a blank selection. + private func columnChoices(for criterion: FilterSortCriterion) -> [String] { + let usedElsewhere = Set(criteria.map(\.columnName)).subtracting([criterion.columnName]) + var choices = columns.filter { !usedElsewhere.contains($0) } + if !columns.contains(criterion.columnName) { + choices.insert(criterion.columnName, at: 0) + } + return choices + } + + private func columnBinding(for criterion: FilterSortCriterion) -> Binding { + Binding( + get: { criterion.columnName }, + set: { newColumn in + replaceCriterion(criterion.columnName) { $0.columnName = newColumn } + } + ) + } + + private func directionBinding(for criterion: FilterSortCriterion) -> Binding { + Binding( + get: { criterion.direction }, + set: { newDirection in + replaceCriterion(criterion.columnName) { $0.direction = newDirection } + } + ) + } + + /// One whole-value write, reading the key as it is now rather than as the row last drew it. + private func replaceCriterion(_ columnName: String, _ change: (inout FilterSortCriterion) -> Void) { + var next = state + guard var replacement = next.sortCriteria(applied: appliedSort).first(where: { $0.columnName == columnName }) + else { return } + change(&replacement) + next.updateSortCriterion(columnName, to: replacement, applied: appliedSort) + state = next + } + + private func addCriterion() { + var next = state + next.addSortCriterion(applied: appliedSort, columns: columns, direction: newSortDirection) + state = next + } + + private func removeCriterion(_ criterion: FilterSortCriterion) { + var next = state + next.removeSortCriterion(criterion.columnName, applied: appliedSort) + state = next + } +} diff --git a/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift b/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift index 0582cfa4ce..68a2b5515a 100644 --- a/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift +++ b/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift @@ -16,6 +16,8 @@ internal struct QueryTabFilterPanel: View { /// is what the two closures this view used to carry were hiding, because a closure is never /// equal to another one and forced a re-evaluation on every parent render. (#3026) @ObservedObject var tabManager: QueryTabManager + /// Settings > Data Grid decides whether the panel holds the sort too. + @ObservedObject private var settingsManager = AppSettingsManager.shared let columns: [String] let primaryKeyColumn: String? let databaseType: DatabaseType @@ -75,7 +77,39 @@ internal struct QueryTabFilterPanel: View { caseMatching: .engine(PluginManager.shared.caseSensitivityStyle(for: databaseType)), offersMatchAny: PluginManager.shared.supportsMatchAnyFilters(for: databaseType), sqlPreview: coordinator.filterCoordinator, - presetStore: FilterPresetStorage.shared + presetStore: FilterPresetStorage.shared, + criteria: Self.criteriaConfiguration( + settings: settingsManager.dataGrid, + offersRawFilter: PluginManager.shared.supportsRawFilter(for: databaseType), + isSQLDialect: isSQLDialect, + supportsColumnSort: coordinator.supportsColumnSort, + columns: columns, + appliedSort: coordinator.filterCoordinator.selectedTabAppliedSortCriteria, + actions: coordinator.filterCoordinator + ) + ) + } + + /// Nil while the setting is off, which leaves the filter-only panel. Text mode is a WHERE + /// condition, so it needs an engine that takes a raw filter and speaks SQL; a document store's + /// raw filter is not a WHERE condition. The section is hidden where a table cannot be sorted by + /// a column, and a new key sorts the way a first header click does. + static func criteriaConfiguration( + settings: DataGridSettings, + offersRawFilter: Bool, + isSQLDialect: Bool, + supportsColumnSort: Bool, + columns: [String], + appliedSort: [FilterSortCriterion], + actions: any FilterCriteriaActions + ) -> FilterCriteriaConfiguration? { + guard settings.showsSortInFilterPanel else { return nil } + return FilterCriteriaConfiguration( + offersTextMode: offersRawFilter && isSQLDialect, + sortColumns: supportsColumnSort ? columns : nil, + appliedSort: supportsColumnSort ? appliedSort : [], + newSortDirection: settings.defaultSortDirection, + actions: actions ) } diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index bd7526e555..705a13bd72 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -1440,6 +1440,9 @@ final class MainContentCoordinator: ObservableObject { tab.sortState = capturedSort tab.hasUserInteraction = true tab.pagination.reset() + // A header sort runs at once, so the filter panel's Sort By section shows it rather + // than an edit made before it. + tab.filterState.sortDraft = nil }) else { return } guard let tabIndex = self.tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } self.rebuildTableQuery(at: tabIndex) diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 584e0f04a0..22394b70de 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -59,6 +59,14 @@ struct DataGridSection: View { 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 { + Toggle("Show sort criteria in the filter panel", isOn: $settings.showsSortInFilterPanel) + .help(String(localized: "Edit the filters and the sort together, write the filter as text, and apply both at once")) + Toggle("Open the filter panel with each table", isOn: $settings.opensFilterPanelForTables) + } header: { + Text("Filter Panel") + } + Section { Picker("Copy rows as:", selection: $settings.rowCopyFormat) { ForEach(RowCopyFormat.allCases) { format in diff --git a/apple/TableProTests/Models/FilterCriteriaStateTests.swift b/apple/TableProTests/Models/FilterCriteriaStateTests.swift new file mode 100644 index 0000000000..acde0ea355 --- /dev/null +++ b/apple/TableProTests/Models/FilterCriteriaStateTests.swift @@ -0,0 +1,275 @@ +// +// FilterCriteriaStateTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct FilterCriteriaStateTests { + private static let columns = ["id", "name", "email"] + + private func builderState(_ filters: [TableFilter], commit: FilterCommit? = nil) -> TabFilterState { + TabFilterState(filters: filters, commit: commit, isVisible: true, filterLogicMode: .or) + } + + // MARK: - Builder and Text + + @Test("Builder to Text holds one raw row with the rows' condition, and Text to Builder keeps it as that row") + func builderToTextToBuilderKeepsTypedText() throws { + let name = TestFixtures.makeTableFilter(column: "name", value: "a") + let email = TestFixtures.makeTableFilter(column: "email", value: "b") + var state = builderState([name, email]) + + let rowID = state.enterTextMode(condition: "`name` = 'a' OR `email` = 'b'") + + #expect(state.effectiveEditMode == .text) + #expect(state.filters.count == 1) + #expect(state.filters.first?.isRawSQL == true) + #expect(state.filters.first?.id == rowID) + #expect(state.textCondition == "`name` = 'a' OR `email` = 'b'") + #expect(state.filterLogicMode == .and) + + state.setTextCondition("`name` = 'c'") + state.enterBuilderMode() + + #expect(state.effectiveEditMode == .builder) + #expect(state.editMode == .builder) + let row = try #require(state.filters.first) + #expect(state.filters.count == 1) + #expect(row.isRawSQL) + #expect(row.value == "`name` = 'c'") + #expect(state.textModeOrigin == nil) + } + + @Test("Text to Builder with nothing typed brings the rows back with their flags and logic mode") + func untouchedRoundTripRestoresRows() { + let enabled = TestFixtures.makeTableFilter(column: "name", value: "a") + let disabled = TestFixtures.makeTableFilter(column: "email", value: "b", isEnabled: false) + var state = builderState([enabled, disabled]) + + state.enterTextMode(condition: "`name` = 'a'") + state.enterBuilderMode() + + #expect(state.filters == [enabled, disabled]) + #expect(state.filterLogicMode == .or) + #expect(state.effectiveEditMode == .builder) + } + + @Test("A solo commit reads as every row once its row is gone, and no commit stays none") + func enteringTextModeKeepsTheCommitResolvable() { + let row = TestFixtures.makeTableFilter(column: "name", value: "a") + var solo = builderState([row], commit: .solo(row.id)) + solo.enterTextMode(condition: "`name` = 'a'") + #expect(solo.commit == .all) + + var none = builderState([row]) + none.enterTextMode(condition: "`name` = 'a'") + #expect(none.commit == nil) + } + + @Test("Rows put in from outside the editor leave Text mode") + func outsideRowsLeaveTextMode() { + var state = builderState([]) + state.enterTextMode(condition: "") + #expect(state.effectiveEditMode == .text) + + state.addFilter(forColumn: "name", settings: FilterSettings()) + + #expect(state.editMode == .builder) + #expect(state.effectiveEditMode == .builder) + #expect(state.textModeOrigin == nil) + } + + @Test("A text mode whose rows are not one raw row reads as Builder") + func misshapenTextStateReadsAsBuilder() { + var state = builderState([TestFixtures.makeTableFilter(column: "name", value: "a")]) + state.editMode = .text + #expect(state.effectiveEditMode == .builder) + #expect(state.textCondition.isEmpty) + + state.setTextCondition("ignored") + #expect(state.filters.first?.value == "a") + } + + @Test("The edit mode persists with the tab and with the table's saved filters, and older files read as Builder") + func editModePersists() throws { + var state = builderState([]) + state.enterTextMode(condition: "id > 1") + + let tabData = try JSONEncoder().encode(state) + let decodedTab = try JSONDecoder().decode(TabFilterState.self, from: tabData) + #expect(decodedTab.editMode == .text) + #expect(decodedTab.effectiveEditMode == .text) + + let savedData = try JSONEncoder().encode(state.persistedState) + let decodedSaved = try JSONDecoder().decode(PersistedFilterState.self, from: savedData) + #expect(decodedSaved.editMode == .text) + + let legacyTab = try JSONDecoder().decode(TabFilterState.self, from: Data(#"{"filters":[]}"#.utf8)) + #expect(legacyTab.editMode == .builder) + let legacySaved = try JSONDecoder().decode(PersistedFilterState.self, from: Data(#"{"filters":[]}"#.utf8)) + #expect(legacySaved.editMode == .builder) + } + + @Test("Restoring a table's saved Text mode brings it back, and nothing saved starts in Builder") + @MainActor + func restoreReadsTheSavedMode() { + let raw = TableFilter.rawCondition("id > 1") + let restored = FilterCoordinator.resolvedRestoredState( + settings: FilterSettings(restoreBehavior: .restoreAndApply), + saved: PersistedFilterState(filters: [raw], editMode: .text), + current: TabFilterState() + ) + #expect(restored.effectiveEditMode == .text) + + var current = TabFilterState() + current.sortDraft = [FilterSortCriterion(columnName: "id", direction: .ascending)] + let empty = FilterCoordinator.resolvedRestoredState( + settings: FilterSettings(restoreBehavior: .restoreAndApply), + saved: PersistedFilterState(filters: [], editMode: .text), + current: current + ) + #expect(empty.editMode == .builder) + #expect(empty.sortDraft == nil) + } + + // MARK: - Sort draft + + @Test("The section shows the tab's sort until an edit seeds a draft from it") + func sortDraftSeedsFromTheTabSort() { + let applied = [FilterSortCriterion(columnName: "name", direction: .descending)] + var state = TabFilterState() + #expect(state.sortCriteria(applied: applied) == applied) + #expect(state.sortDraft == nil) + + state.addSortCriterion(applied: applied, columns: Self.columns, direction: .ascending) + + #expect(state.sortDraft == [ + FilterSortCriterion(columnName: "name", direction: .descending), + FilterSortCriterion(columnName: "id", direction: .ascending) + ]) + } + + @Test("Keys stay unique: + takes an unused column, and a change to a column another key sorts by is refused") + func sortKeysStayUnique() { + var state = TabFilterState() + for _ in 0..<4 { + state.addSortCriterion(applied: [], columns: Self.columns, direction: .ascending) + } + #expect(state.sortDraft?.map { $0.columnName } == Self.columns) + + state.updateSortCriterion( + "id", + to: FilterSortCriterion(columnName: "email", direction: .descending), + applied: [] + ) + #expect(state.sortDraft?.first == FilterSortCriterion(columnName: "id", direction: .ascending)) + + state.updateSortCriterion( + "id", + to: FilterSortCriterion(columnName: "id", direction: .descending), + applied: [] + ) + #expect(state.sortDraft?.first?.direction == .descending) + + state.removeSortCriterion("name", applied: []) + #expect(state.sortDraft?.map { $0.columnName } == ["id", "email"]) + } + + @Test("The tab's sort converts to section keys by name and back to a stamped user sort") + func sortConversionRoundTrips() { + let tabSort = SortState( + columns: [ + SortColumn(columnIndex: 2, direction: .descending), + SortColumn(columnIndex: 0, direction: .ascending, columnName: "id"), + SortColumn(columnIndex: 0, direction: .descending, columnName: "id"), + SortColumn(columnIndex: 9, direction: .ascending) + ], + source: .defaultSort + ) + + let criteria = TabFilterState.sortCriteria(from: tabSort, columns: Self.columns) + #expect(criteria == [ + FilterSortCriterion(columnName: "email", direction: .descending), + FilterSortCriterion(columnName: "id", direction: .ascending) + ]) + + let sort = TabFilterState.sortState( + from: criteria + [FilterSortCriterion(columnName: "gone", direction: .ascending)], + columns: Self.columns + ) + #expect(sort.source == .user) + #expect(sort.columns == [ + SortColumn(columnIndex: 2, direction: .descending, columnName: "email"), + SortColumn(columnIndex: 0, direction: .ascending, columnName: "id") + ]) + } + + // MARK: - Edited state + + @Test("Edited compares what Apply would run with what the rows were fetched with") + func editedFollowsTheRunningFilters() { + let name = TestFixtures.makeTableFilter(column: "name", value: "a") + var state = builderState([name], commit: .all) + state.filterLogicMode = .and + state.adoptAppliedFiltersAsRunning() + #expect(!state.criteriaDiffer(fromAppliedSort: [])) + + var unfinished = state + unfinished.filters.append(TestFixtures.makeTableFilter(column: "", value: "")) + #expect(!unfinished.criteriaDiffer(fromAppliedSort: []), "an incomplete row runs nothing") + + var typed = state + typed.filters[0].value = "b" + #expect(typed.criteriaDiffer(fromAppliedSort: [])) + + var unchecked = state + unchecked.filters[0].isEnabled = false + #expect(unchecked.criteriaDiffer(fromAppliedSort: [])) + + var cleared = state + cleared.commit = nil + cleared.adoptAppliedFiltersAsRunning() + #expect(cleared.criteriaDiffer(fromAppliedSort: []), "Apply would filter rows shown unfiltered") + } + + @Test("Edited sees a changed logic mode only when it joins two rows") + func editedLogicMode() { + let name = TestFixtures.makeTableFilter(column: "name", value: "a") + let email = TestFixtures.makeTableFilter(column: "email", value: "b") + var two = builderState([name, email], commit: .all) + two.filterLogicMode = .and + two.adoptAppliedFiltersAsRunning() + two.filterLogicMode = .or + #expect(two.criteriaDiffer(fromAppliedSort: [])) + + var one = builderState([name], commit: .all) + one.filterLogicMode = .and + one.adoptAppliedFiltersAsRunning() + one.filterLogicMode = .or + #expect(!one.criteriaDiffer(fromAppliedSort: [])) + } + + @Test("Edited sees a sort draft only while it differs from the tab's sort") + func editedSortDraft() { + let applied = [FilterSortCriterion(columnName: "name", direction: .ascending)] + var state = TabFilterState() + #expect(!state.criteriaDiffer(fromAppliedSort: applied)) + + state.updateSortCriterion( + "name", + to: FilterSortCriterion(columnName: "name", direction: .descending), + applied: applied + ) + #expect(state.criteriaDiffer(fromAppliedSort: applied)) + + state.updateSortCriterion( + "name", + to: FilterSortCriterion(columnName: "name", direction: .ascending), + applied: applied + ) + #expect(!state.criteriaDiffer(fromAppliedSort: applied)) + } +} diff --git a/apple/TableProTests/Views/Filter/FilterSortPanelTests.swift b/apple/TableProTests/Views/Filter/FilterSortPanelTests.swift new file mode 100644 index 0000000000..2f16cfef90 --- /dev/null +++ b/apple/TableProTests/Views/Filter/FilterSortPanelTests.swift @@ -0,0 +1,284 @@ +// +// FilterSortPanelTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +private final class StubCriteriaActions: FilterCriteriaActions { + func applyFiltersAndSort() {} + func filterConditionText(for filters: [TableFilter], logicMode: FilterLogicMode) -> String? { "" } +} + +@MainActor +struct FilterSortPanelTests { + private static let columns = ["id", "name", "email"] + + private func makeCoordinator( + filters: [TableFilter] = [], + sort: SortState = SortState(), + type: DatabaseType = .mysql + ) -> (coordinator: MainContentCoordinator, tabManager: QueryTabManager, tabId: UUID) { + let tabManager = QueryTabManager() + let coordinator = MainContentCoordinator( + connection: TestFixtures.makeConnection(type: type), + tabManager: tabManager, + changeManager: DataChangeManager(), + toolbarState: ConnectionToolbarState() + ) + var tab = QueryTab(title: "users", query: "unfiltered", tabType: .table, tableName: "users") + tab.sortState = sort + tab.filterState.filters = filters + tab.filterState.isVisible = true + tabManager.tabs.append(tab) + tabManager.selectedTabId = tab.id + let rows = (0..<3).map { index in Self.columns.map { PluginCellValue.fromOptional("\($0)_\(index)") } } + coordinator.setActiveTableRows( + TableRows.from( + queryRows: rows, + columns: Self.columns, + columnTypes: Array(repeating: .text(rawType: nil), count: Self.columns.count) + ), + for: tab.id + ) + return (coordinator, tabManager, tab.id) + } + + private func tab(_ tabManager: QueryTabManager, _ tabId: UUID) throws -> QueryTab { + try #require(tabManager.tabs.first { $0.id == tabId }) + } + + private func setSortDraft(_ draft: [FilterSortCriterion]?, in tabManager: QueryTabManager, _ tabId: UUID) throws { + let index = try #require(tabManager.tabs.firstIndex { $0.id == tabId }) + tabManager.tabs[index].filterState.sortDraft = draft + } + + // MARK: - Apply Filter & Sort + + @Test("Apply Filter & Sort runs the rows and the sort draft in one query") + func appliesFiltersAndSortTogether() throws { + let name = TestFixtures.makeTableFilter(column: "name", value: "a") + let (coordinator, tabManager, tabId) = makeCoordinator(filters: [name]) + defer { coordinator.teardown() } + try setSortDraft([FilterSortCriterion(columnName: "email", direction: .descending)], in: tabManager, tabId) + + coordinator.filterCoordinator.applyFiltersAndSort() + + let applied = try tab(tabManager, tabId) + #expect(applied.sortState == SortState( + columns: [SortColumn(columnIndex: 2, direction: .descending, columnName: "email")], + source: .user + )) + #expect(applied.content.query.contains("WHERE `name`")) + #expect(applied.content.query.contains("ORDER BY `email` DESC")) + #expect(applied.filterState.commit == .all) + #expect(applied.filterState.executedFilters.map { $0.id } == [name.id]) + #expect(applied.filterState.sortDraft == nil) + #expect(applied.hasUserInteraction) + let appliedSort = coordinator.filterCoordinator.selectedTabAppliedSortCriteria + #expect(appliedSort == [FilterSortCriterion(columnName: "email", direction: .descending)]) + #expect(!applied.filterState.criteriaDiffer(fromAppliedSort: appliedSort)) + } + + @Test("With no row to run, the sort alone reloads the table and the rows stay in the panel") + func sortOnlyApplyKeepsRowsUnapplied() throws { + let unfinished = TestFixtures.makeTableFilter(column: "name", value: "") + let (coordinator, tabManager, tabId) = makeCoordinator(filters: [unfinished]) + defer { coordinator.teardown() } + try setSortDraft([FilterSortCriterion(columnName: "id", direction: .ascending)], in: tabManager, tabId) + + coordinator.filterCoordinator.applyFiltersAndSort() + + let applied = try tab(tabManager, tabId) + #expect(!applied.content.query.contains("WHERE")) + #expect(applied.content.query.contains("ORDER BY `id` ASC")) + #expect(applied.filterState.commit == nil) + #expect(applied.filterState.filters == [unfinished]) + #expect(applied.sortState.columns.compactMap { $0.columnName } == ["id"]) + } + + @Test("A draft equal to the tab's sort leaves the sort and its source alone") + func unchangedDraftKeepsTheSort() throws { + let defaultSort = SortState( + columns: [SortColumn(columnIndex: 0, direction: .ascending, columnName: "id")], + source: .defaultSort + ) + let (coordinator, tabManager, tabId) = makeCoordinator(sort: defaultSort) + defer { coordinator.teardown() } + try setSortDraft([FilterSortCriterion(columnName: "id", direction: .ascending)], in: tabManager, tabId) + + coordinator.filterCoordinator.applyFiltersAndSort() + + let applied = try tab(tabManager, tabId) + #expect(applied.sortState == defaultSort) + #expect(applied.filterState.sortDraft == nil) + } + + @Test("A filter the engine refuses leaves the sort, the draft and the query as they were") + func refusalKeepsTheDraft() throws { + let refused = TableFilter.rawCondition("status = 'a' -- temp") + let (coordinator, tabManager, tabId) = makeCoordinator(filters: [refused]) + defer { coordinator.teardown() } + let draft = [FilterSortCriterion(columnName: "name", direction: .ascending)] + try setSortDraft(draft, in: tabManager, tabId) + + coordinator.filterCoordinator.applyFiltersAndSort() + + let after = try tab(tabManager, tabId) + #expect(after.content.query == "unfiltered") + #expect(after.sortState == SortState()) + #expect(after.filterState.sortDraft == draft) + #expect(after.filterState.commit == nil) + #expect(after.execution.errorMessage != nil) + } + + @Test("A header sort runs at once and the section follows it") + func headerSortClearsTheDraft() throws { + let (coordinator, tabManager, tabId) = makeCoordinator() + defer { coordinator.teardown() } + try setSortDraft([FilterSortCriterion(columnName: "email", direction: .ascending)], in: tabManager, tabId) + + coordinator.handleSortStateChanged(SortState( + columns: [SortColumn(columnIndex: 1, direction: .descending)], + source: .user + )) + + let after = try tab(tabManager, tabId) + #expect(after.filterState.sortDraft == nil) + #expect(coordinator.filterCoordinator.selectedTabAppliedSortCriteria == [ + FilterSortCriterion(columnName: "name", direction: .descending) + ]) + } + + // MARK: - Text mode + + @Test("Text mode starts from the enabled rows' WHERE condition, without the keyword") + func conditionTextFromEnabledRows() throws { + let (coordinator, _, _) = makeCoordinator() + defer { coordinator.teardown() } + let rows = [ + TestFixtures.makeTableFilter(column: "name", op: .greaterThan, value: "a"), + TestFixtures.makeTableFilter(column: "email", value: "b", isEnabled: false), + TableFilter.rawCondition("id > 1") + ] + + let text = coordinator.filterCoordinator.filterConditionText(for: rows, logicMode: .or) + + #expect(text == "`name` > 'a' OR (id > 1)") + #expect(coordinator.filterCoordinator.filterConditionText(for: [], logicMode: .and) == "") + } + + @Test("A row the engine cannot write as SQL refuses the switch") + func refusedRowHasNoConditionText() { + let (coordinator, _, _) = makeCoordinator() + defer { coordinator.teardown() } + + let text = coordinator.filterCoordinator.filterConditionText( + for: [TableFilter.rawCondition("1=1); DELETE FROM users")], + logicMode: .and + ) + + #expect(text == nil) + } + + @Test("Text mode's one raw row applies like any row") + func textModeApplies() throws { + let (coordinator, tabManager, tabId) = makeCoordinator() + defer { coordinator.teardown() } + let index = try #require(tabManager.tabs.firstIndex { $0.id == tabId }) + tabManager.tabs[index].filterState.enterTextMode(condition: "`id` > 1") + + coordinator.filterCoordinator.applyFiltersAndSort() + + let applied = try tab(tabManager, tabId) + #expect(applied.content.query.contains("WHERE (`id` > 1)")) + #expect(applied.filterState.effectiveEditMode == .text) + #expect(!applied.filterState.criteriaDiffer(fromAppliedSort: [])) + } + + // MARK: - Settings + + @Test("Both settings start off and decode off from settings saved before them") + func settingsDefaultOff() throws { + #expect(DataGridSettings.default.showsSortInFilterPanel == false) + #expect(DataGridSettings.default.opensFilterPanelForTables == false) + + let legacy = try JSONDecoder().decode(DataGridSettings.self, from: Data(#"{"showRowNumbers":false}"#.utf8)) + #expect(legacy.showsSortInFilterPanel == false) + #expect(legacy.opensFilterPanelForTables == false) + #expect(legacy.showRowNumbers == false) + + var on = DataGridSettings.default + on.showsSortInFilterPanel = true + on.opensFilterPanelForTables = true + let decoded = try JSONDecoder().decode(DataGridSettings.self, from: JSONEncoder().encode(on)) + #expect(decoded == on) + } + + @Test("With the setting off the panel gets no sort, no Text mode and no combined Apply") + func settingOffLeavesThePlainPanel() { + let off = QueryTabFilterPanel.criteriaConfiguration( + settings: .default, + offersRawFilter: true, + isSQLDialect: true, + supportsColumnSort: true, + columns: Self.columns, + appliedSort: [], + actions: StubCriteriaActions() + ) + let isOff = off == nil + #expect(isOff) + } + + @Test("With the setting on, Text mode needs a SQL raw filter and the section needs a column sort") + func settingOnGatesEachPart() throws { + var settings = DataGridSettings.default + settings.showsSortInFilterPanel = true + settings.defaultSortDirection = .descending + let actions = StubCriteriaActions() + + let sql = try #require(QueryTabFilterPanel.criteriaConfiguration( + settings: settings, offersRawFilter: true, isSQLDialect: true, supportsColumnSort: true, + columns: Self.columns, appliedSort: [], actions: actions + )) + #expect(sql.offersTextMode) + #expect(sql.sortColumns == Self.columns) + #expect(sql.newSortDirection == .descending) + + let document = try #require(QueryTabFilterPanel.criteriaConfiguration( + settings: settings, offersRawFilter: true, isSQLDialect: false, supportsColumnSort: true, + columns: Self.columns, appliedSort: [], actions: actions + )) + #expect(!document.offersTextMode) + + let unsortable = try #require(QueryTabFilterPanel.criteriaConfiguration( + settings: settings, offersRawFilter: false, isSQLDialect: true, supportsColumnSort: false, + columns: Self.columns, + appliedSort: [FilterSortCriterion(columnName: "id", direction: .ascending)], + actions: actions + )) + #expect(!unsortable.offersTextMode) + #expect(!unsortable.showsSort) + #expect(unsortable.appliedSort.isEmpty) + } + + @Test("Opening a table opens the panel only when the setting asks") + func openingATableOpensThePanel() { + let settings = FilterSettings(restoreBehavior: .restoreAndApply, alwaysShowPanel: false) + let nothingSaved = PersistedFilterState(filters: []) + + let off = FilterCoordinator.resolvedRestoredState( + settings: settings, saved: nothingSaved, current: TabFilterState() + ) + let on = FilterCoordinator.resolvedRestoredState( + settings: settings, saved: nothingSaved, current: TabFilterState(), opensPanel: true + ) + + #expect(!off.isVisible) + #expect(on.isVisible) + } +} From f851f6c7f92a0ee9407c9f58f4b540722397cadc Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 17:22:50 +0700 Subject: [PATCH 087/123] feat(settings): switch the table tab's data view with the Layout buttons Navigator Layout now also shows column types in the header, the sort and a Text mode in the filter panel, opens that panel with each table, puts the result bar above the grid and names the database and connection in table tab titles. Standard Layout puts those back to their defaults. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Settings/NavigatorLayoutPreset.swift | 24 +++++++++++- .../Views/Settings/GeneralSettingsView.swift | 10 ++++- .../Settings/SettingsWindowController.swift | 1 + .../Models/NavigatorLayoutPresetTests.swift | 39 +++++++++++++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index 9debf0dc8e..8ce4785efc 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -7,7 +7,8 @@ import Foundation /// The Layout buttons in Settings > General: table details, favorite tables at the top of the tree, /// the Objects tab on selection, the Objects toolbar buttons, labels under the toolbar's icons, the -/// saved connections in the tree and Tree as the default sidebar layout, on or off in one step. +/// saved connections in the tree and Tree as the default sidebar layout, on or off in one step. The +/// same buttons switch the table tab's data view (`applyDataView`). /// /// The tree lists the saved connections itself, so the layout keeps the separate connections column /// off: the sidebar is one tree, with the connection on screen opened in it. @@ -39,6 +40,27 @@ internal enum NavigatorLayoutPreset { defaultLayout = .flat } + /// The table tab's half of the layout: types under the column names, the sort and a Text mode in + /// the filter panel, that panel open with each table, the result bar above the grid and tab titles + /// that name the database and connection. These live in the Data Grid and Tab settings, so the + /// caller passes those bindings beside the General one. + internal static func applyDataView(tabs: inout TabSettings, dataGrid: inout DataGridSettings) { + dataGrid.showsColumnTypesInHeader = true + dataGrid.showsSortInFilterPanel = true + dataGrid.opensFilterPanelForTables = true + dataGrid.resultBarAtTop = true + tabs.titleShowsLocation = true + } + + internal static func restoreDataView(tabs: inout TabSettings, dataGrid: inout DataGridSettings) { + let standardGrid = DataGridSettings.default + dataGrid.showsColumnTypesInHeader = standardGrid.showsColumnTypesInHeader + dataGrid.showsSortInFilterPanel = standardGrid.showsSortInFilterPanel + dataGrid.opensFilterPanelForTables = standardGrid.opensFilterPanelForTables + dataGrid.resultBarAtTop = standardGrid.resultBarAtTop + tabs.titleShowsLocation = TabSettings.default.titleShowsLocation + } + /// The default layout reaches only connections opened later, so each open one is switched the way /// the View menu switches it. An engine with no database tree is skipped, as the menu skips it. @MainActor diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 786bc8d2fa..0bef0e17f0 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -4,6 +4,7 @@ import SwiftUI struct GeneralSettingsView: View { @Binding var settings: GeneralSettings @Binding var tabSettings: TabSettings + @Binding var dataGridSettings: DataGridSettings @ObservedObject var updater: SoftwareUpdater var onResetAll: () -> Void @@ -78,8 +79,10 @@ struct GeneralSettingsView: View { Text(String(localized: """ Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects \ tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the \ - tree, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open \ - connections switch layout too. + tree, and makes Tree the default sidebar layout. In table tabs it shows column types in \ + the header, the sort and a Text mode in the filter panel, opens that panel with each table, \ + puts the result bar above the grid and names the database and connection in tab titles. \ + Standard Layout turns them off again. Open connections switch layout too. """)) } @@ -202,8 +205,10 @@ struct GeneralSettingsView: View { private func useLayoutPreset(navigator: Bool) { if navigator { NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &defaultSidebarLayout) + NavigatorLayoutPreset.applyDataView(tabs: &tabSettings, dataGrid: &dataGridSettings) } else { NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &defaultSidebarLayout) + NavigatorLayoutPreset.restoreDataView(tabs: &tabSettings, dataGrid: &dataGridSettings) } NavigatorLayoutPreset.switchOpenConnections(to: defaultSidebarLayout) } @@ -213,6 +218,7 @@ struct GeneralSettingsView: View { GeneralSettingsView( settings: .constant(.default), tabSettings: .constant(.default), + dataGridSettings: .constant(.default), updater: SoftwareUpdater.shared, onResetAll: {} ) diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index aa23cfa15c..ae3f2aec79 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -160,6 +160,7 @@ private struct SettingsPaneContent: View { GeneralSettingsView( settings: $settingsManager.general, tabSettings: $settingsManager.tabs, + dataGridSettings: $settingsManager.dataGrid, updater: SoftwareUpdater.shared, onResetAll: { settingsManager.resetToDefaults() } ) diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index c19450b044..edcb4dea4a 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -102,6 +102,45 @@ struct NavigatorLayoutPresetTests { #expect(settings == before) } + @Test("Use Navigator Layout turns on the table tab's data view, and Standard Layout turns it off") + func dataViewFollowsTheButtons() { + var tabs = TabSettings.default + var grid = DataGridSettings.default + + NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid) + + #expect(grid.showsColumnTypesInHeader) + #expect(grid.showsSortInFilterPanel) + #expect(grid.opensFilterPanelForTables) + #expect(grid.resultBarAtTop) + #expect(tabs.titleShowsLocation) + + NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid) + + #expect(grid == DataGridSettings.default) + #expect(tabs == TabSettings.default) + } + + @Test("The data view buttons leave every other Data Grid and Tab setting alone") + func dataViewKeepsOtherSettings() { + var tabs = TabSettings.default + tabs.enablePreviewTabs = !tabs.enablePreviewTabs + var grid = DataGridSettings.default + grid.showRowNumbers = !grid.showRowNumbers + grid.defaultPageSize = 250 + let tabsBefore = tabs + let gridBefore = grid + + NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid) + #expect(tabs.enablePreviewTabs == tabsBefore.enablePreviewTabs) + #expect(grid.showRowNumbers == gridBefore.showRowNumbers) + #expect(grid.defaultPageSize == 250) + + NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid) + #expect(tabs == tabsBefore) + #expect(grid == gridBefore) + } + /// The View menu switches one connection through its shared sidebar state; the preset does the /// same for each open one, and skips an engine that has no tree to switch to. @MainActor From 44b0670caedc11cd98d77c1a013d0d972fbfe7ba Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Tue, 10 Nov 2026 17:22:50 +0700 Subject: [PATCH 088/123] chore(l10n): add the data view strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../TablePro/Resources/Localizable.xcstrings | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 5bc3032ede..f7c6b9cbb1 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -20597,6 +20597,9 @@ } } } + }, + "Add sort criterion" : { + }, "Add SSH Server…" : { "localizations" : { @@ -26732,6 +26735,9 @@ } } } + }, + "Apply Filter & Sort" : { + }, "Apply Filter from Link" : { "extractionState" : "stale", @@ -26893,6 +26899,9 @@ } } } + }, + "Apply the filters and the sort (Cmd+Return)" : { + }, "Apply this rule" : { "localizations" : { @@ -32618,6 +32627,9 @@ } } } + }, + "Builder" : { + }, "Building" : { "extractionState" : "manual", @@ -33673,6 +33685,9 @@ } } } + }, + "Can't Switch to Text" : { + }, "Cancel" : { "localizations" : { @@ -40695,6 +40710,9 @@ } } } + }, + "Click + to add sort criteria" : { + }, "Click a table" : { "localizations" : { @@ -56695,6 +56713,9 @@ "Credit Card" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Criteria Edited" : { + }, "Critical" : { "localizations" : { @@ -70475,6 +70496,12 @@ } } } + }, + "Edit the filter as rows or as one WHERE condition" : { + + }, + "Edit the filters and the sort together, write the filter as text, and apply both at once" : { + }, "Edit the import of %@" : { @@ -82653,6 +82680,9 @@ } } } + }, + "Filter editing mode" : { + }, "Filter favorites" : { "localizations" : { @@ -82943,6 +82973,9 @@ } } } + }, + "Filter Panel" : { + }, "Filter privileges" : { "localizations" : { @@ -112703,6 +112736,9 @@ } } } + }, + "Moves the bar with the row count, view switcher and pages from below the results to above them." : { + }, "Moving through this tab's history replaces what it is showing and will discard all unsaved changes." : { "localizations" : { @@ -113747,6 +113783,9 @@ }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter panel, opens that panel with each table, puts the result bar above the grid and names the database and connection in tab titles. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { @@ -129224,6 +129263,9 @@ } } } + }, + "Open the filter panel with each table" : { + }, "Open this query in a new tab and run it" : { "comment" : "A description of the action to open a query in a new tab and run it.", @@ -148126,6 +148168,9 @@ "Remove SET transaction_timeout from the routine to debug it." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Remove sort criterion" : { + }, "Remove tag %@" : { "comment" : "A label for a button that removes a tag from a list of selected tags. The argument is the name of the tag to be removed.", @@ -162179,6 +162224,9 @@ } } } + }, + "Select sort column" : { + }, "Select Tab %d" : { "localizations" : { @@ -165685,6 +165733,9 @@ } } } + }, + "Show column types in the header" : { + }, "Show Completions" : { "localizations" : { @@ -165809,6 +165860,9 @@ } } } + }, + "Show database and connection in table tab titles" : { + }, "Show DDL" : { "localizations" : { @@ -166928,6 +166982,9 @@ } } } + }, + "Show sort criteria in the filter panel" : { + }, "Show SQL" : { "localizations" : { @@ -167074,6 +167131,9 @@ }, "Show the messages that arrived while paused" : { + }, + "Show the result bar above the grid" : { + }, "Show Toolbar" : { "localizations" : { @@ -170638,6 +170698,9 @@ } } } + }, + "Sort column" : { + }, "Sort columns in priority order" : { "localizations" : { @@ -170728,6 +170791,9 @@ } } } + }, + "Sort direction" : { + }, "Sort direction (default ascending)" : { "localizations" : { @@ -191720,6 +191786,9 @@ }, "The rows go in as one transaction. Cancel rolls it back." : { + }, + "The rows on screen were fetched with different filters or sorting" : { + }, "The rules file is not a regular file." : { @@ -196119,6 +196188,9 @@ } } } + }, + "These filters cannot be written as one condition for this database." : { + }, "These messages use the %@ compression codec, which TablePro cannot read." : { "extractionState" : "manual", @@ -203410,6 +203482,9 @@ } } } + }, + "Titles a table tab orders@shop (Shop Demo), with a table or view icon, so each tab says where its rows come from. Query tabs keep their names." : { + }, "TLS handshake failed: %@" : { "extractionState" : "manual", From 005bb31923a1d41b8f03f29d9756cdc34300565d Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 12:04:04 +0700 Subject: [PATCH 089/123] feat(appearance): add a colorful object icon style Settings > Appearance gets an Object Icons choice: Standard, the default, draws exactly what each surface drew before; Colorful draws a filled SF Symbol in a system hue per kind of object. ObjectIconProvider is the one resolver for glyph and tint, read by the sidebar tree and flat list, the Favorites tab, the editor tab strip, the Objects list, the quick switcher and the recent tab switcher. SwiftUI rows follow the setting through AppSettingsManager; the AppKit Objects list and the tree's rename glyph follow it through AppEvents.objectIconStyleChanged and a lazy read. The style lives in the synced appearance category, so the tests that pin that blob's keys now expect objectIconStyle beside the theme ids, still with no appearance mode. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-sync-storage.md | 2 +- apple/TablePro/Core/Events/AppEvents.swift | 5 + .../RecentTabs/RecentTabSwitcherSession.swift | 2 + .../EditorTabLabelResolver.swift | 31 ++- .../MainSplitViewController+RecentTabs.swift | 13 +- .../Query/ObjectListingPresentation.swift | 12 +- .../Core/Storage/AppSettingsManager.swift | 3 + .../Models/Settings/AppSettings.swift | 29 ++- apple/TablePro/Models/UI/ObjectIcon.swift | 175 +++++++++++++++ .../Models/UI/QuickSwitcherItem.swift | 25 +++ .../TablePro/Views/Main/EditorTabStrip.swift | 20 +- .../QuickSwitcherPanelView.swift | 7 +- .../RecentTabSwitcherRow.swift | 9 +- .../Settings/AppearanceSettingsView.swift | 11 + .../Views/Shared/ObjectIconImage.swift | 47 ++++ .../Views/Sidebar/DatabaseTreeCellView.swift | 43 +++- .../Views/Sidebar/DatabaseTreeRowView.swift | 59 +++-- .../Views/Sidebar/FavoritesTabView.swift | 31 ++- .../Sidebar/RenamableSidebarCellView.swift | 14 ++ .../Views/Sidebar/RoutineRowView.swift | 8 +- .../TablePro/Views/Sidebar/TableRowView.swift | 8 +- .../Views/Sidebar/TriggerRowView.swift | 8 +- .../Views/Sidebar/UserTypeRowView.swift | 8 +- .../TableListing/ObjectListingTableView.swift | 43 +++- .../ObjectListingPresentationTests.swift | 6 +- .../Storage/AppearanceModeStorageTests.swift | 2 +- .../Core/Sync/SyncCoordinatorThemeTests.swift | 4 +- .../Models/ObjectIconProviderTests.swift | 208 ++++++++++++++++++ .../AppearanceIconStyleSettingTests.swift | 47 ++++ .../Main/EditorTabLabelResolverTests.swift | 36 +++ .../DatabaseTreeCellIconStyleTests.swift | 71 ++++++ .../ObjectListingIconStyleTests.swift | 81 +++++++ 32 files changed, 977 insertions(+), 91 deletions(-) create mode 100644 apple/TablePro/Models/UI/ObjectIcon.swift create mode 100644 apple/TablePro/Views/Shared/ObjectIconImage.swift create mode 100644 apple/TableProTests/Models/ObjectIconProviderTests.swift create mode 100644 apple/TableProTests/Models/Settings/AppearanceIconStyleSettingTests.swift create mode 100644 apple/TableProTests/Views/Sidebar/DatabaseTreeCellIconStyleTests.swift create mode 100644 apple/TableProTests/Views/TableListing/ObjectListingIconStyleTests.swift diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index 0611f9c5b8..e6eac9ebcc 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -156,7 +156,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Preferences | UserDefaults | `AppSettingsStorage`, `AppSettingsManager` | | Editor and grid fonts | UserDefaults, device-local, never synced | `TypographySettings` through `AppSettingsManager` | | Appearance mode (Auto, Light, Dark) | UserDefaults, device-local, never synced | `AppSettingsStorage` through `AppSettingsManager.appearanceMode` | -| Light and dark theme ids (iCloud-synced, category `appearance`) | UserDefaults | `AppearanceSettings` through `AppSettingsManager` | +| Light and dark theme ids and the object icon style (iCloud-synced, category `appearance`) | UserDefaults | `AppearanceSettings` through `AppSettingsManager` | | User themes (iCloud-synced, one `AppSettings` record `theme.` each) | JSON, one file per theme | `ThemeCatalog` (sync rules: `.claude/rules/theme.md`, Sync) | | Query history | SQLite FTS5 | `QueryHistoryStorage` | | Tab state | JSON | `TabPersistenceCoordinator`, `TabDiskActor` | diff --git a/apple/TablePro/Core/Events/AppEvents.swift b/apple/TablePro/Core/Events/AppEvents.swift index eb2894539b..907acf748b 100644 --- a/apple/TablePro/Core/Events/AppEvents.swift +++ b/apple/TablePro/Core/Events/AppEvents.swift @@ -37,6 +37,11 @@ final class AppEvents { let dataGridSettingsChanged = PassthroughSubject() + /// SwiftUI rows observe the settings and redraw on their own. An AppKit list sets its glyphs + /// when it configures a cell, so it restyles the visible ones on this. Sent after the setting + /// is stored, carrying the new style. + let objectIconStyleChanged = PassthroughSubject() + /// The menu bar re-syncs itself through `MainMenuBuilder`, but a window's toolbar advertises /// the same shortcuts in its tooltips and overflow menu and AppKit never revisits either. let keyboardSettingsChanged = PassthroughSubject() diff --git a/apple/TablePro/Core/RecentTabs/RecentTabSwitcherSession.swift b/apple/TablePro/Core/RecentTabs/RecentTabSwitcherSession.swift index 4048164d15..3efe6cffdb 100644 --- a/apple/TablePro/Core/RecentTabs/RecentTabSwitcherSession.swift +++ b/apple/TablePro/Core/RecentTabs/RecentTabSwitcherSession.swift @@ -24,6 +24,8 @@ internal struct RecentTabCandidate: Identifiable, Equatable { internal let title: String internal let detail: String internal let symbolName: String + /// The glyph's hue in the colorful icon style; nil keeps the row's secondary color. + internal var symbolTint: ObjectIconTint? internal var id: RecentTabReference { reference } } diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift index f594e9cb98..af96826186 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift @@ -48,22 +48,26 @@ internal enum EditorTabLabelResolver { internal let text: String /// What hovering says. internal let description: String - /// The object's glyph, drawn before the text. Only a located title carries one: it is long - /// and mostly the same from tab to tab, so the glyph is what still tells a table from a - /// view at a glance. - internal let symbolName: String? + /// The object's glyph, drawn before the text. In the standard icon style only a located + /// title carries one: it is long and mostly the same from tab to tab, so the glyph is what + /// still tells a table from a view at a glance. In the colorful style every tab showing an + /// object or a query carries its kind's tinted glyph, which is the point of that style. + internal let icon: ObjectIcon? - internal init(text: String, description: String, symbolName: String? = nil) { + internal var symbolName: String? { icon?.symbolName } + + internal init(text: String, description: String, icon: ObjectIcon? = nil) { self.text = text self.description = description - self.symbolName = symbolName + self.icon = icon } } internal static func resolve( tabs: [QueryTab], target: ContainerSwitchTarget?, - style: EditorTabTitleStyle = .name + style: EditorTabTitleStyle = .name, + iconStyle: ObjectIconStyle = .standard ) -> [UUID: Label] { var titles: [UUID: String] = [:] var containers: [UUID: String] = [:] @@ -86,7 +90,7 @@ internal enum EditorTabLabelResolver { result[tab.id] = Label( text: isAmbiguous ? qualified : title, description: qualified, - symbolName: symbolName(of: tab, style: style) + icon: icon(of: tab, style: style, iconStyle: iconStyle) ) } } @@ -112,9 +116,14 @@ internal enum EditorTabLabelResolver { ) } - private static func symbolName(of tab: QueryTab, style: EditorTabTitleStyle) -> String? { - guard case .location = style, showsObject(tab) else { return nil } - return TableRowLogic.iconName(for: tab.tableContext.resolvedObjectKind()) + private static func icon(of tab: QueryTab, style: EditorTabTitleStyle, iconStyle: ObjectIconStyle) -> ObjectIcon? { + switch iconStyle { + case .standard: + guard case .location = style, showsObject(tab) else { return nil } + return ObjectIconProvider.icon(for: .relation(tab.tableContext.resolvedObjectKind()), style: .standard) + case .colorful: + return ObjectIconKind(tab: tab).map { ObjectIconProvider.icon(for: $0, style: .colorful) } + } } /// A located title already names its database, so on an engine whose containers are databases diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+RecentTabs.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+RecentTabs.swift index e9068e4b76..d2db411593 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+RecentTabs.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+RecentTabs.swift @@ -125,6 +125,7 @@ internal extension MainSplitViewController { func recentTabCandidates() -> [RecentTabCandidate] { let hosted = recentTabWorkspaces let namesConnection = hosted.count > 1 + let iconStyle = AppSettingsManager.shared.appearance.objectIconStyle var rows: [RecentTabReference: RecentTabCandidate] = [:] for workspace in hosted { @@ -135,6 +136,7 @@ internal extension MainSplitViewController { for tab in tabs { let reference = RecentTabReference(connectionId: workspace.connectionId, tabId: tab.id) let title = labels[tab.id]?.text ?? tab.title + let icon = Self.recentTabIcon(for: tab, style: iconStyle) rows[reference] = RecentTabCandidate( reference: reference, title: title, @@ -142,7 +144,8 @@ internal extension MainSplitViewController { container: Self.recentTabContainer(of: tab, title: title, target: target), connectionName: connectionName ), - symbolName: Self.recentTabSymbol(for: tab) + symbolName: icon.symbolName, + symbolTint: icon.tint ) } } @@ -191,6 +194,14 @@ internal extension MainSplitViewController { [container, connectionName].compactMap { $0 }.joined(separator: ", ") } + /// The standard style keeps this switcher's own glyphs, which name the kind of tab rather than + /// the kind of object: every object source tab shared one. + static func recentTabIcon(for tab: QueryTab, style: ObjectIconStyle) -> ObjectIcon { + let standard = recentTabSymbol(for: tab) + guard let kind = ObjectIconKind(tab: tab) else { return ObjectIcon(symbolName: standard) } + return ObjectIconProvider.icon(for: kind, style: style, standard: standard) + } + private static func recentTabSymbol(for tab: QueryTab) -> String { switch tab.tabType { case .query: diff --git a/apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift b/apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift index 7331dc80a3..29b6adebf6 100644 --- a/apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift +++ b/apple/TablePro/Core/Services/Query/ObjectListingPresentation.swift @@ -440,7 +440,6 @@ internal enum ObjectListingColumnLayout { internal struct ObjectListingRow: Equatable, Identifiable, Sendable { let id: RowID let item: ObjectListingItem - let iconName: String /// The drawn text of each value, by value index. let texts: [String] let sortKeys: [ObjectListingSortKey] @@ -472,7 +471,7 @@ internal enum ObjectListingRowBuilder { texts.append(formatter.display(row[index], as: format)) keys.append(formatter.sortKey(row[index], as: format)) } - return ObjectListingRow(id: row.id, item: item, iconName: item.iconName, texts: texts, sortKeys: keys) + return ObjectListingRow(id: row.id, item: item, texts: texts, sortKeys: keys) } } @@ -496,11 +495,12 @@ internal enum ObjectListingRowBuilder { } extension ObjectListingItem { - /// The glyph the sidebar draws for the same object. - var iconName: String { + /// The kind the sidebar draws the same object as. A type is drawn as the Types section is, not + /// by its own shape. + var iconKind: ObjectIconKind { switch self { - case .relation(_, _, let type): return TableRowLogic.iconName(for: type) - case .sourced(let ref): return ref.kind.iconName + case .relation(_, _, let type): return .relation(type) + case .sourced(let ref): return ObjectIconKind(ref.kind.sidebarObjectKind) } } } diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 42b5795d14..59b513bf1c 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -38,6 +38,9 @@ final class AppSettingsManager: ObservableObject { lightThemeId: appearance.preferredLightThemeId, darkThemeId: appearance.preferredDarkThemeId ) + if oldValue.objectIconStyle != appearance.objectIconStyle { + appEvents.objectIconStyleChanged.send(appearance.objectIconStyle) + } syncTracker.markDirty(.settings, id: AppSettingsCategory.appearance) } } diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index 7ec75a24b0..eb26efd0d0 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -17,23 +17,45 @@ enum AppAppearanceMode: String, Codable, CaseIterable { case auto } +/// How the sidebar, the tabs and the object lists draw a database object's glyph. +enum ObjectIconStyle: String, Codable, CaseIterable, Identifiable { + /// The outline glyphs every surface drew before the style existed, each in its surface's color. + case standard + /// A filled glyph in a system hue per kind of object, so a table, a view and a function are told + /// apart before their names are read. + case colorful + + var id: String { rawValue } + + var displayName: String { + switch self { + case .standard: return String(localized: "Standard") + case .colorful: return String(localized: "Colorful") + } + } +} + // The appearance mode is not here: it is per Mac (`AppSettingsManager.appearanceMode`), and this // struct is the synced `appearance` category. struct AppearanceSettings: Codable, Equatable { var preferredLightThemeId: String var preferredDarkThemeId: String + var objectIconStyle: ObjectIconStyle static let `default` = AppearanceSettings( preferredLightThemeId: BuiltInThemes.defaultLightId, - preferredDarkThemeId: BuiltInThemes.defaultDarkId + preferredDarkThemeId: BuiltInThemes.defaultDarkId, + objectIconStyle: .standard ) init( preferredLightThemeId: String = BuiltInThemes.defaultLightId, - preferredDarkThemeId: String = BuiltInThemes.defaultDarkId + preferredDarkThemeId: String = BuiltInThemes.defaultDarkId, + objectIconStyle: ObjectIconStyle = .standard ) { self.preferredLightThemeId = preferredLightThemeId self.preferredDarkThemeId = preferredDarkThemeId + self.objectIconStyle = objectIconStyle } init(from decoder: Decoder) throws { @@ -41,10 +63,11 @@ struct AppearanceSettings: Codable, Equatable { let fallback = Self.default preferredLightThemeId = container.decodeSetting(.preferredLightThemeId, default: fallback.preferredLightThemeId) preferredDarkThemeId = container.decodeSetting(.preferredDarkThemeId, default: fallback.preferredDarkThemeId) + objectIconStyle = container.decodeSetting(.objectIconStyle, default: fallback.objectIconStyle) } private enum CodingKeys: String, CodingKey { - case preferredLightThemeId, preferredDarkThemeId + case preferredLightThemeId, preferredDarkThemeId, objectIconStyle } } diff --git a/apple/TablePro/Models/UI/ObjectIcon.swift b/apple/TablePro/Models/UI/ObjectIcon.swift new file mode 100644 index 0000000000..0fcb99aa37 --- /dev/null +++ b/apple/TablePro/Models/UI/ObjectIcon.swift @@ -0,0 +1,175 @@ +// +// ObjectIcon.swift +// TablePro +// + +import Foundation + +/// What an object glyph stands for, on every surface that draws one: the sidebar, the editor tabs, +/// the Objects list, the quick switcher and the recent tab switcher. +internal enum ObjectIconKind: Hashable, Sendable { + case database + case systemDatabase + case schema + case externalSchema + case relation(TableInfo.TableType) + case partition + case routine(RoutineInfo.Kind) + case trigger + case userType(UserDefinedTypeInfo.Kind) + /// The row or tab that lists one kind of object, such as the Tables section. + case section(SidebarObjectKind) + case tableFolder + case query + case savedQuery + case user + + /// The kind a section, an Objects tab or a menu of one kind of object stands for. + internal init(_ kind: SidebarObjectKind) { + switch kind { + case .table: self = .relation(.table) + case .view: self = .relation(.view) + case .materializedView: self = .relation(.materializedView) + case .foreignTable: self = .relation(.foreignTable) + case .sequence: self = .relation(.sequence) + case .procedure: self = .routine(.procedure) + case .function: self = .routine(.function) + case .trigger: self = .trigger + case .type: self = .userType(.other) + } + } + + internal init(_ ref: DatabaseObjectRef) { + switch ref.kind { + case .procedure: self = .routine(.procedure) + case .function: self = .routine(.function) + case .trigger: self = .trigger + case .userType: self = .userType(ref.typeKind ?? .other) + case .view: self = .relation(.view) + case .materializedView: self = .relation(.materializedView) + } + } + + /// The object a tab shows, or nil for a tool tab that shows none, such as the ER diagram. + internal init?(tab: QueryTab) { + switch tab.tabType { + case .query: + self = .query + case .table: + self = .relation(tab.tableContext.resolvedObjectKind()) + case .objectSource: + guard let ref = tab.display.objectRef else { return nil } + self = ObjectIconKind(ref) + case .tableListing: + self = .section(tab.display.listingKind ?? .table) + case .usersRoles: + self = .user + case .createTable, .erDiagram, .serverDashboard, .insights, .tableHealth, .versionHistory, + .routineDebug, .liveMessages: + return nil + } + } +} + +/// A system hue, so the glyph follows Light, Dark and Increase Contrast like the rest of the chrome. +internal enum ObjectIconTint: String, CaseIterable, Sendable { + case gray + case green + case teal + case blue + case cyan + case indigo + case purple + case orange + case yellow + case pink + case mint + case brown +} + +internal struct ObjectIcon: Equatable, Sendable { + internal let symbolName: String + /// Nil in the standard style: the surface draws the glyph in the color it always used, which is + /// the accent on a sidebar object and the label color on a database or schema row. + internal let tint: ObjectIconTint? + + internal init(symbolName: String, tint: ObjectIconTint? = nil) { + self.symbolName = symbolName + self.tint = tint + } +} + +/// The one place that decides which glyph and which hue a kind of object wears in each style. +/// +/// The standard style is the look from before the setting existed, glyph for glyph: a surface whose +/// glyph for a kind differed from the sidebar's passes it as `standard`, so turning the style back +/// off restores every surface exactly. The colorful set is original: SF Symbols with a fill where +/// one exists, each in its kind's system hue. +internal enum ObjectIconProvider { + internal static func icon( + for kind: ObjectIconKind, + style: ObjectIconStyle, + standard: String? = nil + ) -> ObjectIcon { + switch style { + case .standard: + return ObjectIcon(symbolName: standard ?? standardSymbolName(for: kind)) + case .colorful: + return colorfulIcon(for: kind) + } + } + + /// The sidebar's glyph for the kind. + internal static func standardSymbolName(for kind: ObjectIconKind) -> String { + switch kind { + case .database: return "cylinder" + case .systemDatabase: return "gearshape" + case .schema: return "folder" + case .externalSchema: return "folder.badge.gearshape" + case .relation(let type): return TableRowLogic.iconName(for: type) + case .partition: return SidebarPartitionRow.iconName + case .routine(let kind): return RoutineRowLogic.iconName(for: kind) + case .trigger: return SidebarObjectKind.trigger.iconName + case .userType(let kind): return kind.iconName + case .section(let kind): return kind.iconName + case .tableFolder: return "folder" + case .query: return "doc.text" + case .savedQuery: return "star" + case .user: return "person.2" + } + } + + internal static func colorfulIcon(for kind: ObjectIconKind) -> ObjectIcon { + switch kind { + case .database: return ObjectIcon(symbolName: "cylinder.split.1x2.fill", tint: .green) + case .systemDatabase: return ObjectIcon(symbolName: "gearshape.fill", tint: .gray) + case .schema: return ObjectIcon(symbolName: "square.stack.3d.up.fill", tint: .teal) + case .externalSchema: return ObjectIcon(symbolName: "square.stack.3d.forward.dottedline.fill", tint: .teal) + case .relation(let type): return colorfulRelation(type) + case .partition: return ObjectIcon(symbolName: "rectangle.split.3x1.fill", tint: .blue) + case .routine(.function): return ObjectIcon(symbolName: "function", tint: .purple) + case .routine(.procedure): return ObjectIcon(symbolName: "curlybraces.square.fill", tint: .orange) + case .trigger: return ObjectIcon(symbolName: "bolt.fill", tint: .yellow) + // One glyph for every kind of type: the hue names the object, and the tooltip names its shape. + case .userType: return ObjectIcon(symbolName: "t.square.fill", tint: .pink) + case .section(let objectKind): + return ObjectIcon(symbolName: "folder.fill", tint: colorfulIcon(for: ObjectIconKind(objectKind)).tint) + case .tableFolder: return ObjectIcon(symbolName: "folder.fill", tint: .blue) + case .query, .savedQuery: return ObjectIcon(symbolName: "doc.text.fill", tint: .orange) + case .user: return ObjectIcon(symbolName: "person.fill", tint: .brown) + } + } + + private static func colorfulRelation(_ type: TableInfo.TableType) -> ObjectIcon { + switch type { + case .table: return ObjectIcon(symbolName: "tablecells.fill", tint: .blue) + case .view: return ObjectIcon(symbolName: "eyeglasses", tint: .cyan) + case .materializedView: return ObjectIcon(symbolName: "eyeglasses", tint: .indigo) + case .foreignTable: return ObjectIcon(symbolName: "link.circle.fill", tint: .blue) + case .systemTable: return ObjectIcon(symbolName: "tablecells.fill.badge.ellipsis", tint: .gray) + case .partitionedTable: return ObjectIcon(symbolName: "rectangle.split.3x1.fill", tint: .blue) + case .externalTable: return ObjectIcon(symbolName: "externaldrive.connected.to.line.below.fill", tint: .blue) + case .sequence: return ObjectIcon(symbolName: "number.square.fill", tint: .mint) + } + } +} diff --git a/apple/TablePro/Models/UI/QuickSwitcherItem.swift b/apple/TablePro/Models/UI/QuickSwitcherItem.swift index b3757faadb..3b1d2b296f 100644 --- a/apple/TablePro/Models/UI/QuickSwitcherItem.swift +++ b/apple/TablePro/Models/UI/QuickSwitcherItem.swift @@ -159,6 +159,31 @@ internal struct QuickSwitcherItem: Identifiable, Hashable, Sendable { } } + /// The object the row stands for, or nil for a history entry, which keeps its own glyph in + /// either style. + var iconKind: ObjectIconKind? { + switch kind { + case .table: return .relation(tableType ?? .table) + case .view: return .relation(tableType ?? .view) + case .systemTable: return .relation(.systemTable) + case .database: return .database + case .schema: return .schema + case .procedure: return .routine(.procedure) + case .function: return .routine(.function) + case .trigger: return .trigger + case .userType: return .userType(objectRef?.typeKind ?? .other) + case .savedQuery: return .savedQuery + case .queryHistory: return nil + } + } + + /// The standard style keeps this list's own glyphs, coarser than the sidebar's: every table + /// kind reads as a table here. + func icon(style: ObjectIconStyle) -> ObjectIcon { + guard let iconKind else { return ObjectIcon(symbolName: iconName) } + return ObjectIconProvider.icon(for: iconKind, style: style, standard: iconName) + } + /// Localized display label for the item kind var kindLabel: String { switch kind { diff --git a/apple/TablePro/Views/Main/EditorTabStrip.swift b/apple/TablePro/Views/Main/EditorTabStrip.swift index 9ae5884984..86992d5730 100644 --- a/apple/TablePro/Views/Main/EditorTabStrip.swift +++ b/apple/TablePro/Views/Main/EditorTabStrip.swift @@ -160,7 +160,12 @@ internal struct EditorTabStrip: View { } private var labels: [UUID: EditorTabLabelResolver.Label] { - EditorTabLabelResolver.resolve(tabs: displayedTabs, target: containerTarget, style: titleStyle) + EditorTabLabelResolver.resolve( + tabs: displayedTabs, + target: containerTarget, + style: titleStyle, + iconStyle: settings.appearance.objectIconStyle + ) } private var titleStyle: EditorTabTitleStyle { @@ -351,10 +356,10 @@ private struct EditorTabStripItem: View { .foregroundStyle(titleColor) .accessibilityHidden(true) } - if let symbolName = label.symbolName { - Image(systemName: symbolName) + if let icon = label.icon { + icon.image .font(.system(size: EditorTabStripLayout.objectGlyphSize)) - .foregroundStyle(titleColor) + .foregroundStyle(glyphColor(for: icon)) .accessibilityHidden(true) } Text(label.text) @@ -460,6 +465,13 @@ private struct EditorTabStripItem: View { return Color(nsColor: isSelected ? .labelColor : .secondaryLabelColor) } + /// A hue only while the window is active: an inactive window's tabs step down to the label + /// colors, and a glyph left in full color would be the brightest thing in the strip. + private func glyphColor(for icon: ObjectIcon) -> Color { + guard isWindowActive, let tint = icon.tint else { return titleColor } + return tint.color + } + /// Shown for the tab in front at all times, and for any tab the pointer is over, so closing /// the visible tab never needs a hunt for its button. @ViewBuilder diff --git a/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift b/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift index c18dec0af5..5d2c01c741 100644 --- a/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift +++ b/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift @@ -96,6 +96,8 @@ struct QuickSwitcherPanelContent: View { @Environment(\.colorSchemeContrast) private var colorSchemeContrast @ObservedObject var viewModel: QuickSwitcherViewModel + /// Observed so the glyphs follow the object icon style while the panel is open. + @ObservedObject private var settings = AppSettingsManager.shared let onCommit: (QuickSwitcherItem, QuickSwitcherCommitIntent) -> Void var body: some View { @@ -320,9 +322,10 @@ struct QuickSwitcherPanelContent: View { } private func iconView(for item: QuickSwitcherItem, isSelected: Bool) -> some View { - Image(systemName: item.iconName) + let icon = item.icon(style: settings.appearance.objectIconStyle) + return icon.image .font(.system(size: 14, weight: .medium)) - .foregroundStyle(isSelected ? Color.emphasizedSelectionLabel : Color.secondary) + .foregroundStyle(isSelected ? Color.emphasizedSelectionLabel : icon.tint?.color ?? Color.secondary) .frame(width: QuickSwitcherMetrics.iconContainerSize, height: QuickSwitcherMetrics.iconContainerSize) .background( RoundedRectangle(cornerRadius: 6, style: .continuous) diff --git a/apple/TablePro/Views/RecentTabSwitcher/RecentTabSwitcherRow.swift b/apple/TablePro/Views/RecentTabSwitcher/RecentTabSwitcherRow.swift index 563d30b667..c38932d5f6 100644 --- a/apple/TablePro/Views/RecentTabSwitcher/RecentTabSwitcherRow.swift +++ b/apple/TablePro/Views/RecentTabSwitcher/RecentTabSwitcherRow.swift @@ -13,11 +13,18 @@ internal struct RecentTabSwitcherRow: View { isHighlighted ? Color.emphasizedSelectionLabel.opacity(0.85) : Color.secondary } + /// The highlight is the selected-content fill, where a hue would vanish, so it turns white as + /// the title does. + private var glyphColor: Color { + guard !isHighlighted, let tint = candidate.symbolTint else { return secondary } + return tint.color + } + var body: some View { HStack(spacing: 10) { Image(systemName: candidate.symbolName) .font(.callout.weight(.medium)) - .foregroundStyle(secondary) + .foregroundStyle(glyphColor) .frame(width: 18) .accessibilityHidden(true) diff --git a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift index 504099bb28..cf72bd9b52 100644 --- a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift +++ b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift @@ -37,6 +37,17 @@ 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 { + Picker(String(localized: "Object Icons"), selection: $settings.objectIconStyle) { + ForEach(ObjectIconStyle.allCases) { style in + Text(style.displayName).tag(style) + } + } + .accessibilityIdentifier("appearance-object-icon-style") + } footer: { + Text("Colorful gives each kind of object its own filled, colored icon in the sidebar, the tabs and the object lists.") + } } .formStyle(.grouped) .scrollDisabled(true) diff --git a/apple/TablePro/Views/Shared/ObjectIconImage.swift b/apple/TablePro/Views/Shared/ObjectIconImage.swift new file mode 100644 index 0000000000..8715822eb1 --- /dev/null +++ b/apple/TablePro/Views/Shared/ObjectIconImage.swift @@ -0,0 +1,47 @@ +// +// ObjectIconImage.swift +// TablePro +// + +import AppKit +import SwiftUI + +extension ObjectIconTint { + /// System colors, never a theme slot: an object's hue is identity, which stays system. + internal var nsColor: NSColor { + switch self { + case .gray: return .systemGray + case .green: return .systemGreen + case .teal: return .systemTeal + case .blue: return .systemBlue + case .cyan: return .systemCyan + case .indigo: return .systemIndigo + case .purple: return .systemPurple + case .orange: return .systemOrange + case .yellow: return .systemYellow + case .pink: return .systemPink + case .mint: return .systemMint + case .brown: return .systemBrown + } + } + + internal var color: Color { Color(nsColor: nsColor) } +} + +extension ObjectIcon { + internal var image: Image { Image(systemName: symbolName) } +} + +extension View { + /// Tints an object glyph in its kind's hue, or in `standard`, the color the row drew it in + /// before the icon style existed. Either one turns to the selected-content color on a prominent + /// selection. With neither, the glyph keeps the row's own foreground. + @ViewBuilder + internal func objectIconTint(_ icon: ObjectIcon, standard: Color? = nil) -> some View { + if let color = icon.tint?.color ?? standard { + selectionAwareTint(color) + } else { + self + } + } +} diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift index 315ff71ee4..90dc23d49c 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeCellView.swift @@ -10,9 +10,21 @@ import SwiftUI /// rename field is `RenamableSidebarCellView`'s; this only knows how to turn a node into the row /// it draws, and which glyph that row wears while it is being renamed. final class DatabaseTreeCellView: RenamableSidebarCellView { - private var renameSymbolName = "tablecells" + private var renameGlyph = RenameGlyph.symbol("tablecells") - override var editorSymbolName: String { renameSymbolName } + /// Resolved when asked rather than when configured, so a rename begun after the icon style + /// changed wears the new glyph, as the hosted row already does. + var renameIcon: ObjectIcon { + switch renameGlyph { + case .object(let kind): + return ObjectIconProvider.icon(for: kind, style: AppSettingsManager.shared.appearance.objectIconStyle) + case .symbol(let name): + return ObjectIcon(symbolName: name) + } + } + + override var editorSymbolName: String { renameIcon.symbolName } + override var editorSymbolTint: NSColor? { renameIcon.tint?.nsColor } override var editorAccessibilityIdentifier: String { "database-tree-rename-field" } func configure( @@ -21,7 +33,7 @@ final class DatabaseTreeCellView: RenamableSidebarCellView context: DatabaseTreeRowContext, actions: DatabaseTreeRowActions ) { - renameSymbolName = Self.symbolName(for: node) + renameGlyph = Self.renameGlyph(for: node) update(rootView: DatabaseTreeRowView( node: node, isFavorite: isFavorite, @@ -30,23 +42,32 @@ final class DatabaseTreeCellView: RenamableSidebarCellView )) } - private static func symbolName(for node: DatabaseTreeNode) -> String { + private enum RenameGlyph { + case object(ObjectIconKind) + case symbol(String) + } + + private static func renameGlyph(for node: DatabaseTreeNode) -> RenameGlyph { switch node.kind { case .table(let ref), .recentTable(let ref), .favoriteTable(let ref), .temporaryTable(let ref): - return TableRowLogic.iconName(for: ref.table.type) + return .object(.relation(ref.table.type)) case .partition: - return SidebarPartitionRow.iconName + return .object(.partition) case .database(let metadata): - return metadata.isSystemDatabase ? "gearshape" : "cylinder" - case .schema, .tableFolder, .connectionGroup: - return "folder" + return .object(metadata.isSystemDatabase ? .systemDatabase : .database) + case .schema: + return .object(.schema) + case .tableFolder: + return .object(.tableFolder) + case .connectionGroup: + return .symbol("folder") case .savedConnection: - return "server.rack" + return .symbol("server.rack") case .routine, .trigger, .userType, .status, .recentSection, .favoritesSection, .temporarySection, .foldersSection, .objectKindSection, .containerObjectKindSection, .hierarchicalSchemaSection, .redisKeysSection, .redisNode, .tableDetailGroup, .tableDetail: - return "tablecells" + return .symbol("tablecells") } } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift index ab10a2505e..8782243c4c 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift @@ -71,6 +71,10 @@ struct DatabaseTreeRowView: View { @State private var isHovered = false + private func objectIcon(_ kind: ObjectIconKind) -> ObjectIcon { + ObjectIconProvider.icon(for: kind, style: settingsManager.appearance.objectIconStyle) + } + /// 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 @@ -95,13 +99,13 @@ struct DatabaseTreeRowView: View { case .savedConnection(let ref): ConnectionNavigatorConnectionLabel(row: ref.row, glyphSide: context.rowSize.iconPointSize) case .recentSection: - sectionHeader(String(localized: "Recent"), systemImage: "clock") + sectionHeader(String(localized: "Recent"), icon: ObjectIcon(symbolName: "clock")) case .recentTable(let ref), .favoriteTable(let ref): tableRow(ref) case .favoritesSection: - sectionHeader(String(localized: "Favorites"), systemImage: "star") + sectionHeader(String(localized: "Favorites"), icon: ObjectIcon(symbolName: "star")) case .temporarySection: - sectionHeader(String(localized: "Temporary"), systemImage: "hourglass") + sectionHeader(String(localized: "Temporary"), icon: ObjectIcon(symbolName: "hourglass")) case .temporaryTable(let ref): TableRow( table: ref.table, @@ -111,17 +115,17 @@ struct DatabaseTreeRowView: View { accessibilityKind: String(localized: "Temporary Table") ) case .foldersSection: - sectionHeader(String(localized: "Folders"), systemImage: "folder") + sectionHeader(String(localized: "Folders"), icon: ObjectIcon(symbolName: "folder")) case .tableFolder(let ref): folderRow(ref) case .database(let metadata): databaseRow(metadata) case .schema(_, let schema) where context.listsAttachedSchemas: - header(text: schema, systemImage: "cylinder", isActive: false, isSystem: false, caption: nil) + header(text: schema, icon: objectIcon(.database), isActive: false, isSystem: false, caption: nil) case .schema(let database, let schema): header( text: schema, - systemImage: context.isExternalSchema(database, schema) ? "folder.badge.gearshape" : "folder", + icon: objectIcon(context.isExternalSchema(database, schema) ? .externalSchema : .schema), isActive: database == context.activeDatabase && schema == context.activeSchema, isSystem: context.systemSchemas.contains(schema), caption: context.isExternalSchema(database, schema) ? String(localized: "External") : nil @@ -143,18 +147,18 @@ struct DatabaseTreeRowView: View { case .status(let status): statusRow(status) case .objectKindSection(let kind): - sectionHeader(context.objectKindTitle(kind), systemImage: kind.iconName) + sectionHeader(context.objectKindTitle(kind), icon: objectIcon(.section(kind))) case .containerObjectKindSection(let group): objectGroupRow(group.kind) case .hierarchicalSchemaSection(let schema): header( text: schema, - systemImage: "folder", + icon: objectIcon(.schema), isActive: schema == context.activeSchema, isSystem: false ) case .redisKeysSection: - sectionHeader(String(localized: "Keys"), systemImage: "key") + sectionHeader(String(localized: "Keys"), icon: ObjectIcon(symbolName: "key")) case .redisNode(let redisNode): redisRow(redisNode) } @@ -165,11 +169,15 @@ struct DatabaseTreeRowView: View { /// competing with the one on every object below it. Drawn as an ordinary row it takes the icon /// every other row at its depth has. @ViewBuilder - private func sectionHeader(_ text: String, systemImage: String) -> some View { + private func sectionHeader(_ text: String, icon: ObjectIcon) -> some View { if context.drawsSectionsAsRows { - Label(text, systemImage: systemImage) - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) - .lineLimit(1) + Label { + Text(text) + } icon: { + icon.image.objectIconTint(icon) + } + .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .lineLimit(1) } else { Text(text) .font(.caption.weight(.semibold)) @@ -188,7 +196,8 @@ struct DatabaseTreeRowView: View { .foregroundStyle(.secondary) } } icon: { - Image(systemName: "folder") + let icon = objectIcon(.tableFolder) + icon.image.objectIconTint(icon) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) .accessibilityElement(children: .combine) @@ -196,9 +205,14 @@ struct DatabaseTreeRowView: View { } private func objectGroupRow(_ kind: SidebarObjectKind) -> some View { - Label(context.objectKindTitle(kind), systemImage: kind.iconName) - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) - .lineLimit(1) + let icon = objectIcon(.section(kind)) + return Label { + Text(context.objectKindTitle(kind)) + } icon: { + icon.image.objectIconTint(icon) + } + .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .lineLimit(1) } private func databaseRow(_ metadata: DatabaseMetadata) -> some View { @@ -206,7 +220,7 @@ struct DatabaseTreeRowView: View { return HStack(spacing: 6) { header( text: metadata.name, - systemImage: metadata.isSystemDatabase ? "gearshape" : "cylinder", + icon: objectIcon(metadata.isSystemDatabase ? .systemDatabase : .database), isActive: metadata.name == context.activeDatabase, isSystem: metadata.isSystemDatabase ) @@ -268,8 +282,9 @@ struct DatabaseTreeRowView: View { } } } icon: { - Image(systemName: SidebarPartitionRow.iconName) - .selectionAwareTint(Color.accentColor) + let icon = objectIcon(.partition) + icon.image + .objectIconTint(icon, standard: Color.accentColor) .frame(width: 16) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) @@ -321,7 +336,7 @@ struct DatabaseTreeRowView: View { private func header( text: String, - systemImage: String, + icon: ObjectIcon, isActive: Bool, isSystem: Bool, caption: String? = nil @@ -337,7 +352,7 @@ struct DatabaseTreeRowView: View { } } } icon: { - Image(systemName: systemImage) + icon.image.objectIconTint(icon) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) .lineLimit(1) diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index 08ec6fb5fd..668752ca55 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -433,14 +433,19 @@ internal struct FavoritesTabView: View { } private func favoriteDatabaseRow(_ entry: FavoriteDatabaseEntry) -> some View { - Label(entry.database, systemImage: "cylinder") - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) - .lineLimit(1) - .accessibilityLabel(String( - format: String(localized: "%@: %@"), - databaseEntityName, - entry.database - )) + let icon = ObjectIconProvider.icon(for: .database, style: settingsManager.appearance.objectIconStyle) + return Label { + Text(entry.database) + } icon: { + icon.image.objectIconTint(icon) + } + .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .lineLimit(1) + .accessibilityLabel(String( + format: String(localized: "%@: %@"), + databaseEntityName, + entry.database + )) } @ViewBuilder @@ -495,7 +500,11 @@ internal struct FavoritesTabView: View { } private func favoriteTableRow(_ row: FavoriteTableRow) -> some View { - Label { + let icon = ObjectIconProvider.icon( + for: .relation(row.table.type), + style: settingsManager.appearance.objectIconStyle + ) + return Label { HStack(spacing: 6) { Text(row.entry.name) .lineLimit(1) @@ -508,8 +517,8 @@ internal struct FavoritesTabView: View { } } } icon: { - Image(systemName: TableRowLogic.iconName(for: row.table.type)) - .selectionAwareTint(Color.accentColor) + icon.image + .objectIconTint(icon, standard: Color.accentColor) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) .accessibilityLabel( diff --git a/apple/TablePro/Views/Sidebar/RenamableSidebarCellView.swift b/apple/TablePro/Views/Sidebar/RenamableSidebarCellView.swift index f38d7f93ee..587e4edf06 100644 --- a/apple/TablePro/Views/Sidebar/RenamableSidebarCellView.swift +++ b/apple/TablePro/Views/Sidebar/RenamableSidebarCellView.swift @@ -25,11 +25,19 @@ internal class RenamableSidebarCellView: SidebarHostingCellView /// Overridden by a cell that draws more than one kind of row. internal var editorSymbolName: String { "folder" } + /// The glyph's hue in the colorful icon style, so the row keeps its look while it is renamed. + /// Nil leaves the template image to AppKit, which colors it for the row. + internal var editorSymbolTint: NSColor? { nil } internal var editorAccessibilityIdentifier: String { "sidebar-rename-field" } + override internal var backgroundStyle: NSView.BackgroundStyle { + didSet { applyEditorTint() } + } + internal func beginRename(text: String, delegate: any NSTextFieldDelegate) { let field = makeEditorIfNeeded() editorIcon?.image = NSImage(systemSymbolName: editorSymbolName, accessibilityDescription: nil) + applyEditorTint() field.stringValue = text field.delegate = delegate isRenaming = true @@ -56,6 +64,12 @@ internal class RenamableSidebarCellView: SidebarHostingCellView editorIcon?.isHidden = !isRenaming } + /// On the emphasized selection AppKit draws a template glyph in the selected-content color, as + /// the hosted row does; a hue there would sit on the accent fill. + private func applyEditorTint() { + editorIcon?.contentTintColor = backgroundStyle == .emphasized ? nil : editorSymbolTint + } + private func makeEditorIfNeeded() -> NSTextField { if let editorField { return editorField } diff --git a/apple/TablePro/Views/Sidebar/RoutineRowView.swift b/apple/TablePro/Views/Sidebar/RoutineRowView.swift index cc4515a5e2..56f796092d 100644 --- a/apple/TablePro/Views/Sidebar/RoutineRowView.swift +++ b/apple/TablePro/Views/Sidebar/RoutineRowView.swift @@ -41,14 +41,18 @@ struct RoutineRowView: View { let routine: RoutineInfo let displayLabel: String + private var objectIcon: ObjectIcon { + ObjectIconProvider.icon(for: .routine(routine.kind), style: settingsManager.appearance.objectIconStyle) + } + var body: some View { Label { Text(displayLabel) .lineLimit(1) .truncationMode(.tail) } icon: { - Image(systemName: RoutineRowLogic.iconName(for: routine.kind)) - .selectionAwareTint(Color.accentColor) + objectIcon.image + .objectIconTint(objectIcon, standard: Color.accentColor) .frame(width: 16) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) diff --git a/apple/TablePro/Views/Sidebar/TableRowView.swift b/apple/TablePro/Views/Sidebar/TableRowView.swift index 22f4ec55ab..0902d6409a 100644 --- a/apple/TablePro/Views/Sidebar/TableRowView.swift +++ b/apple/TablePro/Views/Sidebar/TableRowView.swift @@ -103,6 +103,10 @@ struct TableRow: View { settingsManager.general.showObjectIcons } + private var objectIcon: ObjectIcon { + ObjectIconProvider.icon(for: .relation(table.type), style: settingsManager.appearance.objectIconStyle) + } + private var showsLeadingIcon: Bool { TableRowLogic.showsLeadingIcon( showObjectIcons: showsObjectIcon, @@ -156,8 +160,8 @@ struct TableRow: View { } } icon: { if showsObjectIcon { - Image(systemName: TableRowLogic.iconName(for: table.type)) - .selectionAwareTint(Color.accentColor) + objectIcon.image + .objectIconTint(objectIcon, standard: Color.accentColor) .frame(width: 16) .overlay(alignment: .bottomTrailing) { pendingStateBadge diff --git a/apple/TablePro/Views/Sidebar/TriggerRowView.swift b/apple/TablePro/Views/Sidebar/TriggerRowView.swift index 7ad2f0b335..ad23c2eb82 100644 --- a/apple/TablePro/Views/Sidebar/TriggerRowView.swift +++ b/apple/TablePro/Views/Sidebar/TriggerRowView.swift @@ -44,6 +44,10 @@ struct TriggerRowView: View { let trigger: TriggerInfo var listedUnderTable = false + private var objectIcon: ObjectIcon { + ObjectIconProvider.icon(for: .trigger, style: settingsManager.appearance.objectIconStyle) + } + var body: some View { Label { HStack(spacing: 6) { @@ -59,8 +63,8 @@ struct TriggerRowView: View { } } } icon: { - Image(systemName: SidebarObjectKind.trigger.iconName) - .selectionAwareTint(Color.accentColor) + objectIcon.image + .objectIconTint(objectIcon, standard: Color.accentColor) .frame(width: 16) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) diff --git a/apple/TablePro/Views/Sidebar/UserTypeRowView.swift b/apple/TablePro/Views/Sidebar/UserTypeRowView.swift index 9b3bf88ead..44ead5dc80 100644 --- a/apple/TablePro/Views/Sidebar/UserTypeRowView.swift +++ b/apple/TablePro/Views/Sidebar/UserTypeRowView.swift @@ -35,14 +35,18 @@ struct UserTypeRowView: View { @ObservedObject private var settingsManager = AppSettingsManager.shared let type: UserDefinedTypeInfo + private var objectIcon: ObjectIcon { + ObjectIconProvider.icon(for: .userType(type.kind), style: settingsManager.appearance.objectIconStyle) + } + var body: some View { Label { Text(type.name) .lineLimit(1) .truncationMode(.tail) } icon: { - Image(systemName: type.kind.iconName) - .selectionAwareTint(Color.accentColor) + objectIcon.image + .objectIconTint(objectIcon, standard: Color.accentColor) .frame(width: 16) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) diff --git a/apple/TablePro/Views/TableListing/ObjectListingTableView.swift b/apple/TablePro/Views/TableListing/ObjectListingTableView.swift index 3d9bb82da8..393fdd1c44 100644 --- a/apple/TablePro/Views/TableListing/ObjectListingTableView.swift +++ b/apple/TablePro/Views/TableListing/ObjectListingTableView.swift @@ -72,6 +72,8 @@ internal final class ObjectListingTableCoordinator: NSObject { // Held here: its theme subscription and the row views hold it weakly. private var themeChrome: ThemeTableChrome? private var themeSubscription: AnyCancellable? + private var iconStyleSubscription: AnyCancellable? + private var iconStyle = AppSettingsManager.shared.appearance.objectIconStyle private var builtColumnIDs: [String] = [] private var appliedRevision: Int? private var isApplyingSort = false @@ -123,6 +125,8 @@ internal final class ObjectListingTableCoordinator: NSObject { themeChrome = ThemeTableChrome(tableView: tableView, family: .records) themeSubscription = ThemeScope.live.changes .sink { [weak self] _ in self?.restyleVisibleCells() } + iconStyleSubscription = AppEvents.shared.objectIconStyleChanged + .sink { [weak self] style in self?.applyIconStyle(style) } sync() return scrollView } @@ -283,6 +287,26 @@ internal final class ObjectListingTableCoordinator: NSObject { } } } + + // MARK: - Icon style + + private func icon(for row: ObjectListingRow) -> ObjectIcon { + ObjectIconProvider.icon(for: row.item.iconKind, style: iconStyle) + } + + /// A glyph is set when its cell is configured, so the cells on screen are given the new one; + /// the rest pick it up as they are configured. + private func applyIconStyle(_ style: ObjectIconStyle) { + iconStyle = style + guard let tableView else { return } + let nameIndex = tableView.column(withIdentifier: NSUserInterfaceItemIdentifier("name")) + guard nameIndex >= 0 else { return } + tableView.enumerateAvailableRowViews { rowView, index in + guard let row = row(at: index), + let cell = rowView.view(atColumn: nameIndex) as? ObjectListingCellView else { return } + cell.showGlyph(icon(for: row), label: row.item.kindName) + } + } } extension ObjectListingTableCoordinator: NSTableViewDataSource, NSTableViewDelegate { @@ -302,7 +326,7 @@ extension ObjectListingTableCoordinator: NSTableViewDataSource, NSTableViewDeleg cell.configure( text: text, alignsTrailing: column.format.alignsTrailing, - glyph: isName ? row.iconName : nil, + glyph: isName ? icon(for: row) : nil, glyphLabel: isName ? row.item.kindName : nil ) return cell @@ -358,6 +382,8 @@ internal final class ObjectListingCellView: NSTableCellView { private let label = NSTextField(labelWithString: "") private let glyph = NSImageView() + /// The colorful style's hue; nil draws the glyph in the accent, as the sidebar does. + private var glyphTint: NSColor? internal init(identifier: NSUserInterfaceItemIdentifier, showsGlyph: Bool) { super.init(frame: .zero) @@ -400,16 +426,23 @@ internal final class ObjectListingCellView: NSTableCellView { didSet { applyStyle() } } - internal func configure(text: String, alignsTrailing: Bool, glyph symbol: String?, glyphLabel: String?) { + internal func configure(text: String, alignsTrailing: Bool, glyph icon: ObjectIcon?, glyphLabel: String?) { label.stringValue = text label.alignment = alignsTrailing ? .right : .natural // Digits of one width, so counts and sizes line up down the column. label.font = alignsTrailing ? .monospacedDigitSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) : .systemFont(ofSize: NSFont.systemFontSize) - if let symbol { - glyph.image = NSImage(systemSymbolName: symbol, accessibilityDescription: glyphLabel) + if let icon { + showGlyph(icon, label: glyphLabel) + } else { + applyStyle() } + } + + internal func showGlyph(_ icon: ObjectIcon, label: String?) { + glyph.image = NSImage(systemSymbolName: icon.symbolName, accessibilityDescription: label) + glyphTint = icon.tint?.nsColor applyStyle() } @@ -422,7 +455,7 @@ internal final class ObjectListingCellView: NSTableCellView { ) label.textColor = slot.map { ThemeScope.live.palette[$0] } ?? .labelColor // The sidebar's tint for the same glyph, turning white on the emphasized selection as the text does. - glyph.contentTintColor = isEmphasized ? .alternateSelectedControlTextColor : .controlAccentColor + glyph.contentTintColor = isEmphasized ? .alternateSelectedControlTextColor : glyphTint ?? .controlAccentColor } } diff --git a/apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift b/apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift index 4ab5a6d9f7..b50913eef1 100644 --- a/apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift +++ b/apple/TableProTests/Core/Services/Query/ObjectListingPresentationTests.swift @@ -276,7 +276,8 @@ struct ObjectListingPresentationTests { let row = try #require(ObjectListingRowBuilder.rows(of: source, columns: columns, formatter: formatter).first) #expect(row.item == .relation(name: "orders", schema: nil, type: .table)) - #expect(row.iconName == TableRowLogic.iconName(for: .table)) + #expect(row.item.iconKind == .relation(.table)) + #expect(ObjectIconProvider.icon(for: row.item.iconKind, style: .standard).symbolName == TableRowLogic.iconName(for: .table)) #expect(row.texts[5] == "6,215,717") #expect(row.texts[7] == bytes(163_840)) #expect(row.texts[10] == "2026-08-12 08:05:33") @@ -294,7 +295,8 @@ struct ObjectListingPresentationTests { let row = try #require(ObjectListingRowBuilder.rows(of: built, columns: columns, formatter: formatter).first) - #expect(row.iconName == SidebarObjectKind.function.iconName) + #expect(row.item.iconKind == .routine(.function)) + #expect(ObjectIconProvider.icon(for: row.item.iconKind, style: .standard).symbolName == SidebarObjectKind.function.iconName) } @Test("Rows sort by a column's values as numbers, and equal values keep the listing's order") diff --git a/apple/TableProTests/Core/Storage/AppearanceModeStorageTests.swift b/apple/TableProTests/Core/Storage/AppearanceModeStorageTests.swift index 88944ae2a0..83ea070c35 100644 --- a/apple/TableProTests/Core/Storage/AppearanceModeStorageTests.swift +++ b/apple/TableProTests/Core/Storage/AppearanceModeStorageTests.swift @@ -81,7 +81,7 @@ struct AppearanceModeStorageTests { let data = try #require(defaults.data(forKey: Self.appearanceKey)) let object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) - #expect(Set(object.keys) == ["preferredLightThemeId", "preferredDarkThemeId"]) + #expect(Set(object.keys) == ["preferredLightThemeId", "preferredDarkThemeId", "objectIconStyle"]) } @Test("Reset returns the mode to Auto") diff --git a/apple/TableProTests/Core/Sync/SyncCoordinatorThemeTests.swift b/apple/TableProTests/Core/Sync/SyncCoordinatorThemeTests.swift index 06087c619b..1f72179d9c 100644 --- a/apple/TableProTests/Core/Sync/SyncCoordinatorThemeTests.swift +++ b/apple/TableProTests/Core/Sync/SyncCoordinatorThemeTests.swift @@ -372,7 +372,7 @@ struct SyncCoordinatorThemeTests { #expect(harness.engine.mode == .auto) } - @Test("The outgoing appearance record carries the theme ids and no mode") + @Test("The outgoing appearance record carries the theme ids and the icon style, and no mode") func outgoingPayloadCarriesNoMode() throws { let harness = try Harness(label: "theme-mode-out") harness.storage.saveAppearance(AppearanceSettings(preferredLightThemeId: "user.day", preferredDarkThemeId: "user.night")) @@ -381,7 +381,7 @@ struct SyncCoordinatorThemeTests { let data = try #require(harness.coordinator.settingsData(for: AppSettingsCategory.appearance)) let object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) - #expect(Set(object.keys) == ["preferredLightThemeId", "preferredDarkThemeId"]) + #expect(Set(object.keys) == ["preferredLightThemeId", "preferredDarkThemeId", "objectIconStyle"]) #expect(object["preferredDarkThemeId"] as? String == "user.night") } diff --git a/apple/TableProTests/Models/ObjectIconProviderTests.swift b/apple/TableProTests/Models/ObjectIconProviderTests.swift new file mode 100644 index 0000000000..fa5cd473c3 --- /dev/null +++ b/apple/TableProTests/Models/ObjectIconProviderTests.swift @@ -0,0 +1,208 @@ +// +// ObjectIconProviderTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct ObjectIconProviderTests { + /// Every glyph the sidebar drew for each kind before the icon style existed. + private static let standardSymbols: [(ObjectIconKind, String)] = [ + (.database, "cylinder"), + (.systemDatabase, "gearshape"), + (.schema, "folder"), + (.externalSchema, "folder.badge.gearshape"), + (.relation(.table), "tablecells"), + (.relation(.view), "eye"), + (.relation(.materializedView), "square.stack.3d.up"), + (.relation(.foreignTable), "link"), + (.relation(.systemTable), "tablecells.badge.ellipsis"), + (.relation(.partitionedTable), "rectangle.split.3x1"), + (.relation(.externalTable), "externaldrive.connected.to.line.below"), + (.relation(.sequence), "number"), + (.partition, "rectangle.split.3x1.fill"), + (.routine(.function), "function"), + (.routine(.procedure), "curlybraces.square"), + (.trigger, "bolt"), + (.userType(.enumeration), "list.bullet"), + (.userType(.composite), "rectangle.split.3x1"), + (.userType(.domain), "checkmark.seal"), + (.userType(.range), "arrow.left.and.right.square"), + (.userType(.aliasType), "character.textbox"), + (.userType(.tableType), "tablecells"), + (.userType(.clrType), "shippingbox"), + (.userType(.udt), "rectangle.split.3x1"), + (.userType(.other), "cube"), + (.section(.table), "tablecells"), + (.section(.view), "eye"), + (.section(.materializedView), "square.stack.3d.up"), + (.section(.foreignTable), "link"), + (.section(.sequence), "number"), + (.section(.procedure), "curlybraces.square"), + (.section(.function), "function"), + (.section(.trigger), "bolt"), + (.section(.type), "cube"), + (.tableFolder, "folder"), + (.query, "doc.text"), + (.savedQuery, "star"), + (.user, "person.2"), + ] + + private static let colorfulIcons: [(ObjectIconKind, ObjectIcon)] = [ + (.database, ObjectIcon(symbolName: "cylinder.split.1x2.fill", tint: .green)), + (.systemDatabase, ObjectIcon(symbolName: "gearshape.fill", tint: .gray)), + (.schema, ObjectIcon(symbolName: "square.stack.3d.up.fill", tint: .teal)), + (.externalSchema, ObjectIcon(symbolName: "square.stack.3d.forward.dottedline.fill", tint: .teal)), + (.relation(.table), ObjectIcon(symbolName: "tablecells.fill", tint: .blue)), + (.relation(.view), ObjectIcon(symbolName: "eyeglasses", tint: .cyan)), + (.relation(.materializedView), ObjectIcon(symbolName: "eyeglasses", tint: .indigo)), + (.relation(.foreignTable), ObjectIcon(symbolName: "link.circle.fill", tint: .blue)), + (.relation(.systemTable), ObjectIcon(symbolName: "tablecells.fill.badge.ellipsis", tint: .gray)), + (.relation(.partitionedTable), ObjectIcon(symbolName: "rectangle.split.3x1.fill", tint: .blue)), + (.relation(.externalTable), ObjectIcon(symbolName: "externaldrive.connected.to.line.below.fill", tint: .blue)), + (.relation(.sequence), ObjectIcon(symbolName: "number.square.fill", tint: .mint)), + (.partition, ObjectIcon(symbolName: "rectangle.split.3x1.fill", tint: .blue)), + (.routine(.function), ObjectIcon(symbolName: "function", tint: .purple)), + (.routine(.procedure), ObjectIcon(symbolName: "curlybraces.square.fill", tint: .orange)), + (.trigger, ObjectIcon(symbolName: "bolt.fill", tint: .yellow)), + (.userType(.enumeration), ObjectIcon(symbolName: "t.square.fill", tint: .pink)), + (.userType(.other), ObjectIcon(symbolName: "t.square.fill", tint: .pink)), + (.section(.table), ObjectIcon(symbolName: "folder.fill", tint: .blue)), + (.section(.view), ObjectIcon(symbolName: "folder.fill", tint: .cyan)), + (.section(.function), ObjectIcon(symbolName: "folder.fill", tint: .purple)), + (.section(.type), ObjectIcon(symbolName: "folder.fill", tint: .pink)), + (.tableFolder, ObjectIcon(symbolName: "folder.fill", tint: .blue)), + (.query, ObjectIcon(symbolName: "doc.text.fill", tint: .orange)), + (.savedQuery, ObjectIcon(symbolName: "doc.text.fill", tint: .orange)), + (.user, ObjectIcon(symbolName: "person.fill", tint: .brown)), + ] + + /// Every kind there is, so a glyph added to either style is checked against the system. + private static var everyKind: [ObjectIconKind] { + var kinds: [ObjectIconKind] = [ + .database, .systemDatabase, .schema, .externalSchema, .partition, .trigger, .tableFolder, + .query, .savedQuery, .user, + ] + kinds += TableInfo.TableType.allCases.map { .relation($0) } + kinds += RoutineInfo.Kind.allCases.map { .routine($0) } + kinds += UserDefinedTypeInfo.Kind.allCases.map { .userType($0) } + kinds += SidebarObjectKind.allCases.map { .section($0) } + return kinds + } + + @Test("The standard style draws today's glyph for every kind, untinted") + func standardStyleKeepsTodaysGlyphs() { + for (kind, symbol) in Self.standardSymbols { + #expect(ObjectIconProvider.icon(for: kind, style: .standard) == ObjectIcon(symbolName: symbol), "\(kind)") + } + #expect(Self.standardSymbols.count == Self.everyKind.count) + } + + @Test("The standard style draws a surface's own glyph when the surface names one") + func standardStyleKeepsASurfacesGlyph() { + let icon = ObjectIconProvider.icon(for: .relation(.systemTable), style: .standard, standard: "gearshape") + let colorful = ObjectIconProvider.icon(for: .relation(.systemTable), style: .colorful, standard: "gearshape") + + #expect(icon == ObjectIcon(symbolName: "gearshape")) + #expect(colorful.symbolName == "tablecells.fill.badge.ellipsis") + } + + @Test("The colorful style gives each kind its glyph and its hue") + func colorfulStylePinsTheSet() { + for (kind, icon) in Self.colorfulIcons { + #expect(ObjectIconProvider.icon(for: kind, style: .colorful) == icon, "\(kind)") + } + } + + @Test("Every kind is tinted in the colorful style") + func colorfulStyleTintsEveryKind() { + for kind in Self.everyKind { + #expect(ObjectIconProvider.icon(for: kind, style: .colorful).tint != nil, "\(kind)") + } + } + + @Test("A section folder wears the hue of the objects it holds") + func sectionsTakeTheirKindsHue() { + for kind in SidebarObjectKind.allCases { + let section = ObjectIconProvider.icon(for: .section(kind), style: .colorful) + let object = ObjectIconProvider.icon(for: ObjectIconKind(kind), style: .colorful) + #expect(section.symbolName == "folder.fill") + #expect(section.tint == object.tint, "\(kind)") + } + } + + @Test("Every glyph in both styles is a symbol the system has") + func everySymbolExists() { + for kind in Self.everyKind { + for style in ObjectIconStyle.allCases { + let name = ObjectIconProvider.icon(for: kind, style: style).symbolName + #expect(NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil, "\(name)") + } + } + } + + @Test("Each hue is the system color, so it follows the appearance and Increase Contrast") + func tintsAreSystemColors() { + #expect(ObjectIconTint.blue.nsColor == .systemBlue) + #expect(ObjectIconTint.cyan.nsColor == .systemCyan) + #expect(ObjectIconTint.mint.nsColor == .systemMint) + #expect(ObjectIconTint.brown.nsColor == .systemBrown) + #expect(Set(ObjectIconTint.allCases.map(\.nsColor)).count == ObjectIconTint.allCases.count) + } + + // MARK: - Surfaces + + @Test("The quick switcher keeps its own glyphs in the standard style and the kind's in the colorful one") + func quickSwitcherItems() { + var sequence = QuickSwitcherItem(frecencyKey: "s", name: "order_id_seq", kind: .table, subtitle: "") + sequence.tableType = .sequence + let system = QuickSwitcherItem(frecencyKey: "p", name: "pg_class", kind: .systemTable, subtitle: "") + let saved = QuickSwitcherItem(frecencyKey: "q", name: "Top customers", kind: .savedQuery, subtitle: "") + let history = QuickSwitcherItem(frecencyKey: "h", name: "SELECT 1", kind: .queryHistory, subtitle: "") + + #expect(sequence.icon(style: .standard) == ObjectIcon(symbolName: "tablecells")) + #expect(system.icon(style: .standard) == ObjectIcon(symbolName: "gearshape")) + #expect(saved.icon(style: .standard) == ObjectIcon(symbolName: "star")) + #expect(history.icon(style: .standard) == ObjectIcon(symbolName: "clock.arrow.circlepath")) + + #expect(sequence.icon(style: .colorful) == ObjectIcon(symbolName: "number.square.fill", tint: .mint)) + #expect(system.icon(style: .colorful) == ObjectIcon(symbolName: "tablecells.fill.badge.ellipsis", tint: .gray)) + #expect(saved.icon(style: .colorful) == ObjectIcon(symbolName: "doc.text.fill", tint: .orange)) + #expect(history.icon(style: .colorful) == ObjectIcon(symbolName: "clock.arrow.circlepath")) + } + + @Test("The recent tab switcher keeps its own glyphs in the standard style and the kind's in the colorful one") + func recentTabs() { + var view = QueryTab(title: "active_orders", tabType: .table, tableName: "active_orders") + view.tableContext.objectType = .materializedView + view.tableContext.isView = true + var source = QueryTab(title: "touch", tabType: .objectSource) + source.display.objectRef = DatabaseObjectRef(kind: .function, name: "touch", database: "shop") + let diagram = QueryTab(title: "ER Diagram", tabType: .erDiagram) + + #expect(MainSplitViewController.recentTabIcon(for: view, style: .standard) == ObjectIcon(symbolName: "eye")) + #expect(MainSplitViewController.recentTabIcon(for: source, style: .standard) + == ObjectIcon(symbolName: "curlybraces.square")) + #expect(MainSplitViewController.recentTabIcon(for: view, style: .colorful) + == ObjectIcon(symbolName: "eyeglasses", tint: .indigo)) + #expect(MainSplitViewController.recentTabIcon(for: source, style: .colorful) + == ObjectIcon(symbolName: "function", tint: .purple)) + #expect(MainSplitViewController.recentTabIcon(for: diagram, style: .colorful) + == MainSplitViewController.recentTabIcon(for: diagram, style: .standard)) + #expect(MainSplitViewController.recentTabIcon(for: diagram, style: .colorful).tint == nil) + } + + @Test("An Objects row draws what the sidebar draws, a type as the Types section does") + func objectsListItems() { + let enumType = DatabaseObjectRef(kind: .userType, name: "mood", database: "shop", typeKind: .enumeration) + + #expect(ObjectListingItem.relation(name: "orders", schema: nil, type: .view).iconKind == .relation(.view)) + #expect(ObjectListingItem.sourced(enumType).iconKind == .userType(.other)) + #expect(ObjectIconProvider.icon(for: ObjectListingItem.sourced(enumType).iconKind, style: .standard) + == ObjectIcon(symbolName: "cube")) + } +} diff --git a/apple/TableProTests/Models/Settings/AppearanceIconStyleSettingTests.swift b/apple/TableProTests/Models/Settings/AppearanceIconStyleSettingTests.swift new file mode 100644 index 0000000000..e546f84fd9 --- /dev/null +++ b/apple/TableProTests/Models/Settings/AppearanceIconStyleSettingTests.swift @@ -0,0 +1,47 @@ +// +// AppearanceIconStyleSettingTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct AppearanceIconStyleSettingTests { + private func decode(_ json: String) throws -> AppearanceSettings { + try JSONDecoder().decode(AppearanceSettings.self, from: Data(json.utf8)) + } + + @Test("Settings saved before the style existed decode to the standard style and keep their themes") + func missingKeyIsStandard() throws { + let settings = try decode(#"{"preferredLightThemeId":"light.one","preferredDarkThemeId":"dark.one"}"#) + + #expect(settings.objectIconStyle == .standard) + #expect(settings.preferredLightThemeId == "light.one") + #expect(settings.preferredDarkThemeId == "dark.one") + } + + @Test("A fresh install draws the standard style") + func defaultIsStandard() { + #expect(AppearanceSettings.default.objectIconStyle == .standard) + #expect(AppearanceSettings().objectIconStyle == .standard) + } + + @Test("The colorful style survives a save and a load") + func colorfulRoundTrips() throws { + let saved = AppearanceSettings(objectIconStyle: .colorful) + let data = try JSONEncoder().encode(saved) + + #expect(try JSONDecoder().decode(AppearanceSettings.self, from: data) == saved) + } + + @Test("A style a newer build invents reads as standard and drops nothing else") + func unknownStyleIsStandard() throws { + let settings = try decode( + #"{"preferredLightThemeId":"light.one","preferredDarkThemeId":"dark.one","objectIconStyle":"neon"}"# + ) + + #expect(settings.objectIconStyle == .standard) + #expect(settings.preferredLightThemeId == "light.one") + } +} diff --git a/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift b/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift index 844c15e9f4..1ee7c6f046 100644 --- a/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift @@ -233,4 +233,40 @@ struct EditorTabLabelResolverTests { #expect(tabs[0].title == "orders") #expect(EditorTabLabelResolver.resolve(tabs: tabs, target: .database)[tabs[0].id]?.text == "orders") } + + // MARK: - Object icon style + + @Test("The colorful style gives every object and query tab its kind's tinted glyph, located or not") + func colorfulStyleTintsEveryObjectTab() { + var view = tableTab("active_orders", database: "shop_demo") + view.tableContext.isView = true + let table = tableTab("orders", database: "shop_demo") + let query = QueryTab(title: "Query 1", tabType: .query) + var listing = QueryTab(title: "Objects", tabType: .tableListing) + listing.display.listingKind = .function + var source = QueryTab(title: "touch", tabType: .objectSource) + source.display.objectRef = DatabaseObjectRef(kind: .trigger, name: "touch", database: "shop_demo") + let tabs = [table, view, query, listing, source] + + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: .database, iconStyle: .colorful) + + #expect(labels[table.id]?.icon == ObjectIcon(symbolName: "tablecells.fill", tint: .blue)) + #expect(labels[view.id]?.icon == ObjectIcon(symbolName: "eyeglasses", tint: .cyan)) + #expect(labels[query.id]?.icon == ObjectIcon(symbolName: "doc.text.fill", tint: .orange)) + #expect(labels[listing.id]?.icon == ObjectIcon(symbolName: "folder.fill", tint: .purple)) + #expect(labels[source.id]?.icon == ObjectIcon(symbolName: "bolt.fill", tint: .yellow)) + #expect(labels[table.id]?.text == "orders") + } + + @Test("A tool tab draws no glyph in the colorful style, and the standard style tints nothing") + func toolTabsAndStandardStyleStayPlain() { + let dashboard = QueryTab(title: "Server Dashboard", tabType: .serverDashboard) + let table = tableTab("orders", database: "shop_demo") + + let colorful = EditorTabLabelResolver.resolve(tabs: [dashboard], target: .database, iconStyle: .colorful) + let standard = EditorTabLabelResolver.resolve(tabs: [table], target: .database, style: shop, iconStyle: .standard) + + #expect(colorful[dashboard.id]?.icon == nil) + #expect(standard[table.id]?.icon == ObjectIcon(symbolName: "tablecells")) + } } diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeCellIconStyleTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeCellIconStyleTests.swift new file mode 100644 index 0000000000..3c6e4be6c5 --- /dev/null +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeCellIconStyleTests.swift @@ -0,0 +1,71 @@ +// +// DatabaseTreeCellIconStyleTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import Testing + +extension GlobalStateSuites { + @Suite(.appSettings { $0.appearance.objectIconStyle = .standard }) + @MainActor + struct DatabaseTreeCellIconStyleTests { + private final class FieldDelegate: NSObject, NSTextFieldDelegate {} + + private func viewCell() -> DatabaseTreeCellView { + let view = TableInfo(name: "active_orders", type: .view, rowCount: nil) + let node = DatabaseTreeNode( + id: "view", + kind: .table(DatabaseTreeTableRef(database: "shop", schema: nil, table: view)) + ) + let cell = DatabaseTreeCellView() + cell.configure( + node: node, + isFavorite: false, + context: DatabaseTreeRowContext( + databaseType: .mysql, + activeDatabase: "shop", + activeSchema: nil, + systemSchemas: [], + pendingTruncates: [], + pendingDeletes: [] + ), + actions: DatabaseTreeRowActions(toggleFavorite: { _ in }, toggleFavoriteDatabase: { _ in }) + ) + return cell + } + + @Test("A configured cell takes the new style when the setting changes, without being configured again") + func cellFollowsTheSetting() { + let cell = viewCell() + #expect(cell.renameIcon == ObjectIcon(symbolName: "eye")) + #expect(cell.editorSymbolTint == nil) + + AppSettingsManager.shared.appearance.objectIconStyle = .colorful + + #expect(cell.renameIcon == ObjectIcon(symbolName: "eyeglasses", tint: .cyan)) + #expect(cell.editorSymbolName == "eyeglasses") + #expect(cell.editorSymbolTint == .systemCyan) + } + + @Test("The rename glyph wears the hue, and turns to AppKit's selected color on the emphasized selection") + func renameGlyphKeepsTheSelectionTreatment() throws { + AppSettingsManager.shared.appearance.objectIconStyle = .colorful + let cell = viewCell() + let delegate = FieldDelegate() + + cell.beginRename(text: "active_orders", delegate: delegate) + let glyph = try #require(cell.imageView) + #expect(glyph.contentTintColor == .systemCyan) + + cell.backgroundStyle = .emphasized + #expect(glyph.contentTintColor == nil) + + cell.backgroundStyle = .normal + #expect(glyph.contentTintColor == .systemCyan) + _ = cell.endRename() + } + } +} diff --git a/apple/TableProTests/Views/TableListing/ObjectListingIconStyleTests.swift b/apple/TableProTests/Views/TableListing/ObjectListingIconStyleTests.swift new file mode 100644 index 0000000000..830913db5b --- /dev/null +++ b/apple/TableProTests/Views/TableListing/ObjectListingIconStyleTests.swift @@ -0,0 +1,81 @@ +// +// ObjectListingIconStyleTests.swift +// TableProTests +// + +import AppKit +import Combine +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +extension GlobalStateSuites { + @Suite(.appSettings { $0.appearance.objectIconStyle = .standard }) + @MainActor + struct ObjectListingIconStyleTests { + private let defaults: EphemeralDefaults + + init() throws { + defaults = try EphemeralDefaults() + } + + private func makeModel() -> TableListingViewModel { + let model = TableListingViewModel( + tabId: UUID(), + scope: DatabaseScope(connectionId: UUID(), database: "shop", schema: nil), + loader: TableListingLoader(databaseType: .mysql, slot: .database), + refreshRequests: Empty().eraseToAnyPublisher(), + columnVisibility: ObjectListingColumnVisibilityStore(defaults: defaults.defaults) + ) + let tableRows = TableRows.from( + queryRows: [[.text("shop"), .text("active_orders"), .text("VIEW")]], + columns: ["Schema", "Name", "Type"], + columnTypes: Array(repeating: .text(rawType: nil), count: 3) + ) + let listing = TableListing( + rows: tableRows, isIncomplete: false, statusMessage: nil, + items: [.existing(0): .relation(name: "active_orders", schema: nil, type: .view)], + columnKeys: ["schema", "name", "kind"] + ) + model.list.show(listing, filterText: "") + return model + } + + private func nameGlyph(in table: NSTableView) throws -> NSImageView { + let column = table.column(withIdentifier: NSUserInterfaceItemIdentifier("name")) + let cell = try #require(table.view(atColumn: column, row: 0, makeIfNecessary: true) as? NSTableCellView) + return try #require(cell.imageView) + } + + @Test("The Name glyph on screen takes the colorful hue as soon as the setting changes, and gives it back") + func visibleGlyphFollowsTheSetting() throws { + let model = makeModel() + let coordinator = ObjectListingTableCoordinator(list: model.list, model: model) + let scrollView = coordinator.makeScrollView() + defer { withExtendedLifetime(coordinator) {} } + let table = try #require(scrollView.documentView as? NSTableView) + let glyph = try nameGlyph(in: table) + #expect(glyph.contentTintColor == .controlAccentColor) + + AppSettingsManager.shared.appearance.objectIconStyle = .colorful + #expect(glyph.contentTintColor == .systemCyan) + + AppSettingsManager.shared.appearance.objectIconStyle = .standard + #expect(glyph.contentTintColor == .controlAccentColor) + } + + @Test("A list opened while the colorful style is on draws its glyphs in their hues") + func newListStartsColorful() throws { + AppSettingsManager.shared.appearance.objectIconStyle = .colorful + let model = makeModel() + let coordinator = ObjectListingTableCoordinator(list: model.list, model: model) + let scrollView = coordinator.makeScrollView() + defer { withExtendedLifetime(coordinator) {} } + let table = try #require(scrollView.documentView as? NSTableView) + + #expect(try nameGlyph(in: table).contentTintColor == .systemCyan) + } + } +} From cf655a3a7a05ca0375aa8ef1dd68fc5ccfa23d53 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 12:03:52 +0700 Subject: [PATCH 090/123] feat(editor): offer the query bar on two rows Settings > Editor gets "Show the query bar on two rows", off by default. On, the first row holds Save (Cmd+S for the tab), Query Builder (the Join Builder sheet, shown only where the engine builds joins), Format (help "Beautify SQL"), a Snippets menu and the AI control. The second row holds the connection picker, the database picker, Explain, Run and Stop. Off, the bar is the single row it was. The Snippets menu lists the saved queries the connection sees, in their folders, from the cache the Favorites sidebar reads. A pick goes in at the caret the way completion inserts a favorite: tab stops become fields and ;; marks where the caret lands. Save Current Query as Favorite sits at the bottom. The connection picker lists the saved connections in the sidebar's groups. A pick moves the tab through WindowManager.moveQueryTab, the Move Tab to Connection route, and the picker dims while the tab runs or holds grid edits. Navigator Layout turns the setting on and Standard Layout turns it off, so applyDataView and restoreDataView take the editor settings. The bar pairs its identifier with .accessibilityElement(children: .contain), so each control keeps its own. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../EditorTabConnectionMovePolicy.swift | 7 ++ .../Query/QueryCommandAvailability.swift | 31 +++++ .../Models/Query/QueryConnectionMenu.swift | 81 +++++++++++++ .../Models/Query/QueryEditorBarLayout.swift | 67 +++++++++++ .../Models/Query/QuerySnippetMenu.swift | 53 ++++++++ .../Models/Settings/EditorSettings.swift | 13 +- .../Settings/NavigatorLayoutPreset.swift | 24 ++-- .../Views/Editor/EditorEventRouter.swift | 6 + .../Views/Editor/QueryConnectionPicker.swift | 100 ++++++++++++++++ .../Views/Editor/QueryEditorBar.swift | 113 +++++++++++++++--- .../Views/Editor/QuerySnippetInsertion.swift | 28 +++++ .../Views/Editor/QuerySnippetsMenu.swift | 55 +++++++++ .../Views/Editor/SQLEditorCoordinator.swift | 5 + .../Main/Child/MainEditorContentView.swift | 7 +- .../MainContentCoordinator+JoinBuilder.swift | 7 ++ .../MainContentCoordinator+QueryBar.swift | 33 +++++ .../Views/Settings/EditorSettingsView.swift | 5 + .../Views/Settings/GeneralSettingsView.swift | 17 ++- .../Settings/SettingsWindowController.swift | 1 + .../Models/NavigatorLayoutPresetTests.swift | 24 +++- .../Query/QueryCommandAvailabilityTests.swift | 45 ++++++- .../Query/QueryConnectionMenuTests.swift | 78 ++++++++++++ .../Query/QueryEditorBarLayoutTests.swift | 72 +++++++++++ .../Models/Query/QuerySnippetMenuTests.swift | 68 +++++++++++ .../Settings/SettingsFieldDecodingTests.swift | 18 +++ .../Editor/QueryEditorPaneLayoutTests.swift | 55 ++++++++- .../Editor/QuerySnippetInsertionTests.swift | 80 +++++++++++++ 27 files changed, 1056 insertions(+), 37 deletions(-) create mode 100644 apple/TablePro/Models/Query/QueryConnectionMenu.swift create mode 100644 apple/TablePro/Models/Query/QueryEditorBarLayout.swift create mode 100644 apple/TablePro/Models/Query/QuerySnippetMenu.swift create mode 100644 apple/TablePro/Views/Editor/QueryConnectionPicker.swift create mode 100644 apple/TablePro/Views/Editor/QuerySnippetInsertion.swift create mode 100644 apple/TablePro/Views/Editor/QuerySnippetsMenu.swift create mode 100644 apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift create mode 100644 apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift create mode 100644 apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift create mode 100644 apple/TableProTests/Models/Query/QuerySnippetMenuTests.swift create mode 100644 apple/TableProTests/Views/Editor/QuerySnippetInsertionTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabConnectionMovePolicy.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabConnectionMovePolicy.swift index 9fd4f3456f..6fcec3b917 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabConnectionMovePolicy.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabConnectionMovePolicy.swift @@ -28,6 +28,13 @@ extension MainContentCoordinator { ) } + /// The query bar's connection picker, which moves the tab the way Move Tab to Connection does, + /// without the picker popover: the menu it was chosen from already named the target. + internal func moveQueryTab(_ tabId: UUID, toConnection targetConnectionId: UUID) { + guard let host = splitViewController else { return } + WindowManager.shared.moveQueryTab(tabId: tabId, from: connectionId, in: host, to: targetConnectionId) + } + /// A dirty file buffer lives in `content` and moves with the tab, so it is the one kind of /// unsaved work `savability` counts that does not block a move. private func holdsWorkThatStaysBehind(_ tab: QueryTab) -> Bool { diff --git a/apple/TablePro/Models/Query/QueryCommandAvailability.swift b/apple/TablePro/Models/Query/QueryCommandAvailability.swift index faa0e846fb..4cfd23401b 100644 --- a/apple/TablePro/Models/Query/QueryCommandAvailability.swift +++ b/apple/TablePro/Models/Query/QueryCommandAvailability.swift @@ -20,6 +20,13 @@ struct QueryCommandAvailability { let canSaveAsFavorite: Bool let canClearQuery: Bool let canClearResults: Bool + /// Save is Cmd+S for this tab, so it is live when Cmd+S would do something here: write the tab's + /// changed file or the grid edits it holds, or ask where to keep a query that has no file yet. + let canSave: Bool + /// Query Builder is the Join Builder sheet, which only an engine with a SQL dialect and foreign + /// keys can fill, so elsewhere the button is left out rather than shown dimmed for good. + let showsQueryBuilder: Bool + let canOpenQueryBuilder: Bool /// Whether the Run menu has anything live in it. Clear Query leaves the results standing and /// takes `canRun` away with it, so gating the menu on Run alone hid Clear Results at the one /// moment it was the command the reader wanted. @@ -35,6 +42,9 @@ struct QueryCommandAvailability { let formatHint: String let favoriteHint: String let aiReviewHint: String + let saveHint: String + let beautifyHint: String + let queryBuilderHint: String /// `isStoppable` is separate from `isExecuting` because a batch whose `COMMIT` is on the wire is /// still running and can no longer be stopped by anything: the HIG asks not to offer a cancel @@ -48,6 +58,9 @@ struct QueryCommandAvailability { explainVariants: [ExplainVariant], supportsFormatting: Bool = true, aiActions: AIQueryActionAvailability = .hidden, + hasUnsavedEdits: Bool = false, + hasSourceFile: Bool = false, + supportsQueryBuilder: Bool = false, shortcutHint: (String, ShortcutAction) -> String ) { self.explainVariants = explainVariants @@ -67,6 +80,10 @@ struct QueryCommandAvailability { canClearQuery = hasQueryText canClearResults = hasResults canOpenRunMenu = canRun || hasQueryText || hasResults + canSave = hasUnsavedEdits || (!hasSourceFile && hasQueryText) + showsQueryBuilder = supportsQueryBuilder + /// The sheet reads the database's tables and foreign keys, so it waits for the session. + canOpenQueryBuilder = supportsQueryBuilder && isConnected runHint = Self.hint( base: shortcutHint(String(localized: "Run"), .executeQuery), @@ -94,6 +111,20 @@ struct QueryCommandAvailability { base: shortcutHint(String(localized: "Save as Favorite"), .saveAsFavorite), reason: hasQueryText ? nil : String(localized: "There is nothing to save yet.") ) + saveHint = Self.hint( + base: shortcutHint(String(localized: "Save"), .saveChanges), + reason: canSave ? nil : String(localized: "There is nothing to save yet.") + ) + beautifyHint = Self.hint( + base: shortcutHint(String(localized: "Beautify SQL"), .formatQuery), + reason: !supportsFormatting + ? String(localized: "This query language has no formatter.") + : hasQueryText ? nil : String(localized: "There is nothing to format yet.") + ) + queryBuilderHint = Self.hint( + base: String(localized: "Build Join Query"), + reason: canOpenQueryBuilder ? nil : String(localized: "This connection is not available.") + ) } /// The one rule for Explain, shared by the editor bar and the Query menu so the button and the diff --git a/apple/TablePro/Models/Query/QueryConnectionMenu.swift b/apple/TablePro/Models/Query/QueryConnectionMenu.swift new file mode 100644 index 0000000000..9be7eaa855 --- /dev/null +++ b/apple/TablePro/Models/Query/QueryConnectionMenu.swift @@ -0,0 +1,81 @@ +// +// QueryConnectionMenu.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary + +/// A row of the two-row query bar's connection menu: a saved connection, or a group of them. +internal enum QueryConnectionMenuItem: Identifiable, Equatable { + case group(id: UUID, name: String, children: [QueryConnectionMenuItem]) + case connection(id: UUID, name: String, color: ConnectionColor) + + internal var id: ConnectionNavigatorRowID { + switch self { + case .group(let id, _, _): return .group(id) + case .connection(let id, _, _): return .connection(id) + } + } +} + +/// The saved connections the menu lists, in the groups and order the sidebar's connection list +/// uses, since both come from `ConnectionNavigatorRowsBuilder`. +internal enum QueryConnectionMenu { + /// A group holding no connection is left out: a submenu that opens on nothing is a dead end. + internal static func items(from rows: [ConnectionNavigatorRow]) -> [QueryConnectionMenuItem] { + rows.compactMap { row in + switch row { + case .group(let group): + let children = items(from: group.children) + guard !children.isEmpty else { return nil } + return .group(id: group.id, name: group.name, children: children) + case .connection(let row): + return .connection(id: row.id, name: row.connection.name, color: row.connection.color) + } + } + } + + @MainActor + internal static func load( + connectionStorage: ConnectionStorage = .shared, + groupStorage: GroupStorage = .shared, + listPreferences: ConnectionListPreferences = .shared, + recentConnections: RecentConnectionsStore = .shared + ) -> [QueryConnectionMenuItem] { + items(from: ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: connectionStorage.loadConnections(), + groups: groupStorage.loadGroups(), + sortMode: listPreferences.sortMode, + lastConnected: recentConnections.lastConnected + ))) + } +} + +/// The connection a query tab runs on, and what picking another one in the bar does. +/// +/// A pick moves the tab, the way Database > Move Tab to Connection does, through the `move` the bar +/// is handed: `MainContentCoordinator.moveQueryTab(_:toConnection:)`, which ends in +/// `WindowManager.moveQueryTab`, the only route a tab takes between connections. +internal struct QueryConnectionPickerModel { + internal let connectionId: UUID + internal let name: String + internal let color: ConnectionColor + /// `canMoveTabToConnection`: a running tab, or one whose grid edits would stay behind, keeps its + /// connection until that is settled. + internal let canMove: Bool + internal let move: @MainActor (UUID) -> Void + + internal var hint: String { + guard canMove else { + return String(localized: "This tab cannot move while its query runs or its grid edits are unsaved.") + } + return String(format: String(localized: "Runs on %@. Choose another connection to move this tab there."), name) + } + + @MainActor + internal func choose(_ id: UUID) { + guard canMove, id != connectionId else { return } + move(id) + } +} diff --git a/apple/TablePro/Models/Query/QueryEditorBarLayout.swift b/apple/TablePro/Models/Query/QueryEditorBarLayout.swift new file mode 100644 index 0000000000..a28d09a8c6 --- /dev/null +++ b/apple/TablePro/Models/Query/QueryEditorBarLayout.swift @@ -0,0 +1,67 @@ +// +// QueryEditorBarLayout.swift +// TablePro +// + +import Foundation + +/// One control of the query bar. The bar draws exactly the controls its rows name, so which ones a +/// layout holds is decided here, where a test can read it without mounting the view. +internal enum QueryEditorBarControl: Hashable, Sendable { + case database + case vimMode + /// Format and Save as Favorite, side by side as one group: the single-row bar's editing tools. + case editingCommands + case ai + case explain + /// Run with its menu while idle, Stop while a query is in flight. + case run + case save + case separator + case queryBuilder + case format + case snippets + case connection +} + +/// A row of the bar: controls from the leading edge, a flexible gap, then controls against the +/// trailing edge. +internal struct QueryEditorBarRow: Equatable, Sendable { + internal var leading: [QueryEditorBarControl] + internal var trailing: [QueryEditorBarControl] +} + +/// Which controls the query bar holds and on which row. +/// +/// One row is the bar as it always was. Two rows split it by what a control acts on: the first row +/// edits the query (Save, Query Builder, Format, Snippets, AI), the second names where it runs and +/// runs it (connection, database, Explain, Run). Save as Favorite moves into the Snippets menu there, +/// beside the saved queries it adds to. +internal enum QueryEditorBarLayout { + internal static func rows( + twoRows: Bool, + showsQueryBuilder: Bool, + showsAI: Bool, + showsVimMode: Bool + ) -> [QueryEditorBarRow] { + let vimMode: [QueryEditorBarControl] = showsVimMode ? [.vimMode] : [] + let ai: [QueryEditorBarControl] = showsAI ? [.ai] : [] + guard twoRows else { + return [QueryEditorBarRow( + leading: [.database] + vimMode, + trailing: [.editingCommands] + ai + [.explain, .run] + )] + } + let queryBuilder: [QueryEditorBarControl] = showsQueryBuilder ? [.queryBuilder] : [] + return [ + QueryEditorBarRow( + leading: [.save, .separator] + queryBuilder + [.format, .snippets] + ai, + trailing: [] + ), + QueryEditorBarRow( + leading: [.connection, .database] + vimMode, + trailing: [.explain, .run] + ), + ] + } +} diff --git a/apple/TablePro/Models/Query/QuerySnippetMenu.swift b/apple/TablePro/Models/Query/QuerySnippetMenu.swift new file mode 100644 index 0000000000..1a337d31d0 --- /dev/null +++ b/apple/TablePro/Models/Query/QuerySnippetMenu.swift @@ -0,0 +1,53 @@ +// +// QuerySnippetMenu.swift +// TablePro +// + +import Foundation + +/// An item of the two-row query bar's Snippets menu. +internal enum QuerySnippetMenuEntry: Identifiable, Equatable { + case folder(SQLFavoriteFolder, children: [QuerySnippetMenuEntry]) + case savedQuery(SQLFavorite) + /// Stands in for the saved queries when the connection has none, so the menu says why it is short. + case empty + case divider + /// The bar's Save as Favorite, which the two-row layout keeps here beside what it adds to. + case saveCurrentQuery + + internal var id: String { + switch self { + case .folder(let folder, _): return "folder-\(folder.id)" + case .savedQuery(let favorite): return "saved-query-\(favorite.id)" + case .empty: return "empty" + case .divider: return "divider" + case .saveCurrentQuery: return "save-current-query" + } + } +} + +/// The saved queries one connection can see, in the folders and order the Favorites sidebar shows, +/// because both come from `FavoritesTreeBuilder`. +internal enum QuerySnippetMenu { + /// `folders` and `favorites` are what `ConnectionDataCache` holds for the connection: its own and + /// every global one. A folder with no saved query anywhere under it is left out, since a submenu + /// that opens on nothing is a dead end. + internal static func entries(folders: [SQLFavoriteFolder], favorites: [SQLFavorite]) -> [QuerySnippetMenuEntry] { + let saved = entries(from: FavoritesTreeBuilder.build(folders: folders, favorites: favorites)) + return (saved.isEmpty ? [.empty] : saved) + [.divider, .saveCurrentQuery] + } + + private static func entries(from nodes: [FavoriteNode]) -> [QuerySnippetMenuEntry] { + nodes.compactMap { node in + switch node.content { + case .folder(let folder): + let children = entries(from: node.children ?? []) + return children.isEmpty ? nil : .folder(folder, children: children) + case .favorite(let favorite): + return .savedQuery(favorite) + case .linkedFolder, .linkedSubfolder, .linkedFavorite: + return nil + } + } + } +} diff --git a/apple/TablePro/Models/Settings/EditorSettings.swift b/apple/TablePro/Models/Settings/EditorSettings.swift index 61c096077e..fdf7cf58bf 100644 --- a/apple/TablePro/Models/Settings/EditorSettings.swift +++ b/apple/TablePro/Models/Settings/EditorSettings.swift @@ -87,6 +87,9 @@ struct EditorSettings: Codable, Equatable { var showStatementRunControls: Bool var showInvisibleCharacters: Bool var jsonViewerPreferredMode: JSONViewMode + /// The query bar above the editor on two rows: Save, Query Builder, Format, Snippets and AI above + /// the connection, the database and the run controls. Off keeps the single row. + var queryBarTwoRows: Bool static let `default` = EditorSettings( showLineNumbers: true, @@ -100,7 +103,8 @@ struct EditorSettings: Codable, Equatable { highlightCurrentStatement: true, showStatementRunControls: true, showInvisibleCharacters: true, - jsonViewerPreferredMode: .text + jsonViewerPreferredMode: .text, + queryBarTwoRows: false ) init( @@ -115,7 +119,8 @@ struct EditorSettings: Codable, Equatable { highlightCurrentStatement: Bool = true, showStatementRunControls: Bool = true, showInvisibleCharacters: Bool = true, - jsonViewerPreferredMode: JSONViewMode = .text + jsonViewerPreferredMode: JSONViewMode = .text, + queryBarTwoRows: Bool = false ) { self.showLineNumbers = showLineNumbers self.highlightCurrentLine = highlightCurrentLine @@ -129,6 +134,7 @@ struct EditorSettings: Codable, Equatable { self.showStatementRunControls = showStatementRunControls self.showInvisibleCharacters = showInvisibleCharacters self.jsonViewerPreferredMode = jsonViewerPreferredMode + self.queryBarTwoRows = queryBarTwoRows } init(from decoder: Decoder) throws { @@ -154,6 +160,7 @@ struct EditorSettings: Codable, Equatable { jsonViewerPreferredMode = container.decodeSetting( .jsonViewerPreferredMode, default: fallback.jsonViewerPreferredMode ) + queryBarTwoRows = container.decodeSetting(.queryBarTwoRows, default: fallback.queryBarTwoRows) } // Spelled out so `uppercaseKeywords` and `vimModeEnabled` stay on the wire after their properties became @@ -174,6 +181,7 @@ struct EditorSettings: Codable, Equatable { case showStatementRunControls case showInvisibleCharacters case jsonViewerPreferredMode + case queryBarTwoRows } private static func decodeKeywordCase(from container: KeyedDecodingContainer) -> SQLKeywordCase { @@ -210,6 +218,7 @@ struct EditorSettings: Codable, Equatable { try container.encode(showStatementRunControls, forKey: .showStatementRunControls) try container.encode(showInvisibleCharacters, forKey: .showInvisibleCharacters) try container.encode(jsonViewerPreferredMode, forKey: .jsonViewerPreferredMode) + try container.encode(queryBarTwoRows, forKey: .queryBarTwoRows) } /// Clamped tab width (1-16) diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index 8ce4785efc..a749739ab8 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -8,7 +8,7 @@ import Foundation /// The Layout buttons in Settings > General: table details, favorite tables at the top of the tree, /// the Objects tab on selection, the Objects toolbar buttons, labels under the toolbar's icons, the /// saved connections in the tree and Tree as the default sidebar layout, on or off in one step. The -/// same buttons switch the table tab's data view (`applyDataView`). +/// same buttons switch the table tab's data view and the query bar (`applyDataView`). /// /// The tree lists the saved connections itself, so the layout keeps the separate connections column /// off: the sidebar is one tree, with the connection on screen opened in it. @@ -40,25 +40,35 @@ internal enum NavigatorLayoutPreset { defaultLayout = .flat } - /// The table tab's half of the layout: types under the column names, the sort and a Text mode in - /// the filter panel, that panel open with each table, the result bar above the grid and tab titles - /// that name the database and connection. These live in the Data Grid and Tab settings, so the - /// caller passes those bindings beside the General one. - internal static func applyDataView(tabs: inout TabSettings, dataGrid: inout DataGridSettings) { + /// The tabs' half of the layout: types under the column names, the sort and a Text mode in the + /// filter panel, that panel open with each table, the result bar above the grid, tab titles that + /// name the database and connection, and the query bar on two rows. These live in the Data Grid, + /// Tab and Editor settings, so the caller passes those bindings beside the General one. + internal static func applyDataView( + tabs: inout TabSettings, + dataGrid: inout DataGridSettings, + editor: inout EditorSettings + ) { dataGrid.showsColumnTypesInHeader = true dataGrid.showsSortInFilterPanel = true dataGrid.opensFilterPanelForTables = true dataGrid.resultBarAtTop = true tabs.titleShowsLocation = true + editor.queryBarTwoRows = true } - internal static func restoreDataView(tabs: inout TabSettings, dataGrid: inout DataGridSettings) { + internal static func restoreDataView( + tabs: inout TabSettings, + dataGrid: inout DataGridSettings, + editor: inout EditorSettings + ) { let standardGrid = DataGridSettings.default dataGrid.showsColumnTypesInHeader = standardGrid.showsColumnTypesInHeader dataGrid.showsSortInFilterPanel = standardGrid.showsSortInFilterPanel dataGrid.opensFilterPanelForTables = standardGrid.opensFilterPanelForTables dataGrid.resultBarAtTop = standardGrid.resultBarAtTop tabs.titleShowsLocation = TabSettings.default.titleShowsLocation + editor.queryBarTwoRows = EditorSettings.default.queryBarTwoRows } /// The default layout reaches only connections opened later, so each open one is switched the way diff --git a/apple/TablePro/Views/Editor/EditorEventRouter.swift b/apple/TablePro/Views/Editor/EditorEventRouter.swift index fe18f4c44c..0a45b47645 100644 --- a/apple/TablePro/Views/Editor/EditorEventRouter.swift +++ b/apple/TablePro/Views/Editor/EditorEventRouter.swift @@ -123,6 +123,12 @@ internal final class EditorEventRouter { coordinator.performFormatSQL() } + /// The query bar's Snippets menu, which sits above the editor it fills, as Format does. + internal func insertSavedQueryForKeyWindow(_ sql: String) { + guard let (coordinator, _) = editor(for: NSApp.keyWindow) else { return } + coordinator.insertSavedQuery(sql) + } + internal func performRemoveInvisibleCharactersForKeyWindow() { guard let (coordinator, _) = editor(for: NSApp.keyWindow) else { return } coordinator.performRemoveInvisibleCharacters() diff --git a/apple/TablePro/Views/Editor/QueryConnectionPicker.swift b/apple/TablePro/Views/Editor/QueryConnectionPicker.swift new file mode 100644 index 0000000000..5e5d8fa315 --- /dev/null +++ b/apple/TablePro/Views/Editor/QueryConnectionPicker.swift @@ -0,0 +1,100 @@ +// +// QueryConnectionPicker.swift +// TablePro +// + +import AppKit +import SwiftUI + +/// The two-row query bar's leading control: the connection the tab runs on, and a menu of the saved +/// connections to move it to. +/// +/// The list is read when the control appears and again when the library changes, never in `body`, +/// so typing in the editor, which redraws the bar on every key, reads no storage. +struct QueryConnectionPicker: View { + /// Wide enough for a typical connection name, so a long one truncates rather than pushing the + /// database picker off the row. + private static let nameWidth: CGFloat = 200 + + let model: QueryConnectionPickerModel + + @State private var items: [QueryConnectionMenuItem] = [] + + var body: some View { + Menu { + menuContent(items) + } label: { + HStack(spacing: 4) { + Image(nsImage: model.color.queryBarMark()) + Text(model.name) + .font(.callout) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: Self.nameWidth, alignment: .leading) + } + .foregroundStyle(.secondary) + .accessibilityLabel(String(format: String(localized: "Connection: %@"), model.name)) + } + .menuStyle(.button) + .buttonStyle(.borderless) + .fixedSize() + .disabled(!model.canMove) + .help(model.hint) + .accessibilityIdentifier("query-connection") + .onAppear(perform: reload) + .onReceive(AppEvents.shared.connectionUpdated) { _ in reload() } + .onReceive(AppEvents.shared.connectionListStateChanged) { reload() } + } + + private func reload() { + let loaded = QueryConnectionMenu.load() + guard loaded != items else { return } + items = loaded + } + + /// Type-erased because a group's submenu holds the same content one level down. + private func menuContent(_ items: [QueryConnectionMenuItem]) -> AnyView { + AnyView(ForEach(items) { item in + switch item { + case .group(_, let name, let children): + Menu(name) { menuContent(children) } + case .connection(let id, let name, let color): + Button { + model.choose(id) + } label: { + if id == model.connectionId { + Label(name, systemImage: "checkmark") + } else { + Label { Text(name) } icon: { Image(nsImage: color.queryBarMark()) } + } + } + } + }) + } +} + +private extension ConnectionColor { + /// The connection's color as a dot. An image rather than a tinted symbol, because a menu item + /// draws a symbol as a template in its text color. A connection with no color draws a ring, so + /// every row and the label keep the mark in the same place. + func queryBarMark(diameter: CGFloat = 10) -> NSImage { + let fill: NSColor? = isDefault ? nil : NSColor(color) + let image = NSImage(size: NSSize(width: diameter, height: diameter), flipped: false) { rect in + let oval = NSBezierPath(ovalIn: rect.insetBy(dx: 0.5, dy: 0.5)) + if let fill { + fill.setFill() + oval.fill() + NSColor.separatorColor.setStroke() + oval.lineWidth = 0.5 + } else { + NSColor.secondaryLabelColor.setStroke() + oval.lineWidth = 1 + } + oval.stroke() + return true + } + image.isTemplate = false + image.accessibilityDescription = displayName + return image + } +} diff --git a/apple/TablePro/Views/Editor/QueryEditorBar.swift b/apple/TablePro/Views/Editor/QueryEditorBar.swift index 7418150171..1017c6624c 100644 --- a/apple/TablePro/Views/Editor/QueryEditorBar.swift +++ b/apple/TablePro/Views/Editor/QueryEditorBar.swift @@ -23,6 +23,10 @@ import TableProPluginKit /// across five controls with no grouping: borderless icon buttons for Clear, Format and Favorite, a /// `.bordered` `.small` Explain, and a `.borderedProminent` `.small` Execute. Here every control is /// one size, the scope leads, the commands trail, and the primary action is the only prominent one. +/// +/// Settings > Editor can put it on two rows (`EditorSettings.queryBarTwoRows`), which adds Save, the +/// Query Builder, Snippets and the tab's connection. `QueryEditorBarLayout` decides which control sits +/// on which row; off, it is the single row above. struct QueryEditorBar: View { let scope: QueryScopeBarModel let commands: QueryCommandAvailability @@ -43,9 +47,51 @@ struct QueryEditorBar: View { let onClearQuery: () -> Void let onClearResults: () -> Void let onContainerChanged: (String) -> Void + /// What the second row and the extra commands need. Nil draws the single row. + var twoRow: TwoRowInput? + + /// The two-row bar's own inputs, given only while the setting is on, so the single row never + /// reads the connection library or the saved queries. + struct TwoRowInput { + let connection: QueryConnectionPickerModel + let savedQueries: ConnectionDataCache + let onSave: () -> Void + let onOpenQueryBuilder: () -> Void + let onInsertSavedQuery: (SQLFavorite) -> Void + } + + private var rows: [QueryEditorBarRow] { + QueryEditorBarLayout.rows( + twoRows: twoRow != nil, + showsQueryBuilder: commands.showsQueryBuilder, + showsAI: commands.aiActions.isVisible, + showsVimMode: vimMode != nil + ) + } var body: some View { - HStack(spacing: 8) { + VStack(alignment: .leading, spacing: 6) { + ForEach(Array(rows.enumerated()), id: \.offset) { _, row in + HStack(spacing: 8) { + ForEach(row.leading, id: \.self) { control($0) } + + Spacer(minLength: 8) + + ForEach(row.trailing, id: \.self) { control($0) } + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .paneBarBackground() + .accessibilityElement(children: .contain) + .accessibilityIdentifier("query-editor-bar") + } + + @ViewBuilder + private func control(_ control: QueryEditorBarControl) -> some View { + switch control { + case .database: QueryContainerPicker( containers: scope.containers, selectedName: scope.selectedName, @@ -54,27 +100,64 @@ struct QueryEditorBar: View { schemaName: scope.schemaName, onChange: onContainerChanged ) - + case .vimMode: if let vimMode { VimModeIndicatorView(mode: vimMode) } - - Spacer(minLength: 8) - + case .editingCommands: editingCommands - - if commands.aiActions.isVisible { - aiControl - } - + case .ai: + aiControl + case .explain: explainControl - + case .run: runControl + case .save: + if let twoRow { + commandButton(String(localized: "Save"), systemImage: "square.and.arrow.down", action: twoRow.onSave) + .disabled(!commands.canSave) + .help(commands.saveHint) + .accessibilityIdentifier("query-save") + } + case .separator: + Divider() + .frame(height: 16) + .accessibilityHidden(true) + case .queryBuilder: + if let twoRow { + commandButton(String(localized: "Query Builder"), systemImage: "hammer", action: twoRow.onOpenQueryBuilder) + .disabled(!commands.canOpenQueryBuilder) + .help(commands.queryBuilderHint) + .accessibilityIdentifier("query-builder") + } + case .format: + commandButton(String(localized: "Format"), systemImage: "wand.and.stars", action: onFormat) + .disabled(!commands.canFormat) + .help(commands.beautifyHint) + .accessibilityIdentifier("query-format") + case .snippets: + if let twoRow { + QuerySnippetsMenu( + savedQueries: twoRow.savedQueries, + canSaveCurrentQuery: commands.canSaveAsFavorite, + onInsert: twoRow.onInsertSavedQuery, + onSaveCurrentQuery: onSaveAsFavorite + ) + } + case .connection: + if let twoRow { + QueryConnectionPicker(model: twoRow.connection) + } } - .padding(.horizontal, 12) - .padding(.vertical, 6) - .paneBarBackground() - .accessibilityIdentifier("query-editor-bar") + } + + /// The two-row bar's editing tools stand alone rather than in a `ControlGroup`, because a separator + /// sits between them and Save. Each is `.bordered` `.small`, the size of every other control here. + private func commandButton(_ title: String, systemImage: String, action: @escaping () -> Void) -> some View { + Button(title, systemImage: systemImage, action: action) + .labelStyle(.iconOnly) + .buttonStyle(.bordered) + .controlSize(.small) } /// The two that change the query without running it, in one `ControlGroup` because adjacent diff --git a/apple/TablePro/Views/Editor/QuerySnippetInsertion.swift b/apple/TablePro/Views/Editor/QuerySnippetInsertion.swift new file mode 100644 index 0000000000..2a29837c60 --- /dev/null +++ b/apple/TablePro/Views/Editor/QuerySnippetInsertion.swift @@ -0,0 +1,28 @@ +// +// QuerySnippetInsertion.swift +// TablePro +// + +import AppKit +import TableProAutocomplete +import TableProEditorKit +import TableProTextEngine + +/// Puts a saved query picked from the query bar's Snippets menu into the editor, the way completion +/// does when it accepts a favorite's keyword (`QueryCompletionAdapter.completionWindowApplyCompletion`): +/// tab stops become fields Tab walks through, and the `;;` marker (`SQLSnippetMarker`) is where the +/// caret ends up. +@MainActor +internal enum QuerySnippetInsertion { + /// A query with neither tab stops nor the marker goes in as written, with the caret after it. + nonisolated internal static func snippet(for sql: String) -> EditorSnippet { + SQLSnippet.parse(sql).map { EditorSnippet($0) } ?? EditorSnippet(text: sql, fields: []) + } + + /// At the caret, or over the selection as typing would. The editor takes focus back from the + /// menu, so the first field can be typed into at once. + internal static func insert(_ sql: String, into controller: TextViewController) { + controller.insertSnippet(snippet(for: sql), replacing: controller.textView.selectedRange()) + controller.view.window?.makeFirstResponder(controller.textView) + } +} diff --git a/apple/TablePro/Views/Editor/QuerySnippetsMenu.swift b/apple/TablePro/Views/Editor/QuerySnippetsMenu.swift new file mode 100644 index 0000000000..3ed90617d2 --- /dev/null +++ b/apple/TablePro/Views/Editor/QuerySnippetsMenu.swift @@ -0,0 +1,55 @@ +// +// QuerySnippetsMenu.swift +// TablePro +// + +import SwiftUI + +/// The two-row query bar's Snippets menu: the saved queries this connection can see, in their +/// folders, each inserted at the caret when chosen, with Save as Favorite at the bottom. +/// +/// It reads the connection's `ConnectionDataCache`, the one the Favorites sidebar reads, so a query +/// saved or edited anywhere shows up here without a load of its own. +struct QuerySnippetsMenu: View { + @ObservedObject var savedQueries: ConnectionDataCache + let canSaveCurrentQuery: Bool + let onInsert: (SQLFavorite) -> Void + let onSaveCurrentQuery: () -> Void + + var body: some View { + Menu { + menuContent(QuerySnippetMenu.entries(folders: savedQueries.folders, favorites: savedQueries.favorites)) + } label: { + Label(String(localized: "Snippets"), systemImage: "parentheses") + } + .labelStyle(.iconOnly) + .menuStyle(.button) + .buttonStyle(.bordered) + .menuIndicator(.visible) + .controlSize(.small) + .fixedSize() + .help(String(localized: "Insert a saved query at the cursor")) + .accessibilityIdentifier("query-snippets") + .onAppear { savedQueries.ensureLoaded() } + } + + /// Type-erased because a folder's submenu holds the same content one level down. + private func menuContent(_ entries: [QuerySnippetMenuEntry]) -> AnyView { + AnyView(ForEach(entries) { entry in + switch entry { + case .folder(let folder, let children): + Menu(folder.name) { menuContent(children) } + case .savedQuery(let favorite): + Button(favorite.name) { onInsert(favorite) } + case .empty: + Button(String(localized: "No Saved Queries")) {} + .disabled(true) + case .divider: + Divider() + case .saveCurrentQuery: + Button(String(localized: "Save Current Query as Favorite…"), action: onSaveCurrentQuery) + .disabled(!canSaveCurrentQuery) + } + }) + } +} diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 61f0e35e5a..a501112351 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -509,6 +509,11 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie formatSQL(selectedRange: textView.selectedRange()) } + func insertSavedQuery(_ sql: String) { + guard let controller else { return } + QuerySnippetInsertion.insert(sql, into: controller) + } + private func formatSQL(selectedRange: NSRange) { guard let textView = controller?.textView else { return } let formatter: QueryFormatting diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index 61d57602af..d9d8a54579 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -1196,6 +1196,9 @@ extension MainEditorContentView { explainVariants: coordinator.connection.type.explainVariants, supportsFormatting: QueryFormatterFactory.supportsFormatting(coordinator.connection.type), aiActions: coordinator.aiQueryActionAvailability(for: tab), + hasUnsavedEdits: tab.content.isFileDirty || changeManager.hasChanges, + hasSourceFile: tab.content.sourceFileURL != nil, + supportsQueryBuilder: coordinator.canBuildJoinQuery, shortcutHint: { label, action in settingsManager.keyboard.shortcutHint(label, for: action) } @@ -1247,6 +1250,7 @@ extension MainEditorContentView { let showsHistoryTip = showsHistoryTip let parameters = parameterBinding(for: tab) let isParameterPanelVisible = parameterVisibilityBinding(for: tab) + let twoRow = settingsManager.editor.queryBarTwoRows ? coordinator.queryBarTwoRowInput(forTab: tab.id) : nil let header: (VimMode?) -> AnyView = { vimMode in AnyView(VStack(alignment: .leading, spacing: 0) { if let change = tab.content.diskChange, @@ -1276,7 +1280,8 @@ extension MainEditorContentView { onSaveAsFavorite: { coordinator.saveCurrentQueryAsFavorite() }, onClearQuery: { coordinator.commandActions?.clearQuery() }, onClearResults: { coordinator.clearActiveQueryResults() }, - onContainerChanged: { name in changeContainer(for: tab, to: name) } + onContainerChanged: { name in changeContainer(for: tab, to: name) }, + twoRow: twoRow ) Divider() if isParameterPanelVisible.wrappedValue && !parameters.wrappedValue.isEmpty { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+JoinBuilder.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+JoinBuilder.swift index a8db0d7519..d76a823c8a 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+JoinBuilder.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+JoinBuilder.swift @@ -21,6 +21,13 @@ extension MainContentCoordinator { )) } + // The query bar's Query Builder: the tab's own database and schema, with no table picked yet. + func openJoinBuilder(forQueryTab tabId: UUID) { + guard admitsSheetCommand(), let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } + let tabScope = scope(for: tab) + openJoinBuilder(database: tabScope?.database, schema: tabScope?.schema, tables: []) + } + // One query joins one schema, so only the tables sharing the first one's are seeded. func openJoinBuilder(seededWith selection: Set) { let refs = selection.sorted { $0.table.name.localizedStandardCompare($1.table.name) == .orderedAscending } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift new file mode 100644 index 0000000000..13c75644f6 --- /dev/null +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift @@ -0,0 +1,33 @@ +// +// MainContentCoordinator+QueryBar.swift +// TablePro +// + +import Foundation + +@MainActor +extension MainContentCoordinator { + /// What the two-row query bar adds for one query tab. Built only while the setting is on, so the + /// single-row bar reads neither the connection library nor the saved queries. + /// + /// Each command is the one the rest of the app already runs: Save is Cmd+S, Query Builder is the + /// Join Builder sheet, a saved query goes in the way completion inserts a favorite, and a + /// connection pick is Move Tab to Connection. + func queryBarTwoRowInput(forTab tabId: UUID) -> QueryEditorBar.TwoRowInput { + QueryEditorBar.TwoRowInput( + connection: QueryConnectionPickerModel( + connectionId: connection.id, + name: connection.name, + color: connection.color, + canMove: canMoveTabToConnection(tabId), + move: { [weak self] target in self?.moveQueryTab(tabId, toConnection: target) } + ), + savedQueries: ConnectionDataCache.shared(for: connectionId), + onSave: { [weak self] in self?.commandActions?.saveChanges() }, + onOpenQueryBuilder: { [weak self] in self?.openJoinBuilder(forQueryTab: tabId) }, + onInsertSavedQuery: { favorite in + EditorEventRouter.shared.insertSavedQueryForKeyWindow(favorite.query) + } + ) + } +} diff --git a/apple/TablePro/Views/Settings/EditorSettingsView.swift b/apple/TablePro/Views/Settings/EditorSettingsView.swift index 9d9d68da78..6b7a83b58b 100644 --- a/apple/TablePro/Views/Settings/EditorSettingsView.swift +++ b/apple/TablePro/Views/Settings/EditorSettingsView.swift @@ -21,6 +21,11 @@ struct EditorSettingsView: View { Toggle("Highlight current statement", isOn: $settings.highlightCurrentStatement) Toggle("Show invisible characters", isOn: $settings.showInvisibleCharacters) Toggle("Word wrap", isOn: $settings.wordWrap) + Toggle("Show the query bar on two rows", isOn: $settings.queryBarTwoRows) + .help(Text(""" + Puts Save, Query Builder, Format, Snippets and AI above the editor, and the connection, \ + the database and the run controls on a second row. + """)) } Section("Gutter") { diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 0bef0e17f0..f281475881 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -5,6 +5,7 @@ struct GeneralSettingsView: View { @Binding var settings: GeneralSettings @Binding var tabSettings: TabSettings @Binding var dataGridSettings: DataGridSettings + @Binding var editorSettings: EditorSettings @ObservedObject var updater: SoftwareUpdater var onResetAll: () -> Void @@ -82,7 +83,8 @@ struct GeneralSettingsView: View { tree, and makes Tree the default sidebar layout. In table tabs it shows column types in \ the header, the sort and a Text mode in the filter panel, opens that panel with each table, \ puts the result bar above the grid and names the database and connection in tab titles. \ - Standard Layout turns them off again. Open connections switch layout too. + In query tabs it shows the query bar on two rows. Standard Layout turns them off again. \ + Open connections switch layout too. """)) } @@ -205,10 +207,18 @@ struct GeneralSettingsView: View { private func useLayoutPreset(navigator: Bool) { if navigator { NavigatorLayoutPreset.apply(to: &settings, defaultLayout: &defaultSidebarLayout) - NavigatorLayoutPreset.applyDataView(tabs: &tabSettings, dataGrid: &dataGridSettings) + NavigatorLayoutPreset.applyDataView( + tabs: &tabSettings, + dataGrid: &dataGridSettings, + editor: &editorSettings + ) } else { NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &defaultSidebarLayout) - NavigatorLayoutPreset.restoreDataView(tabs: &tabSettings, dataGrid: &dataGridSettings) + NavigatorLayoutPreset.restoreDataView( + tabs: &tabSettings, + dataGrid: &dataGridSettings, + editor: &editorSettings + ) } NavigatorLayoutPreset.switchOpenConnections(to: defaultSidebarLayout) } @@ -219,6 +229,7 @@ struct GeneralSettingsView: View { settings: .constant(.default), tabSettings: .constant(.default), dataGridSettings: .constant(.default), + editorSettings: .constant(.default), updater: SoftwareUpdater.shared, onResetAll: {} ) diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index ae3f2aec79..f4636eb9bf 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -161,6 +161,7 @@ private struct SettingsPaneContent: View { settings: $settingsManager.general, tabSettings: $settingsManager.tabs, dataGridSettings: $settingsManager.dataGrid, + editorSettings: $settingsManager.editor, updater: SoftwareUpdater.shared, onResetAll: { settingsManager.resetToDefaults() } ) diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index edcb4dea4a..4f3042a40a 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -102,43 +102,55 @@ struct NavigatorLayoutPresetTests { #expect(settings == before) } - @Test("Use Navigator Layout turns on the table tab's data view, and Standard Layout turns it off") + @Test("Use Navigator Layout turns on the data view and the two-row query bar, and Standard Layout turns them off") func dataViewFollowsTheButtons() { var tabs = TabSettings.default var grid = DataGridSettings.default + var editor = EditorSettings.default - NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid) + NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) #expect(grid.showsColumnTypesInHeader) #expect(grid.showsSortInFilterPanel) #expect(grid.opensFilterPanelForTables) #expect(grid.resultBarAtTop) #expect(tabs.titleShowsLocation) + #expect(editor.queryBarTwoRows) - NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid) + NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) #expect(grid == DataGridSettings.default) #expect(tabs == TabSettings.default) + #expect(editor == EditorSettings.default) + #expect(!editor.queryBarTwoRows) } - @Test("The data view buttons leave every other Data Grid and Tab setting alone") + @Test("The data view buttons leave every other Data Grid, Tab and Editor setting alone") func dataViewKeepsOtherSettings() { var tabs = TabSettings.default tabs.enablePreviewTabs = !tabs.enablePreviewTabs var grid = DataGridSettings.default grid.showRowNumbers = !grid.showRowNumbers grid.defaultPageSize = 250 + var editor = EditorSettings.default + editor.wordWrap = !editor.wordWrap + editor.keyBindings = .vim let tabsBefore = tabs let gridBefore = grid + let editorBefore = editor - NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid) + NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) #expect(tabs.enablePreviewTabs == tabsBefore.enablePreviewTabs) #expect(grid.showRowNumbers == gridBefore.showRowNumbers) #expect(grid.defaultPageSize == 250) + var expectedEditor = editorBefore + expectedEditor.queryBarTwoRows = true + #expect(editor == expectedEditor) - NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid) + NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) #expect(tabs == tabsBefore) #expect(grid == gridBefore) + #expect(editor == editorBefore) } /// The View menu switches one connection through its shared sidebar state; the preset does the diff --git a/apple/TableProTests/Models/Query/QueryCommandAvailabilityTests.swift b/apple/TableProTests/Models/Query/QueryCommandAvailabilityTests.swift index c8cc227698..07b8f50d0e 100644 --- a/apple/TableProTests/Models/Query/QueryCommandAvailabilityTests.swift +++ b/apple/TableProTests/Models/Query/QueryCommandAvailabilityTests.swift @@ -199,6 +199,43 @@ struct QueryCommandAvailabilityTests { #expect(commands.stopHint.contains("committing") == false) } + /// Save is Cmd+S for the tab: a changed file or grid edits are written, and a query with no file + /// yet asks where to go. A clean file and an empty untitled tab have nothing to save. + @Test("Save is live exactly when Cmd+S would write something for the tab") + func saveFollowsWhatCmdSWouldDo() { + #expect(Self.make(hasQueryText: true, hasSourceFile: false).canSave, "Untitled query: Save As") + #expect(Self.make(hasQueryText: false, hasSourceFile: false).canSave == false) + #expect(Self.make(hasSourceFile: true).canSave == false, "A file with nothing changed") + #expect(Self.make(hasUnsavedEdits: true, hasSourceFile: true).canSave, "A changed file") + #expect(Self.make(hasQueryText: false, hasUnsavedEdits: true).canSave, "Grid edits in the results") + #expect(Self.make(isConnected: false, hasSourceFile: false).canSave, "Writing a file needs no session") + #expect(Self.make(hasSourceFile: true).saveHint.contains("nothing to save")) + #expect(Self.make(hasSourceFile: false).saveHint.contains("nothing to save") == false) + } + + @Test("Query Builder shows only where the engine builds joins, and waits for the session") + func queryBuilderFollowsTheEngine() { + let unsupported = Self.make(supportsQueryBuilder: false) + #expect(unsupported.showsQueryBuilder == false) + #expect(unsupported.canOpenQueryBuilder == false) + + let supported = Self.make(supportsQueryBuilder: true) + #expect(supported.showsQueryBuilder) + #expect(supported.canOpenQueryBuilder) + + let offline = Self.make(isConnected: false, supportsQueryBuilder: true) + #expect(offline.showsQueryBuilder) + #expect(offline.canOpenQueryBuilder == false) + #expect(offline.queryBuilderHint.contains("not available")) + } + + @Test("The two-row Format names itself Beautify SQL and keeps Format's reasons") + func beautifyHint() { + #expect(Self.make().beautifyHint == String(localized: "Beautify SQL")) + #expect(Self.make(hasQueryText: false).beautifyHint.contains("nothing to format")) + #expect(Self.make(supportsFormatting: false).beautifyHint.contains("no formatter")) + } + private static func make( isConnected: Bool = true, hasQueryText: Bool = true, @@ -206,7 +243,10 @@ struct QueryCommandAvailabilityTests { isStoppable: Bool = true, hasResults: Bool = true, explainVariants: [ExplainVariant] = [ExplainVariant(id: "plain", label: "Explain", sqlPrefix: "EXPLAIN")], - supportsFormatting: Bool = true + supportsFormatting: Bool = true, + hasUnsavedEdits: Bool = false, + hasSourceFile: Bool = false, + supportsQueryBuilder: Bool = false ) -> QueryCommandAvailability { QueryCommandAvailability( isConnected: isConnected, @@ -216,6 +256,9 @@ struct QueryCommandAvailabilityTests { hasResults: hasResults, explainVariants: explainVariants, supportsFormatting: supportsFormatting, + hasUnsavedEdits: hasUnsavedEdits, + hasSourceFile: hasSourceFile, + supportsQueryBuilder: supportsQueryBuilder, shortcutHint: { label, _ in label } ) } diff --git a/apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift b/apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift new file mode 100644 index 0000000000..951b71144a --- /dev/null +++ b/apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift @@ -0,0 +1,78 @@ +// +// QueryConnectionMenuTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import Testing + +@MainActor +struct QueryConnectionMenuTests { + @Test("Saved connections keep the sidebar's groups and order, and an empty group is left out") + func groupsLikeTheSidebar() { + let production = ConnectionGroup(name: "Production", sortOrder: 0) + let empty = ConnectionGroup(name: "Archive", sortOrder: 1) + let shop = DatabaseConnection(name: "Shop", color: .red, groupId: production.id, sortOrder: 0) + let billing = DatabaseConnection(name: "Billing", groupId: production.id, sortOrder: 1) + let local = DatabaseConnection(name: "Local", color: .green) + + let rows = ConnectionNavigatorRowsBuilder.build(ConnectionNavigatorRowsInput( + connections: [local, billing, shop], + groups: [empty, production] + )) + + #expect(QueryConnectionMenu.items(from: rows) == [ + .group(id: production.id, name: "Production", children: [ + .connection(id: shop.id, name: "Shop", color: .red), + .connection(id: billing.id, name: "Billing", color: .none), + ]), + .connection(id: local.id, name: "Local", color: .green), + ]) + } + + @Test("Choosing another connection moves the tab there through the move it was handed") + func choosingMovesTheTab() { + let current = UUID() + let target = UUID() + var moves: [UUID] = [] + let model = QueryConnectionPickerModel( + connectionId: current, + name: "Shop", + color: .none, + canMove: true, + move: { moves.append($0) } + ) + + model.choose(target) + model.choose(current) + + #expect(moves == [target], "The connection the tab is on is no move") + } + + @Test("A tab that cannot move stays put, and the picker says why") + func busyTabStaysPut() { + var moves: [UUID] = [] + let model = QueryConnectionPickerModel( + connectionId: UUID(), + name: "Shop", + color: .none, + canMove: false, + move: { moves.append($0) } + ) + + model.choose(UUID()) + + #expect(moves.isEmpty) + #expect(model.hint.contains("cannot move")) + } + + /// The menu runs the same policy as Database > Move Tab to Connection: a running query keeps its + /// tab on the connection it was sent to. + @Test("A tab whose query is running cannot move") + func runningTabCannotMove() { + #expect(EditorTabConnectionMovePolicy.canMove(tabType: .query, isBusy: false, hasPendingGridEdits: false)) + #expect(!EditorTabConnectionMovePolicy.canMove(tabType: .query, isBusy: true, hasPendingGridEdits: false)) + } +} diff --git a/apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift b/apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift new file mode 100644 index 0000000000..a71de58dad --- /dev/null +++ b/apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift @@ -0,0 +1,72 @@ +// +// QueryEditorBarLayoutTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct QueryEditorBarLayoutTests { + private static func rows( + twoRows: Bool, + showsQueryBuilder: Bool = true, + showsAI: Bool = true, + showsVimMode: Bool = false + ) -> [QueryEditorBarRow] { + QueryEditorBarLayout.rows( + twoRows: twoRows, + showsQueryBuilder: showsQueryBuilder, + showsAI: showsAI, + showsVimMode: showsVimMode + ) + } + + @Test("Off, the bar is the single row it always was") + func singleRowIsTodaysBar() { + #expect(Self.rows(twoRows: false) == [ + QueryEditorBarRow(leading: [.database], trailing: [.editingCommands, .ai, .explain, .run]), + ]) + } + + @Test("On, the editing tools take the first row and the target and run controls the second") + func twoRowsSplitByWhatEachControlActsOn() { + #expect(Self.rows(twoRows: true) == [ + QueryEditorBarRow(leading: [.save, .separator, .queryBuilder, .format, .snippets, .ai], trailing: []), + QueryEditorBarRow(leading: [.connection, .database], trailing: [.explain, .run]), + ]) + } + + @Test("The commands only the two-row bar adds never reach the single row") + func singleRowHoldsNoTwoRowControl() { + let controls = Self.rows(twoRows: false).flatMap { $0.leading + $0.trailing } + for added in [QueryEditorBarControl.save, .separator, .queryBuilder, .format, .snippets, .connection] { + #expect(!controls.contains(added)) + } + } + + @Test("Each control appears once in either layout") + func noControlTwice() { + for twoRows in [false, true] { + let controls = Self.rows(twoRows: twoRows, showsVimMode: true).flatMap { $0.leading + $0.trailing } + #expect(controls.count == Set(controls).count) + } + } + + @Test("Query Builder is left out where the engine cannot build a join") + func queryBuilderHiddenWhereUnsupported() { + let rows = Self.rows(twoRows: true, showsQueryBuilder: false) + #expect(rows.first?.leading == [.save, .separator, .format, .snippets, .ai]) + #expect(!rows.flatMap { $0.leading + $0.trailing }.contains(.queryBuilder)) + } + + @Test("The AI control and the Vim indicator follow their own conditions in both layouts") + func optionalControls() { + let single = Self.rows(twoRows: false, showsAI: false, showsVimMode: true) + #expect(single == [QueryEditorBarRow(leading: [.database, .vimMode], trailing: [.editingCommands, .explain, .run])]) + + let double = Self.rows(twoRows: true, showsAI: false, showsVimMode: true) + #expect(double.first?.leading == [.save, .separator, .queryBuilder, .format, .snippets]) + #expect(double.last == QueryEditorBarRow(leading: [.connection, .database, .vimMode], trailing: [.explain, .run])) + } +} diff --git a/apple/TableProTests/Models/Query/QuerySnippetMenuTests.swift b/apple/TableProTests/Models/Query/QuerySnippetMenuTests.swift new file mode 100644 index 0000000000..6806ae5a42 --- /dev/null +++ b/apple/TableProTests/Models/Query/QuerySnippetMenuTests.swift @@ -0,0 +1,68 @@ +// +// QuerySnippetMenuTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct QuerySnippetMenuTests { + private static let connectionId = UUID() + + @Test("A connection's saved queries are listed in their folders, with Save as Favorite last") + func listsSavedQueriesInFolders() { + let reports = SQLFavoriteFolder(name: "Reports", sortOrder: 0) + let orders = SQLFavoriteFolder(name: "Orders", connectionId: Self.connectionId, sortOrder: 1) + let topCustomers = SQLFavorite(name: "Top customers", query: "SELECT 1", folderId: reports.id) + let recentOrders = SQLFavorite( + name: "Recent orders", + query: "SELECT 2", + folderId: orders.id, + connectionId: Self.connectionId + ) + let count = SQLFavorite(name: "Count", query: "SELECT count(*) FROM ${1:orders}") + + let entries = QuerySnippetMenu.entries(folders: [orders, reports], favorites: [count, recentOrders, topCustomers]) + + #expect(entries == [ + .folder(reports, children: [.savedQuery(topCustomers)]), + .folder(orders, children: [.savedQuery(recentOrders)]), + .savedQuery(count), + .divider, + .saveCurrentQuery, + ]) + } + + @Test("Folders nest, and one with no saved query under it is left out") + func nestsAndPrunesFolders() { + let parent = SQLFavoriteFolder(name: "Ops", sortOrder: 0) + let child = SQLFavoriteFolder(name: "Locks", parentId: parent.id, sortOrder: 0) + let empty = SQLFavoriteFolder(name: "Drafts", sortOrder: 1) + let emptyChild = SQLFavoriteFolder(name: "Old", parentId: empty.id) + let locks = SQLFavorite(name: "Locks held", query: "SELECT * FROM pg_locks", folderId: child.id) + + let entries = QuerySnippetMenu.entries(folders: [parent, child, empty, emptyChild], favorites: [locks]) + + #expect(entries == [ + .folder(parent, children: [.folder(child, children: [.savedQuery(locks)])]), + .divider, + .saveCurrentQuery, + ]) + } + + @Test("A saved query whose folder this connection cannot see is listed at the top level") + func unresolvedFolderGoesToTheRoot() { + let stray = SQLFavorite(name: "Stray", query: "SELECT 1", folderId: UUID()) + + #expect(QuerySnippetMenu.entries(folders: [], favorites: [stray]) == [.savedQuery(stray), .divider, .saveCurrentQuery]) + } + + @Test("With no saved query the menu says so and still offers to save the current one") + func emptyState() { + let lonelyFolder = SQLFavoriteFolder(name: "Empty") + + #expect(QuerySnippetMenu.entries(folders: [], favorites: []) == [.empty, .divider, .saveCurrentQuery]) + #expect(QuerySnippetMenu.entries(folders: [lonelyFolder], favorites: []) == [.empty, .divider, .saveCurrentQuery]) + } +} diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index 42af9af570..4669f7c10f 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -83,6 +83,24 @@ struct SettingsFieldDecodingTests { #expect(decoded.showsColumnTypesInHeader == true) } + @Test("Editor settings saved before the two-row query bar keep the single row, and the choice round-trips") + func queryBarTwoRowsDefaultsOff() throws { + let legacy = try decode(EditorSettings.self, #"{"wordWrap":true}"#) + #expect(legacy.queryBarTwoRows == false) + #expect(legacy.wordWrap == true) + #expect(EditorSettings.default.queryBarTwoRows == false) + + let bad = try decode(EditorSettings.self, #"{"queryBarTwoRows":"yes","wordWrap":true}"#) + #expect(bad.queryBarTwoRows == false) + #expect(bad.wordWrap == true) + + var chosen = EditorSettings.default + chosen.queryBarTwoRows = true + let decoded = try decode(EditorSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.queryBarTwoRows == true) + #expect(decoded == chosen) + } + @Test("Data Grid settings saved before the result bar could move keep it below the grid") func resultBarAtTopDefaultsOff() throws { let legacy = try decode(DataGridSettings.self, #"{"showRowNumbers":false}"#) diff --git a/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift b/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift index c29a43f22e..275143c11c 100644 --- a/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift +++ b/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift @@ -15,7 +15,10 @@ import Testing @MainActor enum QueryEditorPaneFixture { - static func input(text: Binding = .constant("SELECT 1")) -> QueryEditorPaneInput { + static func input( + text: Binding = .constant("SELECT 1"), + twoRow: QueryEditorBar.TwoRowInput? = nil + ) -> QueryEditorPaneInput { QueryEditorPaneInput( header: { vimMode in AnyView(VStack(spacing: 0) { @@ -34,6 +37,7 @@ enum QueryEditorPaneFixture { isStoppable: true, hasResults: false, explainVariants: [], + supportsQueryBuilder: true, shortcutHint: { label, _ in label } ), isExecuting: false, @@ -49,7 +53,8 @@ enum QueryEditorPaneFixture { onSaveAsFavorite: {}, onClearQuery: {}, onClearResults: {}, - onContainerChanged: { _ in } + onContainerChanged: { _ in }, + twoRow: twoRow ) Divider() }) @@ -61,6 +66,22 @@ enum QueryEditorPaneFixture { ) ) } + + static func twoRowInput(connectionId: UUID) -> QueryEditorBar.TwoRowInput { + QueryEditorBar.TwoRowInput( + connection: QueryConnectionPickerModel( + connectionId: connectionId, + name: "Shop Demo", + color: .blue, + canMove: true, + move: { _ in } + ), + savedQueries: ConnectionDataCache.shared(for: connectionId), + onSave: {}, + onOpenQueryBuilder: {}, + onInsertSavedQuery: { _ in } + ) + } } @MainActor @@ -81,4 +102,34 @@ struct QueryEditorPaneLayoutTests { #expect(editor.maxY <= header.minY + 0.5) #expect(editor.height > 0) } + + /// The second row costs one control's height, and the pane's minimum still holds the bar and an + /// editor below it, so turning the setting on never pushes the bar under the results. + @Test("The two-row bar is taller than one row and still fits the pane minimum") + func twoRowBarFitsThePaneMinimum() { + let connectionId = UUID() + defer { ConnectionDataCache.removeConnection(connectionId) } + let paneMinimum = CollapsibleSplitController.defaultTopMinimumThickness + let single = QueryEditorPaneController(input: QueryEditorPaneFixture.input()) + let double = QueryEditorPaneController(input: QueryEditorPaneFixture.input( + twoRow: QueryEditorPaneFixture.twoRowInput(connectionId: connectionId) + )) + defer { + single.teardown() + double.teardown() + } + for pane in [single, double] { + pane.view.frame = NSRect(x: 0, y: 0, width: 900, height: paneMinimum) + pane.view.layoutSubtreeIfNeeded() + } + + let oneRow = single.header.frame.height + let twoRows = double.header.frame.height + let editor = double.editor.textViewController.view.frame + #expect(twoRows > oneRow + 10) + #expect(twoRows == double.header.intrinsicContentSize.height) + #expect(double.header.frame.maxY <= paneMinimum) + #expect(editor.maxY <= double.header.frame.minY + 0.5) + #expect(editor.height > 0) + } } diff --git a/apple/TableProTests/Views/Editor/QuerySnippetInsertionTests.swift b/apple/TableProTests/Views/Editor/QuerySnippetInsertionTests.swift new file mode 100644 index 0000000000..44adb65c7e --- /dev/null +++ b/apple/TableProTests/Views/Editor/QuerySnippetInsertionTests.swift @@ -0,0 +1,80 @@ +// +// QuerySnippetInsertionTests.swift +// TableProTests +// +// A saved query chosen from the query bar's Snippets menu goes into the editor the way completion +// puts in a favorite: tab stops become fields and `;;` marks where the caret lands. +// + +import AppKit +import TableProEditorKit +import TableProTextEngine +import Testing + +@testable import TablePro + +@MainActor +struct QuerySnippetInsertionTests { + private let controller = EditorControllerFixture.make(string: "SELECT 1;\n") + + private var text: String { controller.textView.string } + + private var selection: [NSRange] { + controller.textView.selectionManager.textSelections.map { $0.range } + } + + private func select(_ range: NSRange) { + controller.textView.selectionManager.setSelectedRange(range) + } + + @Test("Tab stops expand into fields and the first one is selected for typing") + func expandsTabStops() { + select(NSRange(location: 10, length: 0)) + + QuerySnippetInsertion.insert("SELECT * FROM ${1:orders} WHERE ${2:id} = 1", into: controller) + + #expect(text == "SELECT 1;\nSELECT * FROM orders WHERE id = 1") + #expect(controller.isSnippetSessionActive) + #expect(selection == [NSRange(location: 24, length: 6)]) + } + + @Test("The ;; marker is removed and the caret lands where it stood") + func markerPlacesTheCaret() { + select(NSRange(location: 10, length: 0)) + + QuerySnippetInsertion.insert("SELECT * FROM users WHERE ;; LIMIT 10", into: controller) + + #expect(text == "SELECT 1;\nSELECT * FROM users WHERE LIMIT 10") + #expect(selection == [NSRange(location: 36, length: 0)]) + } + + @Test("A query with no placeholder goes in as written, caret after it") + func plainQuery() { + select(NSRange(location: 10, length: 0)) + + QuerySnippetInsertion.insert("SELECT 2", into: controller) + + #expect(text == "SELECT 1;\nSELECT 2") + #expect(!controller.isSnippetSessionActive) + #expect(selection == [NSRange(location: 18, length: 0)]) + } + + @Test("A selection is replaced, as typing would replace it") + func replacesTheSelection() { + select(NSRange(location: 7, length: 1)) + + QuerySnippetInsertion.insert("count(*)", into: controller) + + #expect(text == "SELECT count(*);\n") + } + + /// The parse is completion's own, so a PostgreSQL parameter is not mistaken for a tab stop. + @Test("A bare $1 stays a parameter, as it does when completion inserts the favorite") + func dollarParameterStaysLiteral() { + let snippet = QuerySnippetInsertion.snippet(for: "SELECT * FROM orders WHERE id = $1") + + #expect(snippet.text == "SELECT * FROM orders WHERE id = $1") + #expect(snippet.fields.isEmpty) + #expect(snippet.finalRange == nil) + } +} From d6aca5b46b349e5c4390096d57ddf6cf2092c600 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 12:08:14 +0700 Subject: [PATCH 091/123] feat(settings): turn on colorful object icons with the Navigator Layout Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Settings/NavigatorLayoutPreset.swift | 13 +++++++++---- .../Views/Settings/GeneralSettingsView.swift | 12 ++++++++---- .../Settings/SettingsWindowController.swift | 1 + .../Models/NavigatorLayoutPresetTests.swift | 17 ++++++++++++----- 4 files changed, 30 insertions(+), 13 deletions(-) diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index a749739ab8..2aa3be9a61 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -42,12 +42,14 @@ internal enum NavigatorLayoutPreset { /// The tabs' half of the layout: types under the column names, the sort and a Text mode in the /// filter panel, that panel open with each table, the result bar above the grid, tab titles that - /// name the database and connection, and the query bar on two rows. These live in the Data Grid, - /// Tab and Editor settings, so the caller passes those bindings beside the General one. + /// name the database and connection, the query bar on two rows and colorful object icons. These + /// live in the Data Grid, Tab, Editor and Appearance settings, so the caller passes those bindings + /// beside the General one. internal static func applyDataView( tabs: inout TabSettings, dataGrid: inout DataGridSettings, - editor: inout EditorSettings + editor: inout EditorSettings, + appearance: inout AppearanceSettings ) { dataGrid.showsColumnTypesInHeader = true dataGrid.showsSortInFilterPanel = true @@ -55,12 +57,14 @@ internal enum NavigatorLayoutPreset { dataGrid.resultBarAtTop = true tabs.titleShowsLocation = true editor.queryBarTwoRows = true + appearance.objectIconStyle = .colorful } internal static func restoreDataView( tabs: inout TabSettings, dataGrid: inout DataGridSettings, - editor: inout EditorSettings + editor: inout EditorSettings, + appearance: inout AppearanceSettings ) { let standardGrid = DataGridSettings.default dataGrid.showsColumnTypesInHeader = standardGrid.showsColumnTypesInHeader @@ -69,6 +73,7 @@ internal enum NavigatorLayoutPreset { dataGrid.resultBarAtTop = standardGrid.resultBarAtTop tabs.titleShowsLocation = TabSettings.default.titleShowsLocation editor.queryBarTwoRows = EditorSettings.default.queryBarTwoRows + appearance.objectIconStyle = AppearanceSettings.default.objectIconStyle } /// The default layout reaches only connections opened later, so each open one is switched the way diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index f281475881..87e278de88 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -6,6 +6,7 @@ struct GeneralSettingsView: View { @Binding var tabSettings: TabSettings @Binding var dataGridSettings: DataGridSettings @Binding var editorSettings: EditorSettings + @Binding var appearanceSettings: AppearanceSettings @ObservedObject var updater: SoftwareUpdater var onResetAll: () -> Void @@ -83,8 +84,8 @@ struct GeneralSettingsView: View { tree, and makes Tree the default sidebar layout. In table tabs it shows column types in \ the header, the sort and a Text mode in the filter panel, opens that panel with each table, \ puts the result bar above the grid and names the database and connection in tab titles. \ - In query tabs it shows the query bar on two rows. Standard Layout turns them off again. \ - Open connections switch layout too. + In query tabs it shows the query bar on two rows, and object icons turn colorful. \ + Standard Layout turns them off again. Open connections switch layout too. """)) } @@ -210,14 +211,16 @@ struct GeneralSettingsView: View { NavigatorLayoutPreset.applyDataView( tabs: &tabSettings, dataGrid: &dataGridSettings, - editor: &editorSettings + editor: &editorSettings, + appearance: &appearanceSettings ) } else { NavigatorLayoutPreset.restore(to: &settings, defaultLayout: &defaultSidebarLayout) NavigatorLayoutPreset.restoreDataView( tabs: &tabSettings, dataGrid: &dataGridSettings, - editor: &editorSettings + editor: &editorSettings, + appearance: &appearanceSettings ) } NavigatorLayoutPreset.switchOpenConnections(to: defaultSidebarLayout) @@ -230,6 +233,7 @@ struct GeneralSettingsView: View { tabSettings: .constant(.default), dataGridSettings: .constant(.default), editorSettings: .constant(.default), + appearanceSettings: .constant(.default), updater: SoftwareUpdater.shared, onResetAll: {} ) diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index f4636eb9bf..f8fdb8e1f0 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -162,6 +162,7 @@ private struct SettingsPaneContent: View { tabSettings: $settingsManager.tabs, dataGridSettings: $settingsManager.dataGrid, editorSettings: $settingsManager.editor, + appearanceSettings: $settingsManager.appearance, updater: SoftwareUpdater.shared, onResetAll: { settingsManager.resetToDefaults() } ) diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index 4f3042a40a..4257b57c11 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -102,13 +102,14 @@ struct NavigatorLayoutPresetTests { #expect(settings == before) } - @Test("Use Navigator Layout turns on the data view and the two-row query bar, and Standard Layout turns them off") + @Test("Use Navigator Layout turns on the data view, the two-row query bar and colorful icons, and Standard Layout turns them off") func dataViewFollowsTheButtons() { var tabs = TabSettings.default var grid = DataGridSettings.default var editor = EditorSettings.default + var appearance = AppearanceSettings.default - NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) + NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid, editor: &editor, appearance: &appearance) #expect(grid.showsColumnTypesInHeader) #expect(grid.showsSortInFilterPanel) @@ -116,13 +117,15 @@ struct NavigatorLayoutPresetTests { #expect(grid.resultBarAtTop) #expect(tabs.titleShowsLocation) #expect(editor.queryBarTwoRows) + #expect(appearance.objectIconStyle == .colorful) - NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) + NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid, editor: &editor, appearance: &appearance) #expect(grid == DataGridSettings.default) #expect(tabs == TabSettings.default) #expect(editor == EditorSettings.default) #expect(!editor.queryBarTwoRows) + #expect(appearance == AppearanceSettings.default) } @Test("The data view buttons leave every other Data Grid, Tab and Editor setting alone") @@ -135,22 +138,26 @@ struct NavigatorLayoutPresetTests { var editor = EditorSettings.default editor.wordWrap = !editor.wordWrap editor.keyBindings = .vim + var appearance = AppearanceSettings.default + let appearanceBefore = appearance let tabsBefore = tabs let gridBefore = grid let editorBefore = editor - NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) + NavigatorLayoutPreset.applyDataView(tabs: &tabs, dataGrid: &grid, editor: &editor, appearance: &appearance) #expect(tabs.enablePreviewTabs == tabsBefore.enablePreviewTabs) #expect(grid.showRowNumbers == gridBefore.showRowNumbers) #expect(grid.defaultPageSize == 250) var expectedEditor = editorBefore expectedEditor.queryBarTwoRows = true #expect(editor == expectedEditor) + #expect(appearance.objectIconStyle == .colorful) - NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid, editor: &editor) + NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid, editor: &editor, appearance: &appearance) #expect(tabs == tabsBefore) #expect(grid == gridBefore) #expect(editor == editorBefore) + #expect(appearance == appearanceBefore) } /// The View menu switches one connection through its shared sidebar state; the preset does the From 93cd82a555e4833e91e95f240920546598eeb6a3 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 12:08:14 +0700 Subject: [PATCH 092/123] chore(l10n): add the two-row query bar and object icon strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../TablePro/Resources/Localizable.xcstrings | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index f7c6b9cbb1..1797ebdd45 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -31459,6 +31459,9 @@ } } } + }, + "Beautify SQL" : { + }, "Before" : { @@ -43905,6 +43908,12 @@ } } } + }, + "Colorful" : { + + }, + "Colorful gives each kind of object its own filled, colored icon in the sidebar, the tabs and the object lists." : { + }, "Colors" : { "extractionState" : "stale", @@ -95101,6 +95110,9 @@ } } } + }, + "Insert a saved query at the cursor" : { + }, "Insert all rows in a single transaction. If any row fails, all changes are rolled back." : { "extractionState" : "manual", @@ -113783,6 +113795,9 @@ }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter panel, opens that panel with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter panel, opens that panel with each table, puts the result bar above the grid and names the database and connection in tab titles. Standard Layout turns them off again. Open connections switch layout too." : { @@ -125701,6 +125716,9 @@ } } } + }, + "Object Icons" : { + }, "Object Kind" : { @@ -140387,6 +140405,9 @@ } } } + }, + "Puts Save, Query Builder, Format, Snippets and AI above the editor, and the connection, the database and the run controls on a second row." : { + }, "Puzzle Piece" : { "extractionState" : "manual", @@ -140682,6 +140703,9 @@ } } } + }, + "Query Builder" : { + }, "Query consoles import with their data source. Consoles with a default name start unchecked." : { @@ -156071,6 +156095,9 @@ } } } + }, + "Runs on %@. Choose another connection to move this tab there." : { + }, "Runs statements on the SSH server so a database file there can be read and written in place." : { "localizations" : { @@ -157142,6 +157169,9 @@ } } } + }, + "Save Current Query as Favorite…" : { + }, "Save Failed" : { "localizations" : { @@ -167131,6 +167161,9 @@ }, "Show the messages that arrived while paused" : { + }, + "Show the query bar on two rows" : { + }, "Show the result bar above the grid" : { @@ -170014,6 +170047,9 @@ } } } + }, + "Snippets" : { + }, "Snowflake" : { "extractionState" : "manual", @@ -201830,6 +201866,9 @@ }, "This Tab" : { + }, + "This tab cannot move while its query runs or its grid edits are unsaved." : { + }, "This tab is on %@. Switch the connection to that database to run it." : { "localizations" : { From 02c56c8bdf5a6c69962067e3794da6fd51de98ba Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 12:50:58 +0700 Subject: [PATCH 093/123] fix(filter): settle the panel's edited state, Apply and starting row Three fixes to the filter and sort panel, all under its Data Grid settings: - Builder to Text with nothing typed no longer reads as Criteria Edited. Text mode holds one raw row, which never matched the rows the builder ran, so the switch alone looked like an edit. The host now passes the WHERE condition the rows on screen were fetched with, and text that is still that condition is no edit. - Apply Filter & Sort is prominent only while the criteria are edited. Once the rows on screen match the panel it is a plain bordered button, enabled by the same rules as before. - A filter from outside the panel (a cell's Filter menu, Filter with Column) replaces the empty row the panel opened with, while the reader has not touched it. With both data view settings off the panel keeps that row, as it always has. The row's Raw SQL default is the app's own Default Column setting and is unchanged. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Core/Coordinators/FilterCoordinator.swift | 8 ++ .../Database/TabFilterState+Criteria.swift | 20 +++- .../Database/TabFilterState+Editing.swift | 31 ++++++ .../Models/Database/TableFilter.swift | 6 + .../Views/Filter/FilterPanelHosting.swift | 18 +++ .../Views/Filter/FilterPanelView.swift | 28 ++++- .../Views/Filter/QueryTabFilterPanel.swift | 13 ++- .../Coordinators/CellFilterStateTests.swift | 46 ++++++++ .../Models/FilterCriteriaStateTests.swift | 41 +++++++ .../Models/TabFilterStateEditingTests.swift | 25 +++++ .../Views/Filter/FilterSortPanelTests.swift | 103 ++++++++++++++++++ 11 files changed, 330 insertions(+), 9 deletions(-) diff --git a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift index c478bb9343..14f7eac957 100644 --- a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift @@ -701,6 +701,14 @@ final class FilterCoordinator: ObservableObject { ) } + /// What the selected tab's rows were fetched with, written the way Text mode writes it, so text + /// left as Builder to Text wrote it reads as unedited. Nil outside Text mode, which compares rows. + var selectedTabRunningCondition: String? { + guard let tab = parent.tabManager.selectedTab, tab.filterState.effectiveEditMode == .text else { return nil } + let rerun = tab.filterState.rerunFilters + return filterConditionText(for: rerun.filters, logicMode: parent.supportsMatchAnyFilters ? rerun.logicMode : .and) + } + /// The preview's WHERE clause for the enabled rows, without its keyword, for Text mode to start from. func filterConditionText(for filters: [TableFilter], logicMode: FilterLogicMode) -> String? { guard let generator = filterSQLGenerator(databaseType: parent.connection.type), diff --git a/apple/TablePro/Models/Database/TabFilterState+Criteria.swift b/apple/TablePro/Models/Database/TabFilterState+Criteria.swift index 0f51491924..f3185f167c 100644 --- a/apple/TablePro/Models/Database/TabFilterState+Criteria.swift +++ b/apple/TablePro/Models/Database/TabFilterState+Criteria.swift @@ -136,8 +136,24 @@ internal extension TabFilterState { /// runs (every enabled, complete row) against the filters the rows were fetched with, and the /// sort draft against the tab's sort. An incomplete or unchecked row runs nothing, so it edits /// nothing. - func criteriaDiffer(fromAppliedSort appliedSort: [FilterSortCriterion]) -> Bool { - filterDraftDiffersFromRunning || (sortDraft.map { $0 != appliedSort } ?? false) + /// + /// `runningCondition` is the WHERE condition the rows on screen were fetched with, written the + /// way Text mode writes it. Text mode runs its text as written, so text that is still that + /// condition fetches the same rows, and switching modes without typing edits nothing. + func criteriaDiffer(fromAppliedSort appliedSort: [FilterSortCriterion], runningCondition: String? = nil) -> Bool { + filterDraftDiffers(fromRunningCondition: runningCondition) || (sortDraft.map { $0 != appliedSort } ?? false) + } + + /// The rows compare by condition first. Text mode's one raw row never matches rows the builder + /// ran, so its text is compared with the condition they produce instead. + func filterDraftDiffers(fromRunningCondition runningCondition: String?) -> Bool { + guard filterDraftDiffersFromRunning else { return false } + guard effectiveEditMode == .text, let runningCondition else { return true } + return Self.trimmedCondition(textCondition) != Self.trimmedCondition(runningCondition) + } + + private static func trimmedCondition(_ condition: String) -> String { + condition.trimmingCharacters(in: .whitespacesAndNewlines) } var filterDraftDiffersFromRunning: Bool { diff --git a/apple/TablePro/Models/Database/TabFilterState+Editing.swift b/apple/TablePro/Models/Database/TabFilterState+Editing.swift index 733323a00f..3d28e90f1f 100644 --- a/apple/TablePro/Models/Database/TabFilterState+Editing.swift +++ b/apple/TablePro/Models/Database/TabFilterState+Editing.swift @@ -60,7 +60,36 @@ internal extension TabFilterState { return filter.id } + /// The row the panel opens with. A replaceable one is remembered as it was added, so a filter + /// brought in from outside the panel takes its place until the reader edits it. + @discardableResult + mutating func addStartingFilter( + settings: FilterSettings, + columns: [String], + primaryKeyColumn: String?, + offersRawFilter: Bool, + isReplaceable: Bool + ) -> UUID { + let id = addFilter( + settings: settings, + columns: columns, + primaryKeyColumn: primaryKeyColumn, + offersRawFilter: offersRawFilter + ) + startingFilter = isReplaceable ? filters.last : nil + return id + } + + /// The panel's starting row only stood in for a condition, so it goes once one arrives from + /// outside the panel. A row the reader changed is theirs and stays. + mutating func dropUntouchedStartingFilter() { + defer { startingFilter = nil } + guard let startingFilter, let index = filters.firstIndex(of: startingFilter) else { return } + filters.remove(at: index) + } + mutating func addFilter(forColumn columnName: String, settings: FilterSettings) { + dropUntouchedStartingFilter() filters.append(TableFilter( columnName: columnName, filterOperator: settings.defaultOperator.toFilterOperator() @@ -232,6 +261,8 @@ internal extension TabFilterState { /// modes agree and the mode becomes Match all. With two or more running rows the condition /// cannot join them, so it runs alone. static func cellFilterState(_ state: TabFilterState, adding filter: TableFilter) -> TabFilterState { + var state = state + state.dropUntouchedStartingFilter() let executedIDs = Set(state.executedFilters.map(\.id)) let runningIDs = Set(state.filters.lazy.map(\.id).filter(executedIDs.contains)) let keepsRunningRows = (state.executedLogicMode ?? state.filterLogicMode) == .and || runningIDs.count <= 1 diff --git a/apple/TablePro/Models/Database/TableFilter.swift b/apple/TablePro/Models/Database/TableFilter.swift index 6a61a0f025..c7716196ca 100644 --- a/apple/TablePro/Models/Database/TableFilter.swift +++ b/apple/TablePro/Models/Database/TableFilter.swift @@ -405,6 +405,12 @@ struct TabFilterState: Equatable, Hashable, Codable { /// rows were fetched with is the tab's `SortState`, and a draft is only what Apply would run. var sortDraft: [FilterSortCriterion]? + /// The empty row the panel put in by itself for the reader to type into, as it was put in. A + /// filter brought in from outside the panel takes its place while the row is still exactly this. + /// Only a panel that opts in records it (`FilterPanelConfiguration.replacesUntouchedStartingRow`). + /// Not persisted: an incomplete row is never saved. + var startingFilter: TableFilter? + init(isVisible: Bool = false) { self.filters = [] self.commit = nil diff --git a/apple/TablePro/Views/Filter/FilterPanelHosting.swift b/apple/TablePro/Views/Filter/FilterPanelHosting.swift index e3d16e83de..5670fbc26a 100644 --- a/apple/TablePro/Views/Filter/FilterPanelHosting.swift +++ b/apple/TablePro/Views/Filter/FilterPanelHosting.swift @@ -64,9 +64,24 @@ internal struct FilterCriteriaConfiguration { /// The tab's sort, which the section shows until it is edited. var appliedSort: [FilterSortCriterion] var newSortDirection: SortDirection + /// The WHERE condition the rows on screen were fetched with, as Text mode writes it. Nil outside + /// Text mode, and where those rows cannot be written as one condition. + var runningCondition: String? let actions: any FilterCriteriaActions var showsSort: Bool { sortColumns != nil } + + /// Whether Apply Filter & Sort would fetch rows other than the ones on screen, which is when the + /// header says Criteria Edited. + func isEdited(_ state: TabFilterState) -> Bool { + state.criteriaDiffer(fromAppliedSort: appliedSort, runningCondition: runningCondition) + } + + /// Apply Filter & Sort asks for a press only while pressing it would fetch other rows. Once the + /// rows on screen match the panel it is a plain bordered button, enabled by the same rules. + func applyIsProminent(for state: TabFilterState) -> Bool { + isEdited(state) + } } internal struct FilterPanelConfiguration { @@ -84,4 +99,7 @@ internal struct FilterPanelConfiguration { var presetStore: (any FilterPresetStoring)? /// Nil draws the filter-only panel. var criteria: FilterCriteriaConfiguration? + /// Whether a filter brought in from outside the panel (a cell's Filter menu, Filter with Column) + /// replaces the empty row the panel opened with while the reader has not touched it. + var replacesUntouchedStartingRow = false } diff --git a/apple/TablePro/Views/Filter/FilterPanelView.swift b/apple/TablePro/Views/Filter/FilterPanelView.swift index aec35ae3ad..4eb53c0533 100644 --- a/apple/TablePro/Views/Filter/FilterPanelView.swift +++ b/apple/TablePro/Views/Filter/FilterPanelView.swift @@ -63,11 +63,11 @@ struct FilterPanelView: View { focusedFilterId = state.filters.last?.id return } - focusedFilterId = addDefaultFilter(columns: configuration.columns) + focusedFilterId = addStartingFilter(columns: configuration.columns) } .onChange(of: configuration.columns) { newColumns in guard state.filters.isEmpty, !newColumns.isEmpty, state.isVisible else { return } - focusedFilterId = addDefaultFilter(columns: newColumns) + focusedFilterId = addStartingFilter(columns: newColumns) } .sheet(isPresented: $showSQLSheet) { if let sqlPreview = configuration.sqlPreview { @@ -104,7 +104,7 @@ struct FilterPanelView: View { Spacer() - if let criteria, state.criteriaDiffer(fromAppliedSort: criteria.appliedSort) { + if let criteria, criteria.isEdited(state) { Text("Criteria Edited") .font(.caption) .foregroundStyle(.secondary) @@ -156,9 +156,10 @@ struct FilterPanelView: View { } /// Enabled whenever pressing it would change the rows, and whenever filters run, as the plain Apply is. + @ViewBuilder private func criteriaApplyButton(_ criteria: FilterCriteriaConfiguration) -> some View { - let changesRows = state.criteriaDiffer(fromAppliedSort: criteria.appliedSort) - return Button { + let changesRows = criteria.isEdited(state) + let button = Button { applyAllValidFilters() } label: { if criteria.showsSort { @@ -167,13 +168,17 @@ struct FilterPanelView: View { Text("Apply") } } - .buttonStyle(.borderedProminent) .controlSize(.small) .keyboardShortcut(.return, modifiers: .command) .disabled(!changesRows && enabledValidFilterCount == 0 && !state.hasAppliedFilters) .help(criteria.showsSort ? String(localized: "Apply the filters and the sort (Cmd+Return)") : String(localized: "Apply active filters (Cmd+Return)")) + if criteria.applyIsProminent(for: state) { + button.buttonStyle(.borderedProminent) + } else { + button.buttonStyle(.bordered) + } } private func editModePicker(_ criteria: FilterCriteriaConfiguration) -> some View { @@ -431,6 +436,17 @@ struct FilterPanelView: View { ) } + /// The row an empty panel opens with, which the reader did not ask for by name. + private func addStartingFilter(columns: [String]) -> UUID { + state.addStartingFilter( + settings: FilterSettingsStorage.shared.loadSettings(), + columns: columns, + primaryKeyColumn: configuration.primaryKeyColumn, + offersRawFilter: configuration.offersRawFilter, + isReplaceable: configuration.replacesUntouchedStartingRow + ) + } + private func addDefaultFilter(columns: [String]) -> UUID { state.addFilter( settings: FilterSettingsStorage.shared.loadSettings(), diff --git a/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift b/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift index 68a2b5515a..cadb1f3b15 100644 --- a/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift +++ b/apple/TablePro/Views/Filter/QueryTabFilterPanel.swift @@ -85,11 +85,20 @@ internal struct QueryTabFilterPanel: View { supportsColumnSort: coordinator.supportsColumnSort, columns: columns, appliedSort: coordinator.filterCoordinator.selectedTabAppliedSortCriteria, + runningCondition: coordinator.filterCoordinator.selectedTabRunningCondition, actions: coordinator.filterCoordinator - ) + ), + replacesUntouchedStartingRow: Self.replacesUntouchedStartingRow(settings: settingsManager.dataGrid) ) } + /// Under the data view settings the panel opens with each table, so its empty starting row is + /// one the reader never asked for, and an incoming filter takes its place. With both settings + /// off the panel keeps the row, as it always has. + static func replacesUntouchedStartingRow(settings: DataGridSettings) -> Bool { + settings.showsSortInFilterPanel || settings.opensFilterPanelForTables + } + /// Nil while the setting is off, which leaves the filter-only panel. Text mode is a WHERE /// condition, so it needs an engine that takes a raw filter and speaks SQL; a document store's /// raw filter is not a WHERE condition. The section is hidden where a table cannot be sorted by @@ -101,6 +110,7 @@ internal struct QueryTabFilterPanel: View { supportsColumnSort: Bool, columns: [String], appliedSort: [FilterSortCriterion], + runningCondition: String? = nil, actions: any FilterCriteriaActions ) -> FilterCriteriaConfiguration? { guard settings.showsSortInFilterPanel else { return nil } @@ -109,6 +119,7 @@ internal struct QueryTabFilterPanel: View { sortColumns: supportsColumnSort ? columns : nil, appliedSort: supportsColumnSort ? appliedSort : [], newSortDirection: settings.defaultSortDirection, + runningCondition: runningCondition, actions: actions ) } diff --git a/apple/TableProTests/Core/Coordinators/CellFilterStateTests.swift b/apple/TableProTests/Core/Coordinators/CellFilterStateTests.swift index a29b18ef73..8d9c216001 100644 --- a/apple/TableProTests/Core/Coordinators/CellFilterStateTests.swift +++ b/apple/TableProTests/Core/Coordinators/CellFilterStateTests.swift @@ -210,4 +210,50 @@ struct CellFilterStateTests { let next = TabFilterState.cellFilterState(state, adding: added) #expect(next.filters.map(\.id) == [switched.id], "no second row for the same condition") } + + // MARK: - The panel's starting row + + private func startingState(isReplaceable: Bool) -> TabFilterState { + var state = TabFilterState(isVisible: true) + state.addStartingFilter( + settings: FilterSettings(defaultColumn: .rawSQL), + columns: ["status", "country"], + primaryKeyColumn: nil, + offersRawFilter: true, + isReplaceable: isReplaceable + ) + return state + } + + @Test("The empty row the panel opened with gives way to the cell's condition") + func untouchedStartingRowIsReplaced() { + let next = TabFilterState.cellFilterState(startingState(isReplaceable: true), adding: added) + + #expect(next.filters.map(\.id) == [added.id]) + #expect(next.appliedFilters.map(\.id) == [added.id]) + #expect(next.startingFilter == nil) + } + + @Test("A starting row the reader typed into stays beside the cell's condition, unchecked") + func editedStartingRowStays() throws { + var state = startingState(isReplaceable: true) + state.filters[0].value = "country = 'VN'" + let typed = try #require(state.filters.first) + + let next = TabFilterState.cellFilterState(state, adding: added) + + #expect(next.filters.map(\.id) == [typed.id, added.id]) + #expect(next.filters.map(\.isEnabled) == [false, true]) + } + + @Test("A panel that does not opt in keeps its starting row, as it always has") + func plainStartingRowStays() throws { + let state = startingState(isReplaceable: false) + let starting = try #require(state.filters.first) + + let next = TabFilterState.cellFilterState(state, adding: added) + + #expect(next.filters.map(\.id) == [starting.id, added.id]) + #expect(next.filters.map(\.isEnabled) == [false, true]) + } } diff --git a/apple/TableProTests/Models/FilterCriteriaStateTests.swift b/apple/TableProTests/Models/FilterCriteriaStateTests.swift index acde0ea355..74ed38ce29 100644 --- a/apple/TableProTests/Models/FilterCriteriaStateTests.swift +++ b/apple/TableProTests/Models/FilterCriteriaStateTests.swift @@ -235,6 +235,47 @@ struct FilterCriteriaStateTests { #expect(cleared.criteriaDiffer(fromAppliedSort: []), "Apply would filter rows shown unfiltered") } + @Test("Switching to Text is not an edit while the text is the running rows' condition, and typing into it is") + func textOfTheRunningConditionIsNotAnEdit() { + let raw = TableFilter.rawCondition("total > 1") + let id = TestFixtures.makeTableFilter(column: "id", op: .greaterThan, value: "1") + var state = builderState([raw, id], commit: .all) + state.filterLogicMode = .and + state.adoptAppliedFiltersAsRunning() + let running = "(total > 1) AND `id` > 1" + + state.enterTextMode(condition: running) + #expect(!state.criteriaDiffer(fromAppliedSort: [], runningCondition: running)) + + state.setTextCondition(running + " \n") + #expect(!state.criteriaDiffer(fromAppliedSort: [], runningCondition: running), "only space was added") + + state.setTextCondition("(total > 2) AND `id` > 1") + #expect(state.criteriaDiffer(fromAppliedSort: [], runningCondition: running)) + + state.setTextCondition(running) + state.enterBuilderMode() + #expect(state.filters == [raw, id]) + #expect(!state.criteriaDiffer(fromAppliedSort: [], runningCondition: nil)) + } + + @Test("Text is an edit when nothing runs, or when the running rows cannot be written as one condition") + func textAgainstNoRunningCondition() { + let name = TestFixtures.makeTableFilter(column: "name", value: "a") + var unapplied = builderState([name]) + unapplied.enterTextMode(condition: "`name` = 'a'") + #expect(unapplied.criteriaDiffer(fromAppliedSort: [], runningCondition: "")) + + var applied = builderState([name], commit: .all) + applied.adoptAppliedFiltersAsRunning() + applied.enterTextMode(condition: "`name` = 'a'") + #expect(applied.criteriaDiffer(fromAppliedSort: [], runningCondition: nil)) + + var empty = builderState([]) + empty.enterTextMode(condition: "") + #expect(!empty.criteriaDiffer(fromAppliedSort: [], runningCondition: "")) + } + @Test("Edited sees a changed logic mode only when it joins two rows") func editedLogicMode() { let name = TestFixtures.makeTableFilter(column: "name", value: "a") diff --git a/apple/TableProTests/Models/TabFilterStateEditingTests.swift b/apple/TableProTests/Models/TabFilterStateEditingTests.swift index 05c97ca791..5163bfdd5c 100644 --- a/apple/TableProTests/Models/TabFilterStateEditingTests.swift +++ b/apple/TableProTests/Models/TabFilterStateEditingTests.swift @@ -104,6 +104,31 @@ struct TabFilterStateEditingTests { #expect(state.isVisible) } + @Test("Filtering with a column takes the place of the panel's untouched starting row, and only that row") + func addFilterForColumnReplacesTheStartingRow() throws { + var replaceable = TabFilterState(isVisible: true) + replaceable.addStartingFilter( + settings: settings(.rawSQL), columns: ["id"], primaryKeyColumn: nil, offersRawFilter: true, isReplaceable: true + ) + replaceable.addFilter(forColumn: "email", settings: settings(.rawSQL)) + #expect(replaceable.filters.map(\.columnName) == ["email"]) + + var touched = TabFilterState(isVisible: true) + touched.addStartingFilter( + settings: settings(.rawSQL), columns: ["id"], primaryKeyColumn: nil, offersRawFilter: true, isReplaceable: true + ) + touched.filters[0] = touched.filters[0].selectingColumn("id") + touched.addFilter(forColumn: "email", settings: settings(.rawSQL)) + #expect(touched.filters.map(\.columnName) == ["id", "email"]) + + var plain = TabFilterState(isVisible: true) + plain.addStartingFilter( + settings: settings(.rawSQL), columns: ["id"], primaryKeyColumn: nil, offersRawFilter: true, isReplaceable: false + ) + plain.addFilter(forColumn: "email", settings: settings(.rawSQL)) + #expect(plain.filters.map(\.columnName) == [TableFilter.rawSQLColumn, "email"]) + } + @Test("A duplicate lands after its source and copies the condition") func duplicateInsertsAfterSource() { let first = TestFixtures.makeTableFilter(column: "id", op: .between, value: "1", secondValue: "9") diff --git a/apple/TableProTests/Views/Filter/FilterSortPanelTests.swift b/apple/TableProTests/Views/Filter/FilterSortPanelTests.swift index 2f16cfef90..0d8f4dc7fe 100644 --- a/apple/TableProTests/Views/Filter/FilterSortPanelTests.swift +++ b/apple/TableProTests/Views/Filter/FilterSortPanelTests.swift @@ -200,6 +200,109 @@ struct FilterSortPanelTests { #expect(!applied.filterState.criteriaDiffer(fromAppliedSort: [])) } + // MARK: - Edited state and Apply + + /// The configuration the panel builds for the selected tab with the setting on. + private func criteria(_ coordinator: MainContentCoordinator) throws -> FilterCriteriaConfiguration { + var settings = DataGridSettings.default + settings.showsSortInFilterPanel = true + let filters: FilterCoordinator = coordinator.filterCoordinator + return try #require(QueryTabFilterPanel.criteriaConfiguration( + settings: settings, + offersRawFilter: true, + isSQLDialect: true, + supportsColumnSort: true, + columns: Self.columns, + appliedSort: filters.selectedTabAppliedSortCriteria, + runningCondition: filters.selectedTabRunningCondition, + actions: filters + )) + } + + @Test("Builder to Text with nothing typed is not an edit, and typing other text is") + func switchingToTextIsNotAnEdit() throws { + let raw = TableFilter.rawCondition("id > 1") + let name = TestFixtures.makeTableFilter(column: "name", value: "a") + let (coordinator, tabManager, tabId) = makeCoordinator(filters: [raw, name]) + defer { coordinator.teardown() } + coordinator.filterCoordinator.applyFiltersAndSort() + let index = try #require(tabManager.tabs.firstIndex { $0.id == tabId }) + let applied = tabManager.tabs[index].filterState + #expect(try !criteria(coordinator).isEdited(applied)) + + let condition = try #require(coordinator.filterCoordinator.filterConditionText( + for: applied.filters, + logicMode: applied.filterLogicMode + )) + tabManager.tabs[index].filterState.enterTextMode(condition: condition) + + #expect(coordinator.filterCoordinator.selectedTabRunningCondition == condition) + #expect(try !criteria(coordinator).isEdited(tabManager.tabs[index].filterState)) + + tabManager.tabs[index].filterState.setTextCondition("id > 2") + #expect(try criteria(coordinator).isEdited(tabManager.tabs[index].filterState)) + + tabManager.tabs[index].filterState.setTextCondition(condition) + tabManager.tabs[index].filterState.enterBuilderMode() + #expect(coordinator.filterCoordinator.selectedTabRunningCondition == nil) + #expect(try !criteria(coordinator).isEdited(tabManager.tabs[index].filterState)) + } + + @Test("Apply Filter & Sort is prominent while the criteria are edited and plain once they are applied") + func applyIsProminentOnlyWhileEdited() throws { + let name = TestFixtures.makeTableFilter(column: "name", value: "a") + let (coordinator, tabManager, tabId) = makeCoordinator(filters: [name]) + defer { coordinator.teardown() } + let index = try #require(tabManager.tabs.firstIndex { $0.id == tabId }) + #expect(try criteria(coordinator).applyIsProminent(for: tabManager.tabs[index].filterState)) + + coordinator.filterCoordinator.applyFiltersAndSort() + #expect(try !criteria(coordinator).applyIsProminent(for: tabManager.tabs[index].filterState)) + + try setSortDraft([FilterSortCriterion(columnName: "email", direction: .descending)], in: tabManager, tabId) + #expect(try criteria(coordinator).applyIsProminent(for: tabManager.tabs[index].filterState)) + + coordinator.filterCoordinator.applyFiltersAndSort() + #expect(try !criteria(coordinator).applyIsProminent(for: tabManager.tabs[index].filterState)) + } + + // MARK: - Starting row + + @Test("A cell's Filter menu runs its condition in place of the panel's untouched starting row") + func cellFilterReplacesTheStartingRow() throws { + let (coordinator, tabManager, tabId) = makeCoordinator() + defer { coordinator.teardown() } + let index = try #require(tabManager.tabs.firstIndex { $0.id == tabId }) + tabManager.tabs[index].filterState.addStartingFilter( + settings: FilterSettings(defaultColumn: .rawSQL), + columns: Self.columns, + primaryKeyColumn: "id", + offersRawFilter: true, + isReplaceable: true + ) + let cell = TestFixtures.makeTableFilter(column: "name", value: "name_1") + + coordinator.filterCoordinator.applyCellFilter(cell) + + let after = try tab(tabManager, tabId) + #expect(after.filterState.filters.map { $0.id } == [cell.id]) + #expect(after.filterState.executedFilters.map { $0.id } == [cell.id]) + #expect(after.content.query.contains("WHERE `name`")) + } + + @Test("Only the data view settings let an incoming filter replace the starting row") + func startingRowReplacementFollowsTheSettings() { + #expect(!QueryTabFilterPanel.replacesUntouchedStartingRow(settings: .default)) + + var sortInPanel = DataGridSettings.default + sortInPanel.showsSortInFilterPanel = true + #expect(QueryTabFilterPanel.replacesUntouchedStartingRow(settings: sortInPanel)) + + var opensPanel = DataGridSettings.default + opensPanel.opensFilterPanelForTables = true + #expect(QueryTabFilterPanel.replacesUntouchedStartingRow(settings: opensPanel)) + } + // MARK: - Settings @Test("Both settings start off and decode off from settings saved before them") From 363b708190fc6465304c2c7ea1a53ddb13037c8e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 12:50:58 +0700 Subject: [PATCH 094/123] fix(grid): name the table's own column type in the header The type line showed the result set's type, which MySQL cuts short: INT for int unsigned, DECIMAL for decimal(12,2). A table's data tab now names each column's type as the table defines it, the same text the sidebar shows, in the engine's own casing. A column the definition does not name, and every query tab, keeps the result's type. The tooltip is unchanged. The definition can land after the rows, so its text is read at draw time and an automatic width grows to hold it. A width the user set stays. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .claude/rules/data-grid.md | 2 +- .../Core/DataGrid/DataGridModel.swift | 7 ++ .../Models/UI/DataGridConfiguration.swift | 5 ++ .../Cells/DataGridColumnWidthCalculator.swift | 4 +- .../DataGrid/DataGridHeaderTypeLine.swift | 20 +++-- .../DataGridViewController+Columns.swift | 13 +++- .../DataGridViewController+Header.swift | 10 ++- .../MainContentCoordinator+GridModels.swift | 1 + .../DataGridHeaderTypeLineTests.swift | 78 +++++++++++++++++++ .../Main/DataTabColumnTypesSettingTests.swift | 11 +++ 10 files changed, 139 insertions(+), 12 deletions(-) diff --git a/.claude/rules/data-grid.md b/.claude/rules/data-grid.md index 7debabba59..587154cc8a 100644 --- a/.claude/rules/data-grid.md +++ b/.claude/rules/data-grid.md @@ -52,7 +52,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode - **AppKit's header behavior in the theme's colors.** `DataGridHeaderView` is a `ThemeTableHeaderView` and every column a `ThemeTableHeaderCell` (`.claude/rules/theme.md`); it adds `menu(for:)` and a `viewWillDraw` that repaints the body on each step of a column drag. AppKit draws the title and the primary sort arrow; the controller sets each header cell's `accessibilitySortDirection`, which AppKit leaves unknown. - **The model's sort is the source.** `tableView.sortDescriptors` is written from `store.sortState` under `isApplyingSortDescriptors`, because an assignment inside the callback fires it again. A plain click keeps only the clicked key and flips it on a repeat; an Option-click keeps the key AppKit appended (`HeaderSortCycle`). Shift-click reaches no sort callback, and Command-click selects the column. - **Header text is the column name.** The type, the comment and, while several keys sort, the sort order go in `headerToolTip`; an active value filter adds a funnel symbol attachment to the title, in the header text color. -- **`configuration.showsColumnTypes` adds a type line under every title**, in both panes' headers at once (the data tabs follow the Data Grid setting). The cell holds no object references, since AppKit copies it, so `DataGridHeaderView` lays the line out through `ThemeTableHeaderView`'s `contentRect(forCellFrame:)` and `drawBelowTitle`, and reads the type from the model at draw time. Turning it on or off measures automatic widths again; a width the user set stays. +- **`configuration.showsColumnTypes` adds a type line under every title**, in both panes' headers at once (the data tabs follow the Data Grid setting). The cell holds no object references, since AppKit copies it, so `DataGridHeaderView` lays the line out through `ThemeTableHeaderView`'s `contentRect(forCellFrame:)` and `drawBelowTitle`, and reads the type from the model at draw time. A table's data tab sets `namesDeclaredColumnTypes`, so the line names the table's own definition (`int unsigned`, `decimal(12,2)`) where a result set cuts it short, and the result's type elsewhere; the tooltip keeps the result's type. Turning it on or off measures automatic widths again, and a definition that lands after the rows only grows an automatic width; a width the user set stays. ## Keyboard, mouse and menus diff --git a/apple/TablePro/Core/DataGrid/DataGridModel.swift b/apple/TablePro/Core/DataGrid/DataGridModel.swift index 418483f6b9..a649a679df 100644 --- a/apple/TablePro/Core/DataGrid/DataGridModel.swift +++ b/apple/TablePro/Core/DataGrid/DataGridModel.swift @@ -542,6 +542,13 @@ final class DataGridModel: ObservableObject { return column.dataIndex < formats.count ? formats[column.dataIndex] : nil } + // The table's own spelling of the column's type, where the owner says the columns are that table's. Read at use, so + // a definition that lands after the rows reaches the header with the metadata delta that carried it. + func declaredType(of column: DataGridColumn) -> String? { + guard configuration.namesDeclaredColumnTypes else { return nil } + return rows.declaredType(at: column.dataIndex) + } + // MARK: - Editing func isColumnWritable(_ column: DataGridColumn) -> Bool { diff --git a/apple/TablePro/Models/UI/DataGridConfiguration.swift b/apple/TablePro/Models/UI/DataGridConfiguration.swift index f00b5ddff8..48627baee7 100644 --- a/apple/TablePro/Models/UI/DataGridConfiguration.swift +++ b/apple/TablePro/Models/UI/DataGridConfiguration.swift @@ -16,6 +16,11 @@ struct DataGridConfiguration: Equatable { // A second header line under each column name with the column's type; the data tabs follow the Data Grid setting. var showsColumnTypes = false + // The type line names the table's own column definition (`int unsigned`, `decimal(12,2)`), which a result set can + // cut short (MySQL reports `INT`, `DECIMAL`). Only a table's data tab reads that table; a query's columns can be + // aliases or expressions that only share a name with one. + var namesDeclaredColumnTypes = false + // Keyed by index: the column is the grid's own and has no name a table column could share. var checkboxColumns: Set = [] diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift index f3497f99bd..175a0f9e51 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift @@ -25,6 +25,8 @@ struct DataGridColumnWidthCalculator { let column: DataGridColumn let accessory: DataGridCellAccessory let displayFormat: ValueDisplayFormat? + // The table's own spelling of the type, which the type line names in place of the result's. + var declaredType: String? } private struct Budget { @@ -70,7 +72,7 @@ struct DataGridColumnWidthCalculator { let dataIndex = input.column.dataIndex let headerCharCount = (input.column.name as NSString).length var maxWidth = CGFloat(headerCharCount) * charWidth * Self.headerCharWidthRatio + Self.headerPadding - if showsTypeLine, let typeLine = DataGridHeaderTypeLine(input.column.type) { + if showsTypeLine, let typeLine = DataGridHeaderTypeLine(input.column.type, declaredType: input.declaredType) { maxWidth = max(maxWidth, typeLine.width) } diff --git a/apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift b/apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift index a986560e08..975a098a12 100644 --- a/apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift +++ b/apple/TablePro/Views/DataGrid/DataGridHeaderTypeLine.swift @@ -12,14 +12,24 @@ struct DataGridHeaderTypeLine { let text: String let category: ColumnTypeCategory - init?(_ type: ColumnType?) { - guard let type, let text = Self.typeName(of: type) else { return nil } + // The category comes from the result's type, which the grid reads its values as, and from the definition only when + // the result named no type. + init?(_ type: ColumnType?, declaredType: String? = nil) { + guard let text = Self.typeName(of: type, declaredType: declaredType) else { return nil } self.text = text - category = ColumnTypeCategory(type) + if let type { + category = ColumnTypeCategory(type) + } else { + category = ColumnTypeCategory(ColumnTypeClassifier().classify(rawTypeName: text)) + } } - // The engine's spelling (`varchar(255)`), else the app's name for the type. - static func typeName(of type: ColumnType?) -> String? { + // The table's definition in its own casing (`int unsigned`, `decimal(12,2)`), else the engine's spelling of the + // result's type (`varchar(255)`), else the app's name for the type. + static func typeName(of type: ColumnType?, declaredType: String? = nil) -> String? { + if let declared = declaredType?.trimmingCharacters(in: .whitespacesAndNewlines), !declared.isEmpty { + return declared + } guard let type else { return nil } if let raw = type.rawType?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty { return raw diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift index 42902be98a..0d02b43a3c 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift @@ -38,10 +38,11 @@ extension DataGridViewController { width = saved nextSaved.insert(column.id) } else if let known = knownWidths[column.id], !savedWidthIDs.contains(column.id) { - // Metadata that reveals an accessory arrives after the rows; an auto width only grows to fit it. + // Metadata that reveals an accessory, or the table's own spelling of a type, arrives after the rows; an + // auto width only grows to fit it. width = changedPresentations.contains(column.dataIndex) ? max(known, calculator.automaticWidth(widthInput(for: column))) - : known + : max(known, typeLineWidth(of: column)) } else { width = calculator.automaticWidth(widthInput(for: column)) } @@ -231,10 +232,16 @@ extension DataGridViewController { DataGridColumnWidthCalculator.Input( column: column, accessory: presenter.presentation(forDataIndex: column.dataIndex).accessory, - displayFormat: model.displayFormat(for: column) + displayFormat: model.displayFormat(for: column), + declaredType: model.declaredType(of: column) ) } + private func typeLineWidth(of column: DataGridColumn) -> CGFloat { + guard model.configuration.showsColumnTypes else { return 0 } + return headerTypeLine(for: column)?.width ?? 0 + } + private var visibleGridWidth: CGFloat { main.scrollView.contentView.bounds.width } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift index 0b880264cd..8368f630de 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Header.swift @@ -145,7 +145,13 @@ extension DataGridViewController { guard model.configuration.showsColumnTypes, let id = container.pane(kind).columnID(of: tableColumn), let column = model.columns.column(id: id) else { return nil } - return DataGridHeaderTypeLine(column.type) + return headerTypeLine(for: column) + } + + // A table's data tab names the type as the table defines it; any other grid, or a column the definition lacks, + // names the result's type. + func headerTypeLine(for column: DataGridColumn) -> DataGridHeaderTypeLine? { + DataGridHeaderTypeLine(column.type, declaredType: model.declaredType(of: column)) } // Titles, the value-filter funnel, tooltips and sort accessibility for every column of both panes. @@ -282,7 +288,7 @@ extension DataGridViewController { // The type line is read out while it shows, so VoiceOver hears what the header draws. private func headerAccessibilityLabel(for column: DataGridColumn, showsComment: Bool, showsType: Bool, isMasked: Bool) -> String { var label = String(format: String(localized: "Column: %@"), column.name) - if showsType, let typeName = DataGridHeaderTypeLine.typeName(of: column.type) { + if showsType, let typeName = headerTypeLine(for: column)?.text { label += ", " + typeName } if isMasked { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift index 549eb1de45..4f99ae5ae0 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift @@ -179,6 +179,7 @@ extension MainContentCoordinator { configuration.primaryKeyColumns = tab.tableContext.primaryKeyColumns configuration.showRowNumbers = AppSettingsManager.shared.dataGrid.showRowNumbers configuration.showsColumnTypes = AppSettingsManager.shared.dataGrid.showsColumnTypesInHeader + configuration.namesDeclaredColumnTypes = tab.tabType == .table configuration.appliesRowSortPreferences = true configuration.appliesRowCopyFormat = true configuration.supportsColumnSort = tab.tabType != .table || supportsColumnSort diff --git a/apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift b/apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift index 3c57974e1b..6325b133ce 100644 --- a/apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift +++ b/apple/TableProTests/Views/DataGrid/DataGridHeaderTypeLineTests.swift @@ -178,6 +178,84 @@ struct DataGridHeaderTypeLineTests { #expect(column.headerCell.accessibilityLabel() == String(format: String(localized: "Column: %@"), "id") + ", bigint(20)") } + // MARK: - The table's own type + + // MySQL's result set reports `INT` and `DECIMAL`; the table defines `int unsigned` and `decimal(12,2)`. `note` is a + // column the definition does not name. + private static func definedRows(declaredTypes: [String: String] = ["id": "int unsigned", "total": "decimal(12,2)"]) -> TableRows { + TableRows.from( + queryRows: (0..<5).map { [.text("\($0)"), .text("1.5"), .text("x")] }, + columns: ["id", "total", "note"], + columnTypes: [.integer(rawType: "INT"), .decimal(rawType: "DECIMAL"), .text(rawType: "VARCHAR")], + columnDeclaredTypes: declaredTypes + ) + } + + private func definedGrid(namesDeclaredTypes: Bool, rows: TableRows = definedRows()) -> HostedDataGrid { + var configuration = Self.configuration(showsColumnTypes: true) + configuration.namesDeclaredColumnTypes = namesDeclaredTypes + return HostedDataGrid(rows: rows, configuration: configuration) + } + + private func typeLine(_ name: String, in grid: HostedDataGrid) throws -> DataGridHeaderTypeLine? { + grid.controller.headerTypeLine(for: try #require(grid.tableColumn(named: name)), in: .main) + } + + @Test("A table's data tab names each type as the table defines it, in its casing, and the result's type where it is not defined") + func typeLineNamesTheTablesDefinition() throws { + let grid = definedGrid(namesDeclaredTypes: true) + defer { grid.close() } + + let id = try #require(try typeLine("id", in: grid)) + #expect(id.text == "int unsigned") + #expect(id.category == .number) + let total = try #require(try typeLine("total", in: grid)) + #expect(total.text == "decimal(12,2)") + #expect(total.category == .number) + #expect(try typeLine("note", in: grid)?.text == "VARCHAR") + + let column = try #require(grid.tableColumn(named: "total")) + #expect(column.headerCell.accessibilityLabel() == String(format: String(localized: "Column: %@"), "total") + ", decimal(12,2)") + #expect(column.headerToolTip == "total (DECIMAL)", "the tooltip is unchanged") + } + + @Test("A grid whose owner does not name the table's types shows the result's type") + func otherGridsNameTheResultsType() throws { + let grid = definedGrid(namesDeclaredTypes: false) + defer { grid.close() } + + #expect(try typeLine("id", in: grid)?.text == "INT") + #expect(try typeLine("total", in: grid)?.text == "DECIMAL") + } + + @Test("A definition takes the place of the result's type, and an empty one does not") + func declaredTypeNameFallsBack() throws { + #expect(DataGridHeaderTypeLine.typeName(of: .integer(rawType: "INT"), declaredType: "int unsigned") == "int unsigned") + #expect(DataGridHeaderTypeLine.typeName(of: .integer(rawType: "INT"), declaredType: " ") == "INT") + #expect(DataGridHeaderTypeLine.typeName(of: nil, declaredType: nil) == nil) + let untyped = try #require(DataGridHeaderTypeLine(nil, declaredType: "decimal(12,2)")) + #expect(untyped.text == "decimal(12,2)") + #expect(untyped.category == .number) + } + + @Test("A definition that lands after the rows renames the type line and widens an automatic width to hold it") + func lateDefinitionWidensTheColumn() throws { + let grid = definedGrid(namesDeclaredTypes: true, rows: Self.definedRows(declaredTypes: [:])) + defer { grid.close() } + let column = try #require(grid.tableColumn(named: "total")) + #expect(try typeLine("total", in: grid)?.text == "DECIMAL") + let before = column.width + + grid.owner.tableRows.updateDisplayMetadata(columnDeclaredTypes: ["total": "decimal(12,2) unsigned zerofill"]) + grid.model.apply(.columnsReplaced) + grid.layout() + + let line = try #require(try typeLine("total", in: grid)) + #expect(line.text == "decimal(12,2) unsigned zerofill") + #expect(before < line.width) + #expect(column.width >= line.width) + } + // MARK: - Width @Test("An automatic width makes room for a type line wider than the name and the values") diff --git a/apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift b/apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift index 6c63e5acc6..1a83383ff8 100644 --- a/apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift +++ b/apple/TableProTests/Views/Main/DataTabColumnTypesSettingTests.swift @@ -31,6 +31,17 @@ extension GlobalStateSuites { @Test("A grid no setting reaches keeps one header line") func plainGridHasNoTypes() { #expect(!DataGridConfiguration().showsColumnTypes) + #expect(!DataGridConfiguration().namesDeclaredColumnTypes) + } + + @Test("A table's data tab names the table's own column types, and a query tab its result's") + func onlyTableTabsNameDeclaredTypes() { + let fixture = CoordinatorFixture() + let table = fixture.addTab(QueryTab(title: "orders", query: "SELECT * FROM orders", tabType: .table, tableName: "orders")) + let query = fixture.addTab(QueryTab(title: "Query 1", query: "SELECT id FROM orders", tabType: .query)) + + #expect(fixture.coordinator.gridConfiguration(for: table).namesDeclaredColumnTypes) + #expect(!fixture.coordinator.gridConfiguration(for: query).namesDeclaredColumnTypes) } } } From 1b5d268e12f95387af501a22c88ff5c255ed71a5 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:06:30 +0700 Subject: [PATCH 095/123] fix(editor): draw the two-row query bar's tools at toolbar size and name them Row 1 of the two-row bar drew Save, Query Builder and Format as small bordered grey glyphs, which read as disabled under the labeled toolbar. They are now borderless regular-size glyphs with more space between them, and Snippets and AI follow. In the Colorful icon style each tool wears a system hue while it can act, baked into a non-template image the way the toolbar's Objects buttons are, so a menu's button keeps it; disabled, the plain template glyph takes the system's dimming. Save, Query Builder and Format carry an explicit accessibility label, and the Snippets and connection menus are named beside `.contain`, since a glyph alone names nothing. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Query/QueryEditorBarLayout.swift | 17 +++ .../Views/Editor/QueryConnectionPicker.swift | 3 + .../Views/Editor/QueryEditorBar.swift | 142 ++++++++++++++++-- .../Views/Editor/QuerySnippetsMenu.swift | 13 +- .../Query/QueryEditorBarLayoutTests.swift | 24 +++ 5 files changed, 180 insertions(+), 19 deletions(-) diff --git a/apple/TablePro/Models/Query/QueryEditorBarLayout.swift b/apple/TablePro/Models/Query/QueryEditorBarLayout.swift index a28d09a8c6..b93b71460e 100644 --- a/apple/TablePro/Models/Query/QueryEditorBarLayout.swift +++ b/apple/TablePro/Models/Query/QueryEditorBarLayout.swift @@ -65,3 +65,20 @@ internal enum QueryEditorBarLayout { ] } } + +/// The hue each editing tool of the two-row bar wears in the colorful icon style, the way the toolbar's +/// Objects buttons each wear one, so the run reads at a glance. The standard style and every control of +/// the second row stay monochrome. +internal enum QueryEditorBarToolTint { + internal static func tint(for control: QueryEditorBarControl, style: ObjectIconStyle) -> ObjectIconTint? { + guard style == .colorful else { return nil } + switch control { + case .save: return .blue + case .queryBuilder: return .orange + case .format: return .purple + case .snippets: return .teal + case .ai: return .pink + case .database, .vimMode, .editingCommands, .explain, .run, .separator, .connection: return nil + } + } +} diff --git a/apple/TablePro/Views/Editor/QueryConnectionPicker.swift b/apple/TablePro/Views/Editor/QueryConnectionPicker.swift index 5e5d8fa315..cdd01a45f3 100644 --- a/apple/TablePro/Views/Editor/QueryConnectionPicker.swift +++ b/apple/TablePro/Views/Editor/QueryConnectionPicker.swift @@ -40,6 +40,9 @@ struct QueryConnectionPicker: View { .fixedSize() .disabled(!model.canMove) .help(model.hint) + // The label's own name reaches VoiceOver only through the menu, which names it only beside `.contain`. + .accessibilityElement(children: .contain) + .accessibilityLabel(String(format: String(localized: "Connection: %@"), model.name)) .accessibilityIdentifier("query-connection") .onAppear(perform: reload) .onReceive(AppEvents.shared.connectionUpdated) { _ in reload() } diff --git a/apple/TablePro/Views/Editor/QueryEditorBar.swift b/apple/TablePro/Views/Editor/QueryEditorBar.swift index 1017c6624c..9663173682 100644 --- a/apple/TablePro/Views/Editor/QueryEditorBar.swift +++ b/apple/TablePro/Views/Editor/QueryEditorBar.swift @@ -3,6 +3,7 @@ // TablePro // +import AppKit import SwiftUI import TableProPluginKit @@ -26,8 +27,17 @@ import TableProPluginKit /// /// Settings > Editor can put it on two rows (`EditorSettings.queryBarTwoRows`), which adds Save, the /// Query Builder, Snippets and the tab's connection. `QueryEditorBarLayout` decides which control sits -/// on which row; off, it is the single row above. +/// on which row; off, it is the single row above. The first of the two rows is a run of borderless +/// glyphs at the toolbar's size rather than small bezels, because it sits right under the toolbar and +/// small grey bezels there read as disabled even when they are not. struct QueryEditorBar: View { + /// The glyph size of the first row's tools, the regular size the window's toolbar draws at. + static let toolGlyphSize: CGFloat = 15 + /// Each tool's target, wider than its glyph so the run is easy to hit and reads as separate tools. + static let toolTargetSize = CGSize(width: 26, height: 22) + /// The first row holds glyphs with no bezel, so they need more air between them than the second. + static let toolSpacing: CGFloat = 10 + let scope: QueryScopeBarModel let commands: QueryCommandAvailability let isExecuting: Bool @@ -72,7 +82,7 @@ struct QueryEditorBar: View { var body: some View { VStack(alignment: .leading, spacing: 6) { ForEach(Array(rows.enumerated()), id: \.offset) { _, row in - HStack(spacing: 8) { + HStack(spacing: row.leading.contains(.save) ? Self.toolSpacing : 8) { ForEach(row.leading, id: \.self) { control($0) } Spacer(minLength: 8) @@ -107,31 +117,40 @@ struct QueryEditorBar: View { case .editingCommands: editingCommands case .ai: - aiControl + if twoRow != nil { + aiTool + } else { + aiControl + } case .explain: explainControl case .run: runControl case .save: if let twoRow { - commandButton(String(localized: "Save"), systemImage: "square.and.arrow.down", action: twoRow.onSave) + toolButton(.save, title: String(localized: "Save"), systemImage: "square.and.arrow.down", action: twoRow.onSave) .disabled(!commands.canSave) .help(commands.saveHint) .accessibilityIdentifier("query-save") } case .separator: Divider() - .frame(height: 16) + .frame(height: 18) .accessibilityHidden(true) case .queryBuilder: if let twoRow { - commandButton(String(localized: "Query Builder"), systemImage: "hammer", action: twoRow.onOpenQueryBuilder) - .disabled(!commands.canOpenQueryBuilder) - .help(commands.queryBuilderHint) - .accessibilityIdentifier("query-builder") + toolButton( + .queryBuilder, + title: String(localized: "Query Builder"), + systemImage: "hammer", + action: twoRow.onOpenQueryBuilder + ) + .disabled(!commands.canOpenQueryBuilder) + .help(commands.queryBuilderHint) + .accessibilityIdentifier("query-builder") } case .format: - commandButton(String(localized: "Format"), systemImage: "wand.and.stars", action: onFormat) + toolButton(.format, title: String(localized: "Format"), systemImage: "wand.and.stars", action: onFormat) .disabled(!commands.canFormat) .help(commands.beautifyHint) .accessibilityIdentifier("query-format") @@ -152,12 +171,56 @@ struct QueryEditorBar: View { } /// The two-row bar's editing tools stand alone rather than in a `ControlGroup`, because a separator - /// sits between them and Save. Each is `.bordered` `.small`, the size of every other control here. - private func commandButton(_ title: String, systemImage: String, action: @escaping () -> Void) -> some View { - Button(title, systemImage: systemImage, action: action) - .labelStyle(.iconOnly) - .buttonStyle(.bordered) - .controlSize(.small) + /// sits between them and Save. Borderless at the toolbar's size, so the row reads as the toolbar's + /// continuation. The name is set on the button itself: the glyph is all that draws, and an image + /// carries no name of its own to VoiceOver. + private func toolButton( + _ control: QueryEditorBarControl, + title: String, + systemImage: String, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + Label { + Text(title) + } icon: { + QueryBarToolGlyph(control: control, systemImage: systemImage, title: title) + } + } + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .controlSize(.regular) + .accessibilityLabel(title) + } + + /// The single row's AI control as a first-row tool: Review on a click, the other actions in its menu. + /// One control rather than a group, because a group draws a bezel and both halves share one state. + /// `.accessibilityLabel` names a `Menu` only beside `.accessibilityElement(children: .contain)`. + private var aiTool: some View { + Menu { + ForEach(AIQueryAction.editorActions, id: \.self) { action in + Button(action.menuTitle, systemImage: action.systemImage) { onAIAction(action) } + } + } label: { + Label { + Text(AIQueryAction.review.menuTitle) + } icon: { + QueryBarToolGlyph(control: .ai, systemImage: "sparkles", title: AIQueryAction.review.menuTitle) + } + } primaryAction: { + onAIAction(.review) + } + .labelStyle(.iconOnly) + .menuStyle(.button) + .buttonStyle(.borderless) + .menuIndicator(.visible) + .controlSize(.regular) + .fixedSize() + .disabled(!commands.aiActions.isEnabled) + .help(commands.aiReviewHint) + .accessibilityElement(children: .contain) + .accessibilityLabel(AIQueryAction.review.menuTitle) + .accessibilityIdentifier("query-ai-review") } /// The two that change the query without running it, in one `ControlGroup` because adjacent @@ -296,3 +359,50 @@ struct QueryEditorBar: View { } } } + +/// A first-row tool's glyph. In the colorful icon style it wears its tool's hue while the tool can act, +/// drawn as the toolbar draws its Objects buttons: a hierarchical symbol baked into a non-template image, +/// because a menu's button draws a template symbol in its text color. Disabled, it is the plain template +/// glyph, which the control dims the way the system dims any other, so it never reads as available. +struct QueryBarToolGlyph: View { + let control: QueryEditorBarControl + let systemImage: String + let title: String + + /// Observed so the hue follows the icon style while the bar is on screen. + @ObservedObject private var settings = AppSettingsManager.shared + @Environment(\.isEnabled) private var isEnabled + + init(control: QueryEditorBarControl, systemImage: String, title: String) { + self.control = control + self.systemImage = systemImage + self.title = title + } + + var body: some View { + glyph + .frame(width: QueryEditorBar.toolTargetSize.width, height: QueryEditorBar.toolTargetSize.height) + .contentShape(Rectangle()) + } + + @ViewBuilder + private var glyph: some View { + if isEnabled, + let tint = QueryEditorBarToolTint.tint(for: control, style: settings.appearance.objectIconStyle), + let image = Self.tintedImage(systemImage, tint: tint.nsColor, title: title) { + Image(nsImage: image) + } else { + Image(systemName: systemImage) + .font(.system(size: QueryEditorBar.toolGlyphSize)) + } + } + + static func tintedImage(_ symbol: String, tint: NSColor, title: String) -> NSImage? { + let configuration = NSImage.SymbolConfiguration(pointSize: QueryEditorBar.toolGlyphSize, weight: .regular) + .applying(NSImage.SymbolConfiguration(hierarchicalColor: tint)) + let image = NSImage(systemSymbolName: symbol, accessibilityDescription: title)? + .withSymbolConfiguration(configuration) + image?.isTemplate = false + return image + } +} diff --git a/apple/TablePro/Views/Editor/QuerySnippetsMenu.swift b/apple/TablePro/Views/Editor/QuerySnippetsMenu.swift index 3ed90617d2..1b4f4a4a7c 100644 --- a/apple/TablePro/Views/Editor/QuerySnippetsMenu.swift +++ b/apple/TablePro/Views/Editor/QuerySnippetsMenu.swift @@ -20,15 +20,22 @@ struct QuerySnippetsMenu: View { Menu { menuContent(QuerySnippetMenu.entries(folders: savedQueries.folders, favorites: savedQueries.favorites)) } label: { - Label(String(localized: "Snippets"), systemImage: "parentheses") + Label { + Text(String(localized: "Snippets")) + } icon: { + QueryBarToolGlyph(control: .snippets, systemImage: "parentheses", title: String(localized: "Snippets")) + } } .labelStyle(.iconOnly) .menuStyle(.button) - .buttonStyle(.bordered) + .buttonStyle(.borderless) .menuIndicator(.visible) - .controlSize(.small) + .controlSize(.regular) .fixedSize() .help(String(localized: "Insert a saved query at the cursor")) + // `.accessibilityLabel` names a `Menu` only beside `.contain`; on its own it replaces the name with nothing. + .accessibilityElement(children: .contain) + .accessibilityLabel(String(localized: "Snippets")) .accessibilityIdentifier("query-snippets") .onAppear { savedQueries.ensureLoaded() } } diff --git a/apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift b/apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift index a71de58dad..7fcaf33f96 100644 --- a/apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift +++ b/apple/TableProTests/Models/Query/QueryEditorBarLayoutTests.swift @@ -69,4 +69,28 @@ struct QueryEditorBarLayoutTests { #expect(double.first?.leading == [.save, .separator, .queryBuilder, .format, .snippets]) #expect(double.last == QueryEditorBarRow(leading: [.connection, .database, .vimMode], trailing: [.explain, .run])) } + + // MARK: - Tool hues + + private static let tools: [QueryEditorBarControl] = [.save, .queryBuilder, .format, .snippets, .ai] + + @Test("In the colorful style each first-row tool wears a hue of its own") + func colorfulToolsEachHaveAHue() { + let tints = Self.tools.compactMap { QueryEditorBarToolTint.tint(for: $0, style: .colorful) } + #expect(tints.count == Self.tools.count) + #expect(Set(tints).count == tints.count) + } + + @Test("The standard style and the second row stay monochrome") + func standardStyleAndSecondRowStayPlain() { + let every: [QueryEditorBarControl] = Self.tools + [ + .database, .vimMode, .editingCommands, .explain, .run, .separator, .connection, + ] + for control in every { + #expect(QueryEditorBarToolTint.tint(for: control, style: .standard) == nil) + } + for control in [QueryEditorBarControl.database, .vimMode, .editingCommands, .explain, .run, .separator, .connection] { + #expect(QueryEditorBarToolTint.tint(for: control, style: .colorful) == nil) + } + } } From 3ab5168b59a2c25750d97b28ce59e3e6c869430f Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:06:30 +0700 Subject: [PATCH 096/123] fix(editor): close the completion popup when a run starts Completion items load asynchronously, so a click on Run could land while a request was still out and the popup opened over the results after it, and Command-Return passes through an open popup to the menu and left it open. Run, Run Without Limit, Run All, the statement run and Explain now end the completion session of the editors in the coordinator's window first, which also cancels a request still loading. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Views/Editor/EditorEventRouter.swift | 9 ++ .../Views/Editor/SQLEditorCoordinator.swift | 8 ++ .../MainContentCoordinator+ExecuteAll.swift | 1 + .../MainContentCoordinator+Explain.swift | 1 + .../Views/Main/MainContentCoordinator.swift | 15 ++++ .../Main/RunEndsEditorCompletionTests.swift | 89 +++++++++++++++++++ 6 files changed, 123 insertions(+) create mode 100644 apple/TableProTests/Views/Main/RunEndsEditorCompletionTests.swift diff --git a/apple/TablePro/Views/Editor/EditorEventRouter.swift b/apple/TablePro/Views/Editor/EditorEventRouter.swift index 0a45b47645..923ca84948 100644 --- a/apple/TablePro/Views/Editor/EditorEventRouter.swift +++ b/apple/TablePro/Views/Editor/EditorEventRouter.swift @@ -163,6 +163,15 @@ internal final class EditorEventRouter { coordinator.runStatementAtCursorAndAdvance() } + /// A run started in `window`, so every editor there ends its completion session. Not only the focused one: + /// the run may come from a click on the query bar, which leaves the focus where it was, or from the menu. + internal func dismissCompletions(in window: NSWindow?) { + guard let window else { return } + for ref in editors.values where ref.textView?.window === window { + ref.coordinator?.dismissCompletions() + } + } + /// Called when the Edit menu's "Clear Selection" item is chosen with the pointer. /// /// Only with the pointer. AppKit never dispatches an unmodified Escape as a key equivalent: diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index a501112351..17ecd43b33 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -766,6 +766,14 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimEngine = nil } + // MARK: - Completion + + /// Ends this editor's completion session, whether its popup is showing or its items are still loading, so + /// nothing opens over the results of a run that started meanwhile. + func dismissCompletions() { + controller?.dismissCompletions() + } + // MARK: - Menu Escape Routing /// Called by `EditorEventRouter.handleEscapeFromMenu()` when the "Clear Selection" menu item is diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift index 520eea9ae1..12936dbd7f 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift @@ -8,6 +8,7 @@ import Foundation extension MainContentCoordinator { func runAllStatements(extraCapabilities: CallerCapabilities = []) { commitActiveGridEdit() + endEditorCompletion() queryExecutionCoordinator.runAllStatements(extraCapabilities: extraCapabilities) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift index 64385b570e..91c45884d3 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift @@ -22,6 +22,7 @@ extension MainContentCoordinator { } guard !isShowingSafeModePrompt else { return nil } guard let statement = explainStatement(in: tab) else { return nil } + endEditorCompletion() let anchor = tab.tabType == .table ? nil : StatementAnchor(statement) guard let request = ExplainRequest.make( variant: variant, diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 705a13bd72..7b257b6851 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -242,6 +242,12 @@ final class MainContentCoordinator: ObservableObject { // For alerts instead of NSApp.keyWindow, which may return a sheet window and leave dialogs stuck. weak var contentWindow: NSWindow? + /// Ends the completion sessions of the editors in a window. Injected so a test can see each run path reach it + /// without an editor on screen. + var dismissEditorCompletions: @MainActor (NSWindow?) -> Void = { window in + EditorEventRouter.shared.dismissCompletions(in: window) + } + // Its own workspace's browse history: the window's answer follows the connection and mode on screen. var browseUndoManager: UndoManager? { let host = contentWindow?.contentViewController as? MainSplitViewController @@ -972,6 +978,7 @@ final class MainContentCoordinator: ObservableObject { return } commitActiveGridEdit() + endEditorCompletion() if tab.tabType == .table { executeTableTabQueryDirectly(trigger: trigger, viewport: viewport) @@ -986,6 +993,13 @@ final class MainContentCoordinator: ObservableObject { ) } + /// A run sends the reader to its results, which an open completion popup would cover until Escape. Completion + /// items load asynchronously, so a click on Run can land while a request is still out and the popup open after + /// it, and Command-Return passes through an open popup to the menu. Every run path ends the session first. + func endEditorCompletion() { + dismissEditorCompletions(contentWindow) + } + // Takes SQL, not a range: the editor text and the tab binding can briefly differ, and a range on the wrong one truncates silently. @discardableResult func runStatement(_ sql: String, sourceOffset: Int? = nil) -> Bool { @@ -995,6 +1009,7 @@ final class MainContentCoordinator: ObservableObject { return false } commitActiveGridEdit() + endEditorCompletion() return executeResolvedSQL(sql, tabIndex: index, bypassRowLimit: false, sourceOffset: sourceOffset) } diff --git a/apple/TableProTests/Views/Main/RunEndsEditorCompletionTests.swift b/apple/TableProTests/Views/Main/RunEndsEditorCompletionTests.swift new file mode 100644 index 0000000000..7e228ba9c4 --- /dev/null +++ b/apple/TableProTests/Views/Main/RunEndsEditorCompletionTests.swift @@ -0,0 +1,89 @@ +// +// RunEndsEditorCompletionTests.swift +// TableProTests +// +// A completion popup left open after a run covers the results until Escape. Every run path ends the +// editor's completion session in the coordinator's own window first. +// + +import AppKit +import Foundation +import Testing + +@testable import TablePro + +@MainActor +struct RunEndsEditorCompletionTests { + /// Blank text runs nothing, so no case reaches a driver or the execution gate, and each one still shows + /// that the session ends before the run decides what to execute. + @Test("Run, Run Statement and Run All end the completion session in the coordinator's window") + func everyRunPathEndsTheSession() { + let harness = Harness() + defer { harness.tearDown() } + + harness.coordinator.runQuery(viewport: .keepPlace) + harness.coordinator.runQuery(viewport: .keepPlace, bypassRowLimit: true) + harness.coordinator.runStatement(" ", sourceOffset: 0) + harness.coordinator.runAllStatements() + + #expect(harness.recorder.windows.count == 4) + #expect(harness.recorder.windows.allSatisfy { $0 === harness.window }) + } + + @Test("A run refused because the tab is already running leaves the session alone") + func refusedRunLeavesTheSession() throws { + let harness = Harness() + defer { harness.tearDown() } + let tabId = try #require(harness.tabManager.selectedTabId) + let claim = harness.coordinator.tabExecution.claim(tabId) + defer { _ = harness.coordinator.tabExecution.settle(claim) } + + harness.coordinator.runQuery(viewport: .keepPlace) + harness.coordinator.runStatement("SELECT 1", sourceOffset: 0) + + #expect(harness.recorder.windows.isEmpty) + } +} + +@MainActor +private final class WindowRecorder { + var windows: [NSWindow?] = [] +} + +/// A coordinator with one blank query tab selected, a window of its own and no session behind it. +@MainActor +private struct Harness { + let coordinator: MainContentCoordinator + let tabManager: QueryTabManager + let window: NSWindow + let recorder = WindowRecorder() + + init() { + tabManager = QueryTabManager() + coordinator = MainContentCoordinator( + connection: TestFixtures.makeConnection(type: .sqlite), + tabManager: tabManager, + changeManager: DataChangeManager(), + toolbarState: ConnectionToolbarState() + ) + window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + coordinator.contentWindow = window + let recorder = recorder + coordinator.dismissEditorCompletions = { recorder.windows.append($0) } + let tab = QueryTab(title: "Query", query: " ", tabType: .query) + tabManager.tabs.append(tab) + tabManager.selectedTabId = tab.id + } + + func tearDown() { + coordinator.cancelAllQueryTasks() + coordinator.teardown() + window.orderOut(nil) + } +} From ecd4fc774337b285f8765fdf44ec186c066e6e1e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:06:30 +0700 Subject: [PATCH 097/123] fix(tabs): give located tab titles their width and keep the database MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tabs shared the strip equally, so with seven tabs at 1512 pt a located title was cut to "orders@shop_dem…" and the connection never showed. In a scrolling strip a located tab now asks for its whole title, up to 320 pt, and takes the room from tabs that ask for none, down to the minimum width. When it still does not fit, the title drops the connection first, then truncates the middle of the table name and keeps "@database" whole. The reorder resolves against the drawn widths, and a width follows its tab through a drag. With the setting off, or in the wrapped strip, the run is the equal one it was. The tooltip and the accessibility label keep the full title. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../EditorTabLabelResolver.swift | 28 ++- .../Infrastructure/EditorTabReorder.swift | 35 +++ ...plitViewController+TabStripAccessory.swift | 11 + .../Views/Main/EditorTabRunLayout.swift | 53 +++- .../TablePro/Views/Main/EditorTabStrip.swift | 49 +++- .../Main/EditorTabStripInteraction.swift | 28 ++- .../Views/Main/EditorTabStripLayout.swift | 112 +++++++++ .../Main/EditorTabLabelResolverTests.swift | 36 ++- .../Main/EditorTabLocatedWidthTests.swift | 226 ++++++++++++++++++ 9 files changed, 564 insertions(+), 14 deletions(-) create mode 100644 apple/TableProTests/Views/Main/EditorTabLocatedWidthTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift index af96826186..10c2504b25 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabLabelResolver.swift @@ -53,16 +53,29 @@ internal enum EditorTabLabelResolver { /// still tells a table from a view at a glance. In the colorful style every tab showing an /// object or a query carries its kind's tinted glyph, which is the point of that style. internal let icon: ObjectIcon? + /// A located title's short form, drawn when the whole title does not fit, and nil for every other + /// title. The tab asks for the width of the whole title first; when the strip cannot give it, the + /// connection goes, then the object gives way in its middle while `@database` stays whole, so the + /// tab never loses the part that tells it from the same table in another database. + internal let shortForm: ShortForm? internal var symbolName: String? { icon?.symbolName } - internal init(text: String, description: String, icon: ObjectIcon? = nil) { + internal init(text: String, description: String, icon: ObjectIcon? = nil, shortForm: ShortForm? = nil) { self.text = text self.description = description self.icon = icon + self.shortForm = shortForm } } + /// `orders` and `@shop_demo` of `orders@shop_demo (Shop Demo)`. `database` is empty when the tab + /// names no database. + internal struct ShortForm: Equatable { + internal let object: String + internal let database: String + } + internal static func resolve( tabs: [QueryTab], target: ContainerSwitchTarget?, @@ -90,7 +103,8 @@ internal enum EditorTabLabelResolver { result[tab.id] = Label( text: isAmbiguous ? qualified : title, description: qualified, - icon: icon(of: tab, style: style, iconStyle: iconStyle) + icon: icon(of: tab, style: style, iconStyle: iconStyle), + shortForm: shortForm(of: tab, style: style, container: isAmbiguous ? containers[tab.id] : nil) ) } } @@ -116,6 +130,16 @@ internal enum EditorTabLabelResolver { ) } + /// Qualified the way the whole title is, so a collision the location does not settle stays told apart. + private static func shortForm(of tab: QueryTab, style: EditorTabTitleStyle, container: String?) -> ShortForm? { + guard case .location = style, showsObject(tab) else { return nil } + let database = tab.tableContext.databaseName + return ShortForm( + object: qualify(tab.title, with: container), + database: database.isEmpty ? "" : "@\(database)" + ) + } + private static func icon(of tab: QueryTab, style: EditorTabTitleStyle, iconStyle: ObjectIconStyle) -> ObjectIcon? { switch iconStyle { case .standard: diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift index aa52514285..740a9fc9bc 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift @@ -127,4 +127,39 @@ internal enum EditorTabReorderResolver { : Array((candidate ... (currentIndex - 1)).reversed()) return crossable.last(where: hasCrossed) } + + /// The tab a location falls in, for a run whose tabs need not be even: `boundaries` holds the + /// leading edge of each tab and the trailing edge of the last (`EditorTabRunLayout.linearBoundaries`). + internal static func destination(forLocation location: CGFloat, boundaries: [CGFloat]) -> Int { + let count = boundaries.count - 1 + guard count > 1 else { return 0 } + return boundaries[1 ..< count].filter { $0 <= location }.count + } + + /// `settledDestination(forLocation:tabWidth:currentIndex:count:)` for a run of uneven tabs, which a + /// located title asking for its whole width makes. The rule is the same, each neighbour's own centre, + /// and the run is rebuilt after every move, so a wide tab swapped past a narrow one does not swap back + /// until the pointer returns past the wide one's centre. + internal static func settledDestination( + forLocation location: CGFloat, + boundaries: [CGFloat], + currentIndex: Int + ) -> Int? { + let count = boundaries.count - 1 + guard count > 1, currentIndex >= 0, currentIndex < count else { return nil } + let candidate = destination(forLocation: location, boundaries: boundaries) + guard candidate != currentIndex else { return nil } + + func hasCrossed(_ index: Int) -> Bool { + let centre = (boundaries[index] + boundaries[index + 1]) / 2 + return candidate > currentIndex + ? location >= centre - crossingTolerance + : location <= centre + crossingTolerance + } + + let crossable = candidate > currentIndex + ? Array((currentIndex + 1) ... candidate) + : Array((candidate ... (currentIndex - 1)).reversed()) + return crossable.last(where: hasCrossed) + } } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift index c08c0833da..eac2ae2e4e 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift @@ -209,5 +209,16 @@ internal extension MainSplitViewController { tabIds: manager.visibleTabs.map(\.id), overflow: AppSettingsManager.shared.tabs.overflow ) + let settings = AppSettingsManager.shared + let labels = EditorTabLabelResolver.resolve( + tabs: manager.visibleTabs, + target: target, + style: EditorTabTitleStyle( + showsLocation: settings.tabs.titleShowsLocation, + connectionName: workspace.connection?.name ?? "" + ), + iconStyle: settings.appearance.objectIconStyle + ) + interaction.setPreferredWidths(EditorTabStripLayout.preferredWidths(tabs: manager.visibleTabs, labels: labels)) } } diff --git a/apple/TablePro/Views/Main/EditorTabRunLayout.swift b/apple/TablePro/Views/Main/EditorTabRunLayout.swift index 3bf4173095..67148781a0 100644 --- a/apple/TablePro/Views/Main/EditorTabRunLayout.swift +++ b/apple/TablePro/Views/Main/EditorTabRunLayout.swift @@ -40,6 +40,8 @@ internal struct EditorTabPlacement: Equatable { /// construction rather than by three views agreeing. internal struct EditorTabRunLayout: Equatable { internal let placements: [EditorTabPlacement] + /// The width every tab has in an even run, and the width of a tab that asked for none in a run where + /// some did (`EditorTabStripLayout.tabWidths(forTrack:preferred:)`). internal let tabWidth: CGFloat internal let tabsPerRow: Int internal let rowCount: Int @@ -56,6 +58,18 @@ internal struct EditorTabRunLayout: Equatable { internal func placement(at index: Int) -> EditorTabPlacement? { placements.first { $0.index == index } } + + /// Where one tab ends and the next begins along the axis the reorder resolves on, from the leading + /// edge of the first to the trailing edge of the last. One row as it is drawn, whatever its widths; + /// a wrapped run, whose tabs are always even, as if it had never wrapped. + internal var linearBoundaries: [CGFloat] { + guard !placements.isEmpty else { return [] } + guard rowCount == 1 else { + return (0 ... placements.count).map { CGFloat($0) * tabWidth } + } + let frames = placements.sorted { $0.index < $1.index }.map(\.frame) + return [frames[0].minX] + frames.map(\.maxX) + } } /// The pure geometry of the run, kept apart from both the AppKit view and the SwiftUI one. @@ -65,13 +79,27 @@ internal enum EditorTabRunLayoutBuilder { /// `scroll` keeps one row and lets the content run past the viewport. `rows` fits as many tabs /// per row as `minimumTabWidth` allows and wraps, so the content never runs wider than the /// track and no tab is ever off screen. + /// + /// `preferredWidths`, in run order, are the widths located tabs ask for. Only a scrolling run + /// honours them: a wrapped run fits its rows by counting even tabs, and an uneven row would leave + /// its gaps and its reorder projection disagreeing with what is drawn. internal static func run( forTrack width: CGFloat, count: Int, - overflow: EditorTabStripOverflow + overflow: EditorTabStripOverflow, + preferredWidths: [CGFloat?] = [] ) -> EditorTabRunLayout { guard count > 0, width > 0 else { return .empty } + if overflow == .scroll, preferredWidths.count == count, preferredWidths.contains(where: { $0 != nil }) { + let widths = EditorTabStripLayout.tabWidths(forTrack: width, preferred: preferredWidths) + let share = EditorTabStripLayout.tabWidth(forTrack: width, count: count) + if widths != Array(repeating: share, count: count) { + let flexible = preferredWidths.indices.first { preferredWidths[$0] == nil }.map { widths[$0] } + return unevenRun(widths: widths, flexibleWidth: flexible ?? share) + } + } + let usable = max(width - EditorTabStripLayout.trackPadding * 2, 0) let perRow = tabsPerRow(usable: usable, count: count, overflow: overflow) let rows = Int(ceil(Double(count) / Double(max(perRow, 1)))) @@ -107,6 +135,29 @@ internal enum EditorTabRunLayoutBuilder { ) } + /// One scrolling row of tabs laid edge to edge at their own widths. + private static func unevenRun(widths: [CGFloat], flexibleWidth: CGFloat) -> EditorTabRunLayout { + var leading: CGFloat = 0 + let placements = widths.enumerated().map { index, width -> EditorTabPlacement in + defer { leading += width } + return EditorTabPlacement( + index: index, + row: 0, + frame: CGRect(x: leading, y: 0, width: width, height: EditorTabStripLayout.tabHeight) + ) + } + return EditorTabRunLayout( + placements: placements, + tabWidth: flexibleWidth, + tabsPerRow: widths.count, + rowCount: 1, + contentSize: CGSize( + width: widths.reduce(0, +), + height: EditorTabStripLayout.rowStride - EditorTabStripLayout.rowSpacing + ) + ) + } + private static func tabsPerRow(usable: CGFloat, count: Int, overflow: EditorTabStripOverflow) -> Int { guard overflow == .rows else { return count } let fitting = Int(floor(usable / EditorTabStripLayout.minimumTabWidth)) diff --git a/apple/TablePro/Views/Main/EditorTabStrip.swift b/apple/TablePro/Views/Main/EditorTabStrip.swift index 86992d5730..af6513e20b 100644 --- a/apple/TablePro/Views/Main/EditorTabStrip.swift +++ b/apple/TablePro/Views/Main/EditorTabStrip.swift @@ -84,6 +84,12 @@ internal struct EditorTabStrip: View { .onChange(of: settings.tabs.overflow) { style in interaction.overflow = style } + /// A located title asks for its whole width. Handed over here, where the labels are resolved, on + /// appearing and whenever a title, the location setting or the icon style moves it. + .onAppear { interaction.setPreferredWidths(preferredWidths) } + .onChange(of: preferredWidths) { widths in + interaction.setPreferredWidths(widths) + } /// Cmd+1..9, opening a table from the sidebar and closing a tab can all land on a tab that /// is scrolled out of sight, so the selection pulls itself into view. .onChange(of: tabManager.selectedTabId) { newValue in @@ -168,6 +174,10 @@ internal struct EditorTabStrip: View { ) } + private var preferredWidths: [UUID: CGFloat] { + EditorTabStripLayout.preferredWidths(tabs: displayedTabs, labels: labels) + } + private var titleStyle: EditorTabTitleStyle { EditorTabTitleStyle(showsLocation: settings.tabs.titleShowsLocation, connectionName: connectionName) } @@ -362,12 +372,7 @@ private struct EditorTabStripItem: View { .foregroundStyle(glyphColor(for: icon)) .accessibilityHidden(true) } - Text(label.text) - .lineLimit(1) - .truncationMode(.tail) - .italic(tab.isPreview) - .font(.system(size: EditorTabStripLayout.fontSize)) - .foregroundStyle(titleColor) + titleText } .frame(maxWidth: .infinity) unseenIndicator @@ -382,6 +387,38 @@ private struct EditorTabStripItem: View { .contentShape(Rectangle()) } + /// A located title that does not fit drops the connection first, then gives way in the middle of the + /// object's name while `@database` stays whole: cut at its tail it lost the database and the + /// connection both, which are what tell this tab from the same table elsewhere. Any other title is + /// cut at its tail, as the system's tabs cut theirs. + @ViewBuilder + private var titleText: some View { + if let short = label.shortForm { + ViewThatFits(in: .horizontal) { + titleSegment(label.text) + HStack(spacing: 0) { + titleSegment(short.object) + .truncationMode(.middle) + if !short.database.isEmpty { + titleSegment(short.database) + .layoutPriority(1) + } + } + } + } else { + titleSegment(label.text) + .truncationMode(.tail) + } + } + + private func titleSegment(_ text: String) -> some View { + Text(text) + .lineLimit(1) + .italic(tab.isPreview) + .font(.system(size: EditorTabStripLayout.fontSize)) + .foregroundStyle(titleColor) + } + // The trailing slot is reserved, so nothing reflows. Running outranks the unseen mark, and shows on the selected tab too. @ViewBuilder private var unseenIndicator: some View { diff --git a/apple/TablePro/Views/Main/EditorTabStripInteraction.swift b/apple/TablePro/Views/Main/EditorTabStripInteraction.swift index 08163be1d0..6400f9dd21 100644 --- a/apple/TablePro/Views/Main/EditorTabStripInteraction.swift +++ b/apple/TablePro/Views/Main/EditorTabStripInteraction.swift @@ -49,6 +49,8 @@ internal final class EditorTabStripInteraction: ObservableObject { /// The last width the pointer's owner measured, kept so a tab opening or closing can re-lay /// the run without waiting for AppKit to schedule another layout pass. private var trackWidth: CGFloat = 0 + /// The widths located tabs ask for, keyed by tab so a width follows its tab through a reorder. + private var preferredWidths: [UUID: CGFloat] = [:] internal var overflow: EditorTabStripOverflow = .scroll { didSet { @@ -78,10 +80,12 @@ internal final class EditorTabStripInteraction: ObservableObject { internal func updateRun(trackWidth: CGFloat, count: Int) { self.trackWidth = trackWidth viewportWidth = max(trackWidth - EditorTabStripLayout.trackPadding * 2, 0) + let order = displayedIds let rebuilt = EditorTabRunLayoutBuilder.run( forTrack: trackWidth, count: count, - overflow: overflow + overflow: overflow, + preferredWidths: order.count == count && !preferredWidths.isEmpty ? order.map { preferredWidths[$0] } : [] ) guard rebuilt != run else { return } run = rebuilt @@ -91,6 +95,14 @@ internal final class EditorTabStripInteraction: ObservableObject { onRowCountChanged?(run.rowCount) } + /// Takes the widths the strip's labels ask for, from the view that resolves them. The run is rebuilt + /// only when one moved, since the view hands them over on every change of its labels. + internal func setPreferredWidths(_ widths: [UUID: CGFloat]) { + guard widths != preferredWidths else { return } + preferredWidths = widths + updateRun(trackWidth: trackWidth, count: tabIds.count) + } + internal func setHovered(_ id: UUID?, overCloseButton: Bool = false) { if hoveredTabId != id { hoveredTabId = id } let close = overCloseButton ? id : nil @@ -134,14 +146,14 @@ internal final class EditorTabStripInteraction: ObservableObject { guard var live = reorder, let currentIndex = live.destinationIndex else { return false } let destination = EditorTabReorderResolver.settledDestination( forLocation: location, - tabWidth: run.tabWidth, - currentIndex: currentIndex, - count: live.order.count + boundaries: run.linearBoundaries, + currentIndex: currentIndex ) guard let destination else { return false } live.move(to: destination) guard live != reorder else { return false } reorder = live + rebuildForNewOrder() return true } @@ -160,6 +172,14 @@ internal final class EditorTabStripInteraction: ObservableObject { internal func clearReorder() { reorder = nil tearingOffTabId = nil + rebuildForNewOrder() + } + + /// A tab that asked for its own width keeps it wherever the order puts it. An even run is the same + /// in any order, so it is left alone. + private func rebuildForNewOrder() { + guard !preferredWidths.isEmpty else { return } + updateRun(trackWidth: trackWidth, count: tabIds.count) } /// Takes the tab list and the overflow style from the model that owns them. diff --git a/apple/TablePro/Views/Main/EditorTabStripLayout.swift b/apple/TablePro/Views/Main/EditorTabStripLayout.swift index 306bfd9591..3176ea7057 100644 --- a/apple/TablePro/Views/Main/EditorTabStripLayout.swift +++ b/apple/TablePro/Views/Main/EditorTabStripLayout.swift @@ -3,6 +3,7 @@ // TablePro // +import AppKit import CoreGraphics import Foundation import SwiftUI @@ -90,6 +91,117 @@ internal enum EditorTabStripLayout { return max(usable / divisor, minimumTabWidth) } + /// The widest a located tab grows to show its whole title. Past it the title takes its short form. + internal static let maximumLocatedTabWidth: CGFloat = 320 + + /// The widths of a scrolling run in which some tabs ask for a width of their own, in run order. + /// + /// A located title, `orders@shop_demo (Shop Demo)`, is longer than an equal share of a strip with a + /// few tabs open, and the share cut it to `orders@shop_dem…` while the tabs beside it, `Query 1`, + /// held room they did not need. So a tab asking for more than the share takes it, up to the + /// maximum, from the tabs that ask for none, which give it up only down to the minimum a name fits + /// in. A tab asking for less than the share never drops below what it asked for. When the others + /// are at that minimum, the asking tabs share what is left evenly, never below the share itself. + /// Nothing asks: every tab gets the share, exactly as before. + internal static func tabWidths(forTrack width: CGFloat, preferred: [CGFloat?]) -> [CGFloat] { + let count = preferred.count + guard count > 0 else { return [] } + let share = tabWidth(forTrack: width, count: count) + let asked = preferred.map { $0.map { min(max($0, minimumTabWidth), maximumLocatedTabWidth) } } + let growing = asked.indices.filter { (asked[$0] ?? 0) > share } + guard !growing.isEmpty else { return Array(repeating: share, count: count) } + + let usable = max(width - trackPadding * 2, 0) + let others = asked.indices.filter { !growing.contains($0) } + let floors = others.map { asked[$0] ?? minimumTabWidth } + let room = usable - floors.reduce(0, +) + let level = cappingLevel(growing.map { asked[$0] ?? share }, total: room) + + var widths = Array(repeating: share, count: count) + for index in growing { + let wanted = asked[index] ?? share + widths[index] = min(wanted, max(level ?? wanted, share)) + } + let rest = usable - growing.reduce(0) { $0 + widths[$1] } + let raised = raisingLevel(floors, total: rest) + for (index, floor) in zip(others, floors) { + widths[index] = max(floor, raised) + } + return widths + } + + /// The level `L` at which every value capped at `L` adds up to `total`, or nil when the values fit + /// as they are. + private static func cappingLevel(_ values: [CGFloat], total: CGFloat) -> CGFloat? { + guard values.reduce(0, +) > total else { return nil } + var remaining = total + let sorted = values.sorted() + for (position, value) in sorted.enumerated() { + let even = remaining / CGFloat(sorted.count - position) + if value >= even { return even } + remaining -= value + } + return nil + } + + /// The level `L` at which every value raised to `L` adds up to `total`, or zero when the values + /// already take more than it. + private static func raisingLevel(_ values: [CGFloat], total: CGFloat) -> CGFloat { + var remaining = total + let sorted = values.sorted(by: >) + for (position, value) in sorted.enumerated() { + let even = remaining / CGFloat(sorted.count - position) + if value <= even { return even } + remaining -= value + } + return 0 + } + + /// The width a located tab asks for, keyed by tab. Only a located title asks: every other title is + /// short enough for the share, which is what it always had. + @MainActor + internal static func preferredWidths( + tabs: [QueryTab], + labels: [UUID: EditorTabLabelResolver.Label] + ) -> [UUID: CGFloat] { + tabs.reduce(into: [:]) { widths, tab in + guard let label = labels[tab.id], label.shortForm != nil else { return } + widths[tab.id] = min( + naturalWidth(of: label, isPinned: tab.isPinned, isPreview: tab.isPreview), + maximumLocatedTabWidth + ) + } + } + + /// What a tab needs to draw `label` whole: the close button's slot and the trailing slot that balances + /// it, their insets, the glyphs and the title in the strip's face. Rounded up, with a point to spare, + /// because a text measured to the exact width can still truncate once laid out. + internal static func naturalWidth(of label: EditorTabLabelResolver.Label, isPinned: Bool, isPreview: Bool) -> CGFloat { + var glyphs: [CGFloat] = [] + if isPinned { + glyphs.append(symbolWidth("pin.fill", pointSize: pinGlyphSize)) + } + if let icon = label.icon { + glyphs.append(symbolWidth(icon.symbolName, pointSize: objectGlyphSize)) + } + let parts = glyphs + [textWidth(label.text, isPreview: isPreview)] + let spacing = pinSpacing * CGFloat(parts.count - 1) + return ceil(accessoryInset * 2 + accessoryWidth * 2 + parts.reduce(0, +) + spacing) + 1 + } + + /// The title's width in the face the strip draws it in, italic for a preview. + internal static func textWidth(_ text: String, isPreview: Bool) -> CGFloat { + let regular = NSFont.systemFont(ofSize: fontSize) + let font = isPreview ? NSFontManager.shared.convert(regular, toHaveTrait: .italicFontMask) : regular + return ceil((text as NSString).size(withAttributes: [.font: font]).width) + } + + private static func symbolWidth(_ name: String, pointSize: CGFloat) -> CGFloat { + let configuration = NSImage.SymbolConfiguration(pointSize: pointSize, weight: .regular) + let image = NSImage(systemSymbolName: name, accessibilityDescription: nil)?.withSymbolConfiguration(configuration) + return ceil(image?.size.width ?? pointSize) + } + /// How far a tab fades while it is the one being dragged. Enough to read as lifted out of the /// strip, not so far that its title stops being legible on the way past its neighbours. internal static let draggingOpacity: CGFloat = 0.45 diff --git a/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift b/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift index 1ee7c6f046..4c14d6e835 100644 --- a/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabLabelResolverTests.swift @@ -150,7 +150,9 @@ struct EditorTabLabelResolverTests { #expect(labels[tabs[0].id]?.text == "orders (Shop Demo)") } - @Test("A long title is kept whole with the table name first, so the strip's tail truncation cuts the location") + /// The strip, not the resolver, shortens a title that does not fit, so the text stays whole and the + /// short form carries the parts the strip keeps. + @Test("A long title is kept whole, and its short form keeps the table and the database apart") func keepsLongTitlesWhole() { let table = String(repeating: "customer_order_line_item_", count: 4) + "archive" let database = String(repeating: "warehouse_reporting_", count: 3) + "replica" @@ -164,6 +166,38 @@ struct EditorTabLabelResolverTests { #expect(text == "\(table)@\(database) (\(connection))") #expect(text.hasPrefix(table)) #expect(!text.contains("…")) + #expect(labels[tabs[0].id]?.shortForm == EditorTabLabelResolver.ShortForm(object: table, database: "@\(database)")) + } + + @Test("Only a located title has a short form, and one with no database keeps the object alone") + func shortFormBelongsToLocatedTitles() { + let tabs = [ + tableTab("orders", database: "shop_demo"), + tableTab("audit_log"), + QueryTab(title: "Query 1", tabType: .query), + ] + let located = EditorTabLabelResolver.resolve(tabs: tabs, target: .database, style: shop) + let named = EditorTabLabelResolver.resolve(tabs: tabs, target: .database) + + #expect(located[tabs[0].id]?.shortForm == EditorTabLabelResolver.ShortForm(object: "orders", database: "@shop_demo")) + #expect(located[tabs[1].id]?.shortForm == EditorTabLabelResolver.ShortForm(object: "audit_log", database: "")) + #expect(located[tabs[2].id]?.shortForm == nil) + #expect(tabs.allSatisfy { named[$0.id]?.shortForm == nil }) + } + + /// Two schemas of one database hold `orders` each: the location does not tell them apart, the schema does, + /// and the short form has to keep it. + @Test("A short form keeps the schema a collision needs") + func shortFormKeepsTheQualifyingSchema() { + let tabs = [ + tableTab("orders", database: "shop_demo", schema: "sales"), + tableTab("orders", database: "shop_demo", schema: "archive"), + ] + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: .schema, style: shop) + + #expect(labels[tabs[0].id]?.text == "sales.orders@shop_demo (Shop Demo)") + #expect(labels[tabs[0].id]?.shortForm == EditorTabLabelResolver.ShortForm(object: "sales.orders", database: "@shop_demo")) + #expect(labels[tabs[1].id]?.shortForm?.object == "archive.orders") } @Test("A view tab carries the view glyph, and every other object kind its sidebar glyph") diff --git a/apple/TableProTests/Views/Main/EditorTabLocatedWidthTests.swift b/apple/TableProTests/Views/Main/EditorTabLocatedWidthTests.swift new file mode 100644 index 0000000000..9b3d3e77f6 --- /dev/null +++ b/apple/TableProTests/Views/Main/EditorTabLocatedWidthTests.swift @@ -0,0 +1,226 @@ +// +// EditorTabLocatedWidthTests.swift +// TableProTests +// +// A located title (`orders@shop_demo (Shop Demo)`) is longer than an equal share of the strip, so it +// asks for its own width and takes it from the tabs that ask for none, down to the minimum a name +// fits in. The reorder follows the widths the run draws. +// + +import CoreGraphics +import Foundation +import Testing + +@testable import TablePro + +struct EditorTabLocatedWidthTests { + private static let wideTrack: CGFloat = 1_180 + private static var usable: CGFloat { wideTrack - EditorTabStripLayout.trackPadding * 2 } + + private static func widths(_ run: EditorTabRunLayout) -> [CGFloat] { + run.placements.sorted { $0.index < $1.index }.map(\.frame.width) + } + + private static func isClose(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { + abs(lhs - rhs) < 0.001 + } + + // MARK: - Widths + + @Test("Without a preferred width the run is the equal share it always was") + func noPreferenceKeepsTheEqualShare() { + let plain = EditorTabRunLayoutBuilder.run(forTrack: Self.wideTrack, count: 7, overflow: .scroll) + let unasked = EditorTabRunLayoutBuilder.run( + forTrack: Self.wideTrack, count: 7, overflow: .scroll, preferredWidths: Array(repeating: nil, count: 7) + ) + let modest = EditorTabRunLayoutBuilder.run( + forTrack: Self.wideTrack, count: 7, overflow: .scroll, preferredWidths: [130, nil, 140, nil, nil, nil, nil] + ) + + #expect(unasked == plain) + #expect(modest == plain) + } + + @Test("A located tab grows to its whole title when the other tabs can give it room") + func locatedTabGrowsWhenThereIsRoom() { + let run = EditorTabRunLayoutBuilder.run( + forTrack: Self.wideTrack, count: 7, overflow: .scroll, + preferredWidths: [nil, 205, nil, 225, nil, nil, nil] + ) + let widths = Self.widths(run) + let others = (Self.usable - 430) / 5 + + #expect(widths[1] == 205) + #expect(widths[3] == 225) + #expect([0, 2, 4, 5, 6].allSatisfy { Self.isClose(widths[$0], others) }) + #expect(Self.isClose(run.contentSize.width, Self.usable)) + #expect(run.rowCount == 1) + } + + @Test("The tabs sit edge to edge in their order, whatever their widths") + func placementsAreContiguous() { + let run = EditorTabRunLayoutBuilder.run( + forTrack: Self.wideTrack, count: 4, overflow: .scroll, preferredWidths: [nil, 310, nil, 290] + ) + let frames = run.placements.sorted { $0.index < $1.index }.map(\.frame) + + #expect(frames.first?.minX == 0) + for index in 1 ..< frames.count { + #expect(Self.isClose(frames[index].minX, frames[index - 1].maxX)) + } + #expect(Self.isClose(run.linearBoundaries.last ?? 0, run.contentSize.width)) + #expect(run.linearBoundaries.count == 5) + } + + @Test("The other tabs give room only down to the minimum, and the growing tabs share what is left") + func growingTabsShareWhenRoomRunsOut() { + let track: CGFloat = 800 + let usable = track - EditorTabStripLayout.trackPadding * 2 + let run = EditorTabRunLayoutBuilder.run( + forTrack: track, count: 6, overflow: .scroll, preferredWidths: [300, 300, nil, nil, nil, nil] + ) + let widths = Self.widths(run) + let minimum = EditorTabStripLayout.minimumTabWidth + let grown = (usable - 4 * minimum) / 2 + + #expect(Self.isClose(widths[0], grown)) + #expect(Self.isClose(widths[1], grown)) + #expect(widths[2 ... 5].allSatisfy { Self.isClose($0, minimum) }) + #expect(Self.isClose(run.contentSize.width, usable)) + } + + @Test("A located tab never grows past the maximum") + func preferredWidthIsCapped() { + let run = EditorTabRunLayoutBuilder.run( + forTrack: Self.wideTrack, count: 7, overflow: .scroll, preferredWidths: [1_000, nil, nil, nil, nil, nil, nil] + ) + #expect(Self.widths(run)[0] == EditorTabStripLayout.maximumLocatedTabWidth) + } + + @Test("A tab asking for less than the room the others get never drops below what it asked for") + func smallerRequestIsAFloor() { + let run = EditorTabRunLayoutBuilder.run( + forTrack: Self.wideTrack, count: 7, overflow: .scroll, + preferredWidths: [150, 300, nil, nil, nil, nil, nil] + ) + let widths = Self.widths(run) + + #expect(widths[0] == 150) + #expect(widths[1] == 300) + #expect(widths[2 ... 6].allSatisfy { Self.isClose($0, (Self.usable - 450) / 5) }) + #expect(Self.isClose(run.contentSize.width, Self.usable)) + } + + @Test("A full strip keeps every tab at the minimum and scrolls as it did") + func fullStripScrollsAsBefore() { + let plain = EditorTabRunLayoutBuilder.run(forTrack: 604, count: 12, overflow: .scroll) + let located = EditorTabRunLayoutBuilder.run( + forTrack: 604, count: 12, overflow: .scroll, preferredWidths: Array(repeating: 260, count: 12) + ) + + #expect(located == plain) + } + + @Test("A wrapped strip keeps its equal widths") + func wrappingIgnoresPreferredWidths() { + let plain = EditorTabRunLayoutBuilder.run(forTrack: Self.wideTrack, count: 7, overflow: .rows) + let located = EditorTabRunLayoutBuilder.run( + forTrack: Self.wideTrack, count: 7, overflow: .rows, preferredWidths: [nil, 300, nil, 300, nil, nil, nil] + ) + + #expect(located == plain) + } + + // MARK: - Reorder + + @Test("The reorder crosses a wide neighbour at its own centre, and the swap does not undo itself") + func reorderUsesTheDrawnWidths() { + let before: [CGFloat] = [0, 100, 400, 500] + #expect(EditorTabReorderResolver.settledDestination(forLocation: 240, boundaries: before, currentIndex: 0) == nil) + #expect(EditorTabReorderResolver.settledDestination(forLocation: 260, boundaries: before, currentIndex: 0) == 1) + + // The narrow tab now sits after the wide one, and the pointer has not come back past the wide one's centre. + let after: [CGFloat] = [0, 300, 400, 500] + #expect(EditorTabReorderResolver.settledDestination(forLocation: 260, boundaries: after, currentIndex: 1) == nil) + #expect(EditorTabReorderResolver.settledDestination(forLocation: 140, boundaries: after, currentIndex: 1) == 0) + } + + @Test("Equal boundaries answer exactly as the equal width does") + func boundariesMatchTheEqualWidth() { + let width: CGFloat = 120 + let boundaries = (0 ... 5).map { CGFloat($0) * width } + for current in 0 ..< 5 { + for location in stride(from: CGFloat(-50), through: 700, by: 7.5) { + #expect( + EditorTabReorderResolver.settledDestination( + forLocation: location, boundaries: boundaries, currentIndex: current + ) == EditorTabReorderResolver.settledDestination( + forLocation: location, tabWidth: width, currentIndex: current, count: 5 + ) + ) + } + } + } + + // MARK: - The strip's state + + @MainActor + @Test("A preferred width reaches the run, and follows its tab through a reorder") + func interactionCarriesWidthsWithTheirTabs() throws { + let ids = (0 ..< 4).map { _ in UUID() } + let interaction = EditorTabStripInteraction() + interaction.adopt(tabIds: ids, overflow: .scroll) + interaction.updateRun(trackWidth: Self.wideTrack, count: ids.count) + + interaction.setPreferredWidths([ids[0]: 310]) + #expect(interaction.run.placement(at: 0)?.frame.width == 310) + + interaction.beginReorder(of: ids[0]) + interaction.updateReorder(toLinearLocation: 2_000) + let moved = try #require(interaction.displayedIds.firstIndex(of: ids[0])) + #expect(moved == ids.count - 1) + #expect(interaction.run.placement(at: moved)?.frame.width == 310) + #expect(interaction.run.placement(at: 0)?.frame.width != 310) + + interaction.clearReorder() + #expect(interaction.run.placement(at: 0)?.frame.width == 310) + } + + // MARK: - What a tab asks for + + @MainActor + @Test("Only a located title asks for a width, and it is wider than its text alone") + func onlyLocatedTitlesAskForAWidth() throws { + var table = QueryTab(title: "orders", tabType: .table, tableName: "orders") + table.tableContext.databaseName = "shop_demo" + let query = QueryTab(title: "Query 1", tabType: .query) + let tabs = [table, query] + + let located = EditorTabLabelResolver.resolve( + tabs: tabs, target: .database, style: .location(connectionName: "Shop Demo") + ) + let widths = EditorTabStripLayout.preferredWidths(tabs: tabs, labels: located) + let width = try #require(widths[table.id]) + #expect(widths[query.id] == nil) + #expect(width > EditorTabStripLayout.textWidth("orders@shop_demo (Shop Demo)", isPreview: false)) + #expect(width <= EditorTabStripLayout.maximumLocatedTabWidth) + + let named = EditorTabLabelResolver.resolve(tabs: tabs, target: .database) + #expect(EditorTabStripLayout.preferredWidths(tabs: tabs, labels: named).isEmpty) + } + + @MainActor + @Test("A longer title asks for more room, and a glyph adds its own") + func naturalWidthGrowsWithItsParts() { + let short = EditorTabLabelResolver.Label(text: "orders@shop (A)", description: "") + let long = EditorTabLabelResolver.Label(text: "customer_orders@shop_demo (Shop Demo)", description: "") + let glyph = EditorTabLabelResolver.Label( + text: "orders@shop (A)", description: "", icon: ObjectIcon(symbolName: "tablecells") + ) + + let shortWidth = EditorTabStripLayout.naturalWidth(of: short, isPinned: false, isPreview: false) + #expect(EditorTabStripLayout.naturalWidth(of: long, isPinned: false, isPreview: false) > shortWidth) + #expect(EditorTabStripLayout.naturalWidth(of: glyph, isPinned: false, isPreview: false) > shortWidth) + #expect(EditorTabStripLayout.naturalWidth(of: short, isPinned: true, isPreview: false) > shortWidth) + } +} From c54f12e3c3409770cef92ae36574b49001d934d6 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:06:31 +0700 Subject: [PATCH 098/123] fix(listing): reuse the container's Objects tab for a selection of another kind A selection previewed a container's objects beside a kept Objects tab of the same container whenever that tab showed another kind, so clicking shop_demo after the Views button had kept its tab opened a second "Objects" tab of the same database. A preview now lands on the kept listing showing the kind, else the container's preview, else the kept listing, which switches to the kind asked for. One container has one Objects tab. Tests updated on purpose: the cases that expected a preview beside a kept listing now expect the kept listing reused, and the ones that need a kept listing with a preview beside it build that pair directly, as only a restored session can hold it now. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Query/QueryTabManager.swift | 19 +++-- .../QueryTabManagerTableListingTests.swift | 72 +++++++++++-------- .../Main/CoordinatorTableListingTests.swift | 29 +++++--- 3 files changed, 72 insertions(+), 48 deletions(-) diff --git a/apple/TablePro/Models/Query/QueryTabManager.swift b/apple/TablePro/Models/Query/QueryTabManager.swift index 3421c3d98d..24b0e512d9 100644 --- a/apple/TablePro/Models/Query/QueryTabManager.swift +++ b/apple/TablePro/Models/Query/QueryTabManager.swift @@ -548,9 +548,9 @@ final class QueryTabManager: ObservableObject { selectedTabId = newTab.id } - // A container holds at most one kept listing and one preview, the way a table preview sits beside kept table tabs. - // Asking again lands on one of them and another kind retargets it, rather than opening a third. A new preview takes - // the strip slot of the preview it replaces, so browsing the sidebar does not grow the strip. + // A container holds one listing, kept or a preview. Asking again lands on it and another kind retargets it, rather + // than opening a second. A new preview takes the strip slot of the preview it replaces, so browsing the sidebar does + // not grow the strip. @discardableResult func addTableListingTab( title: String, @@ -596,9 +596,11 @@ final class QueryTabManager: ObservableObject { } /// Where a request for a container's objects lands among the listings open for it, nil for a new - /// tab. A preview never changes a kept listing, so its kind, filter and sort survive browsing: it - /// returns to one showing the kind, else it takes the container's preview. A request to keep takes - /// the kept listing, else the preview, and the preview beside a kept listing goes. + /// tab. One container has one Objects tab: a preview returns to a kept listing showing the kind, as + /// it is, else it takes the container's preview, else the kept listing, which then shows the kind + /// asked for. Opening a second tab beside a kept one put two "Objects" tabs of one database on the + /// strip with nothing to tell them apart. A request to keep takes the kept listing, else the preview, + /// and a preview left beside a kept listing, which only a restored session can hold, goes. func tableListingLanding( databaseName: String, schemaName: String?, @@ -619,7 +621,10 @@ final class QueryTabManager: ObservableObject { if let keptShowingKind { return TableListingLanding(tabId: keptShowingKind.id, retargets: false, closesPreviewId: nil) } - return preview.map { TableListingLanding(tabId: $0.id, retargets: true, closesPreviewId: nil) } + if let preview { + return TableListingLanding(tabId: preview.id, retargets: true, closesPreviewId: nil) + } + return kept.first.map { TableListingLanding(tabId: $0.id, retargets: true, closesPreviewId: nil) } } if let keptTab = keptShowingKind ?? kept.first { return TableListingLanding(tabId: keptTab.id, retargets: true, closesPreviewId: preview?.id) diff --git a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift index 902f6eb931..114b5a10e6 100644 --- a/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift +++ b/apple/TableProTests/Models/Query/QueryTabManagerTableListingTests.swift @@ -86,27 +86,41 @@ struct QueryTabManagerTableListingTests { // MARK: - A kept listing and a preview beside it - @Test("A preview of another kind opens beside a kept listing and leaves it as it was") - func previewOpensBesideTheKeptListing() throws { + /// A preview restored or kept beside a kept listing, which no request can make any more but a session + /// saved before the container had one Objects tab still holds. + private func appendListing( + to manager: QueryTabManager, + title: String, + databaseName: String, + kind: SidebarObjectKind? = nil, + isPreview: Bool + ) -> UUID { + var tab = QueryTab(title: title, tabType: .tableListing) + tab.tableContext.isEditable = false + tab.tableContext.databaseName = databaseName + tab.display.listingKind = kind + tab.isPreview = isPreview + manager.tabs.append(tab) + manager.selectedTabId = tab.id + return tab.id + } + + @Test("A preview of another kind shows it in the container's kept listing rather than opening a second") + func previewOfAnotherKindReusesTheKeptListing() throws { let manager = QueryTabManager() - let kept = manager.addTableListingTab(title: "Tables: sales", databaseName: "shop", schemaName: "sales") - let version = manager.tabStructureVersion + let kept = manager.addTableListingTab(title: "Objects: sales", databaseName: "shop", schemaName: "sales") + manager.addTab(initialQuery: "SELECT 1", databaseName: "shop") - let preview = manager.addTableListingTab( - title: "Views: sales", databaseName: "shop", schemaName: "sales", kind: .view, isPreview: true + let landed = manager.addTableListingTab( + title: "Objects: sales", databaseName: "shop", schemaName: "sales", kind: .view, isPreview: true ) let keptTab = try #require(manager.tabs.first { $0.id == kept }) - let previewTab = try #require(manager.tabs.first { $0.id == preview }) - #expect(preview != kept) - #expect(manager.tabs.map(\.id) == [kept, preview]) - #expect(manager.selectedTabId == preview) - #expect(keptTab.display.listingKind == nil) - #expect(keptTab.title == "Tables: sales") - #expect(!keptTab.isPreview) - #expect(previewTab.display.listingKind == .view) - #expect(previewTab.isPreview) - #expect(manager.tabStructureVersion > version) + #expect(landed == kept) + #expect(manager.tabs.filter { $0.tabType == .tableListing }.map(\.id) == [kept]) + #expect(manager.selectedTabId == kept) + #expect(keptTab.display.listingKind == .view) + #expect(!keptTab.isPreview, "A browse never turns a kept tab back into a preview") } @Test("A preview asking for the kind a kept listing shows selects that listing") @@ -126,13 +140,11 @@ struct QueryTabManagerTableListingTests { #expect(manager.tabs.first { $0.id == kept }?.isPreview == false) } - @Test("Another preview kind retargets the preview beside the kept listing, never the kept one") + @Test("Another preview kind retargets a preview left beside the kept listing, never the kept one") func previewRetargetsOnlyThePreview() throws { let manager = QueryTabManager() let kept = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil) - let preview = manager.addTableListingTab( - title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true - ) + let preview = appendListing(to: manager, title: "Views", databaseName: "shop", kind: .view, isPreview: true) let landed = manager.addTableListingTab( title: "Functions", databaseName: "shop", schemaName: nil, kind: .function, isPreview: true @@ -146,13 +158,11 @@ struct QueryTabManagerTableListingTests { #expect(manager.tabs.first { $0.id == preview }?.isPreview == true) } - @Test("A request to keep retargets the kept listing and closes the preview beside it") + @Test("A request to keep retargets the kept listing and closes a preview left beside it") func keepRequestRetargetsTheKeptListingAndClosesThePreview() throws { let manager = QueryTabManager() let kept = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil) - let preview = manager.addTableListingTab( - title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true - ) + let preview = appendListing(to: manager, title: "Views", databaseName: "shop", kind: .view, isPreview: true) let landing = try #require( manager.tableListingLanding(databaseName: "shop", schemaName: nil, kind: .function, isPreview: false) ) @@ -171,20 +181,22 @@ struct QueryTabManagerTableListingTests { #expect(manager.selectedTab?.isPreview == false) } - @Test("Each container keeps its own kept listing and preview") - func otherContainersKeepTheirOwnPair() throws { + @Test("Each container keeps its own listing") + func otherContainersKeepTheirOwnListing() throws { let manager = QueryTabManager() let shop = manager.addTableListingTab(title: "Tables", databaseName: "shop", schemaName: nil) let archive = manager.addTableListingTab(title: "Tables", databaseName: "archive", schemaName: nil) - let shopViews = manager.addTableListingTab( - title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true + let reports = manager.addTableListingTab( + title: "Views", databaseName: "reports", schemaName: nil, kind: .view, isPreview: true ) manager.addTableListingTab(title: "Functions", databaseName: "archive", schemaName: nil, kind: .function) + manager.addTableListingTab(title: "Views", databaseName: "shop", schemaName: nil, kind: .view, isPreview: true) - #expect(manager.tabs.map(\.id) == [shop, archive, shopViews]) + #expect(manager.tabs.map(\.id) == [shop, archive, reports]) #expect(manager.tabs.first { $0.id == archive }?.display.listingKind == .function) - #expect(manager.tabs.first { $0.id == shopViews }?.display.listingKind == .view) + #expect(manager.tabs.first { $0.id == shop }?.display.listingKind == .view) + #expect(manager.tabs.first { $0.id == reports }?.display.listingKind == .view) } @Test("Tables is stored as no kind, so it reads like a tab saved before kinds existed") diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index 0ac0307d27..3f7d0ac843 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -183,21 +183,22 @@ struct CoordinatorTableListingTests { #expect(tabManager.tabs.count == 2) } - @Test("A selection of another kind in a kept listing's container previews it beside the kept tab") - func selectionBesideAKeptListingLeavesItAlone() throws { + /// Clicking the database row after the Views button had kept its Objects tab put a second "Objects" + /// tab of the same database on the strip. + @Test("A selection of another kind in a kept listing's container shows it in that tab, never a second") + func selectionReusesTheKeptListing() throws { let (coordinator, tabManager, _) = makeCoordinator() defer { coordinator.teardown() } - coordinator.showObjects(group("shop"), asPreview: false) + coordinator.showObjects(group("shop", .view), asPreview: false) let kept = try #require(tabManager.selectedTabId) + tabManager.addTab(initialQuery: "SELECT 1", databaseName: "shop") - coordinator.showObjects(group("shop", .view), asPreview: true) + coordinator.showObjects(group("shop"), asPreview: true) - let preview = try #require(tabManager.selectedTab) let keptTab = try #require(tabManager.tabs.first { $0.id == kept }) - #expect(tabManager.tabs.map(\.id) == [kept, preview.id]) - #expect(preview.isPreview) - #expect(preview.display.listingKind == .view) - #expect(keptTab.display.listingKind == nil) + #expect(tabManager.selectedTabId == kept) + #expect(tabManager.tabs.filter { $0.tabType == .tableListing }.map(\.id) == [kept]) + #expect(keptTab.display.listingKind == nil, "The tab shows the Tables the selection asked for") #expect(keptTab.title == String(localized: "Objects")) #expect(!keptTab.isPreview) } @@ -217,13 +218,19 @@ struct CoordinatorTableListingTests { #expect(tabManager.selectedTab?.isPreview == false) } - @Test("Show Objects retargets the kept listing, closes the preview beside it and refreshes the kept one") + @Test("Show Objects retargets the kept listing, closes a preview left beside it and refreshes the kept one") func showObjectsTakesTheKeptListing() throws { let (coordinator, tabManager, _) = makeCoordinator() defer { coordinator.teardown() } coordinator.showObjects(group("shop"), asPreview: false) let kept = try #require(tabManager.selectedTabId) - coordinator.showObjects(group("shop", .view), asPreview: true) + // Only a session restored from before one container had one Objects tab holds a preview beside a kept one. + var leftover = QueryTab(title: String(localized: "Objects"), tabType: .tableListing) + leftover.tableContext.databaseName = "shop" + leftover.display.listingKind = .view + leftover.isPreview = true + tabManager.tabs.append(leftover) + tabManager.selectedTabId = leftover.id var refreshed: [UUID] = [] let subscription = AppEvents.shared.tabRefreshRequested.sink { refreshed.append($0) } defer { subscription.cancel() } From 25d9660ec28cece1878bc586792807395893c4e5 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:06:38 +0700 Subject: [PATCH 099/123] fix(toolbar): keep Save Changes in place on a labeled toolbar On the Objects tab, and on the other tabs that can never stage a change, the toolbar hid Save Changes, so Refresh, Actions and Safe Mode moved across the titlebar on every switch. With the Navigator Layout's labels on, the item now stays where it is, disabled. The visibility key carries the labels setting, and a change of it applies the context again. Without labels the toolbar hides it as before. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Context.swift | 3 ++- .../Infrastructure/MainWindowToolbar.swift | 7 ++++-- .../Toolbar/ToolbarContextResolver.swift | 6 +++-- apple/TablePro/Models/UI/ToolbarContext.swift | 9 ++++++- .../ToolbarContextResolverTests.swift | 25 +++++++++++++++++++ .../Infrastructure/ToolbarLabelsTests.swift | 12 +++++++++ 6 files changed, 56 insertions(+), 6 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift index 9589fcd937..ceff214942 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Context.swift @@ -33,7 +33,8 @@ internal extension MainWindowToolbar { ?? false, isAIEnabled: AppSettingsManager.shared.ai.enabled, stagesObjectChanges: tab?.tabType == .objectSource && tab?.display.objectRef?.kind == .userType, - showsDebugItems: debugItemsEnabled() + showsDebugItems: debugItemsEnabled(), + keepsContentCommandsInPlace: labelsEnabled() ) } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index dbcfb7c6df..69f598df00 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -605,10 +605,13 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } } - // Pushed by the General setting's own write, like the Objects buttons. + // Pushed by the General setting's own write, like the Objects buttons. The labels also decide whether a content + // command that cannot act hides or dims in place, so the visibility is applied again. internal static func applyToolbarLabelsSettingChange() { for window in NSApp.windows { - (window.toolbar?.delegate as? MainWindowToolbar)?.reconcileDisplayMode() + guard let owner = window.toolbar?.delegate as? MainWindowToolbar else { continue } + owner.reconcileDisplayMode() + owner.refreshContext() } } diff --git a/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift b/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift index 68d5bdf2fd..8408885094 100644 --- a/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift +++ b/apple/TablePro/Core/Services/Infrastructure/Toolbar/ToolbarContextResolver.swift @@ -71,8 +71,10 @@ internal enum ToolbarContextResolver { case .objectSource where key.stagesObjectChanges: return [] case .serverDashboard, .insights, .tableHealth, .objectSource, .versionHistory, .tableListing: - // None of these can stage a change, so the commit control could only ever be dim. - return [MainWindowToolbar.saveChanges] + // None of these can stage a change, so the commit control could only ever be dim. A labeled toolbar keeps + // it there, dim: each item is wide with its name under it, and taking one out moved Refresh, Actions and + // Safe Mode across the titlebar on every switch to one of these tabs. + return key.keepsContentCommandsInPlace ? [] : [MainWindowToolbar.saveChanges] case .routineDebug, .liveMessages: // A debug run or a live subscription has nothing to reload or commit; its own controls take that place. return [MainWindowToolbar.refresh, MainWindowToolbar.saveChanges] diff --git a/apple/TablePro/Models/UI/ToolbarContext.swift b/apple/TablePro/Models/UI/ToolbarContext.swift index 013f47aacc..fba4a3ab4c 100644 --- a/apple/TablePro/Models/UI/ToolbarContext.swift +++ b/apple/TablePro/Models/UI/ToolbarContext.swift @@ -42,6 +42,8 @@ internal struct ToolbarContext: Equatable { // Whether the Routine Debugger module puts its controls in the toolbar at all. internal let showsDebugItems: Bool + // A labeled toolbar is a fixed strip of named commands: a content command that cannot act dims in place. + internal let keepsContentCommandsInPlace: Bool // What the selected debug tab can do now; empty and false everywhere else. internal let debugCommands: Set internal let canStopDebugging: Bool @@ -67,6 +69,7 @@ internal struct ToolbarContext: Equatable { internal let isAIEnabled: Bool internal var stagesObjectChanges = false internal var showsDebugItems = false + internal var keepsContentCommandsInPlace = false } internal var visibilityKey: VisibilityKey { @@ -80,7 +83,8 @@ internal struct ToolbarContext: Equatable { supportsServerDashboard: supportsServerDashboard, isAIEnabled: isAIEnabled, stagesObjectChanges: stagesObjectChanges, - showsDebugItems: showsDebugItems + showsDebugItems: showsDebugItems, + keepsContentCommandsInPlace: keepsContentCommandsInPlace ) } @@ -106,6 +110,7 @@ internal struct ToolbarContext: Equatable { isAIEnabled: Bool = false, stagesObjectChanges: Bool = false, showsDebugItems: Bool = false, + keepsContentCommandsInPlace: Bool = false, debugCommands: Set = [], canStopDebugging: Bool = false, isPresentingSheet: Bool = false, @@ -136,6 +141,7 @@ internal struct ToolbarContext: Equatable { self.isAIEnabled = isAIEnabled self.stagesObjectChanges = stagesObjectChanges self.showsDebugItems = showsDebugItems + self.keepsContentCommandsInPlace = keepsContentCommandsInPlace self.debugCommands = debugCommands self.canStopDebugging = canStopDebugging self.isPresentingSheet = isPresentingSheet @@ -191,6 +197,7 @@ internal struct ToolbarContext: Equatable { isAIEnabled: key.isAIEnabled, stagesObjectChanges: key.stagesObjectChanges, showsDebugItems: key.showsDebugItems, + keepsContentCommandsInPlace: key.keepsContentCommandsInPlace, debugCommands: debugCommands, canStopDebugging: canStopDebugging, isPresentingSheet: isPresentingSheet, diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift index f4159ae8f8..427054cb66 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarContextResolverTests.swift @@ -296,6 +296,31 @@ struct ToolbarContextResolverTests { #expect(hidden.contains(MainWindowToolbar.refresh) == false) } + /// A labeled toolbar draws each item wide with its name under it, so an item taken out moves every + /// one after it. There the commit control stays where it is and dims instead. + @Test( + "A labeled toolbar keeps the commit control in place, dim, where a tab can never stage a change", + arguments: [TabType.serverDashboard, .insights, .tableHealth, .objectSource, .versionHistory, .tableListing] + ) + func labeledToolbarKeepsSaveChangesInPlace(tabKind: TabType) { + let context = ToolbarContext( + tabKind: tabKind, + pane: .content, + isConnected: true, + hasSelectedWorkspace: true, + keepsContentCommandsInPlace: true + ) + #expect(context.visibilityKey.keepsContentCommandsInPlace) + #expect(Self.hidden(context).contains(MainWindowToolbar.saveChanges) == false) + #expect(ToolbarContextResolver.isEnabled(MainWindowToolbar.saveChanges, context: context) == false) + } + + @Test("The Objects tab still loses the commit control on a toolbar without labels") + func objectsTabHidesSaveChangesWithoutLabels() { + let context = ToolbarContext(tabKind: .tableListing, pane: .content, isConnected: true, hasSelectedWorkspace: true) + #expect(Self.hidden(context).contains(MainWindowToolbar.saveChanges)) + } + @Test("A type's tab stages changes, so it keeps the commit control other object tabs lose") func typeTabKeepsSaveChanges() { let typeTab = ToolbarContext( diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift index 44e7e5d13f..b3055aed08 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLabelsTests.swift @@ -109,6 +109,18 @@ struct ToolbarLabelsTests { #expect(record.isApplied) } + /// The labeled toolbar is the one that keeps a content command in place, so the key the visibility is + /// resolved from carries the setting, and a change of it re-resolves the set. + @Test("The visibility key follows the labels setting") + func visibilityKeyFollowsTheLabels() throws { + let storage = try EphemeralDefaults() + let labeled = Self.owner(labelsOn: true, record: ToolbarLabelsRecord(defaults: storage.defaults)) + let plain = Self.owner(labelsOn: false, record: ToolbarLabelsRecord(defaults: storage.defaults)) + + #expect(labeled.currentVisibilityKey().keepsContentCommandsInPlace) + #expect(!plain.currentVisibilityKey().keepsContentCommandsInPlace) + } + @Test("With labels the window title stops drawing, and without them it draws again") func labelsHideTheTitle() { #expect(MainWindowToolbar.titleVisibility(showsLabels: true) == .hidden) From 073da417e8a8ee5bb221879b203ec46d754f7f50 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:06:38 +0700 Subject: [PATCH 100/123] fix(join-builder): draw relation glyphs through ObjectIconProvider The Query Builder's table list drew a grey table glyph for every name, views included, and ignored the Colorful icon style. It now takes each name's kind from the sidebar's list of the scope and draws the glyph and hue ObjectIconProvider gives that kind in the chosen style, a table when the sidebar has not listed it. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../ViewModels/JoinBuilderViewModel.swift | 28 +++++++++++++-- .../Views/JoinBuilder/JoinBuilderSheet.swift | 18 ++++++++-- .../Views/Main/JoinBuilderOpeningTests.swift | 36 +++++++++++++++++++ 3 files changed, 77 insertions(+), 5 deletions(-) diff --git a/apple/TablePro/ViewModels/JoinBuilderViewModel.swift b/apple/TablePro/ViewModels/JoinBuilderViewModel.swift index 5c0963546f..a2eff2e5b7 100644 --- a/apple/TablePro/ViewModels/JoinBuilderViewModel.swift +++ b/apple/TablePro/ViewModels/JoinBuilderViewModel.swift @@ -66,12 +66,32 @@ internal final class JoinBuilderViewModel: ObservableObject { private var columnTypes: [String: [String: ColumnType]] = [:] private var qualifyingSchema: String? + /// What each listed name is, from the sidebar's own list of the scope: the catalog read names tables + /// and views alike, and a view drawn with the table glyph reads as something it can write to. + @Published internal private(set) var relationTypes: [String: TableInfo.TableType] = [:] private let services: AppServices - - internal init(launch: JoinBuilderLaunchRequest, connection: DatabaseConnection, services: AppServices = .live) { + private let listedRelations: @MainActor (DatabaseScope) -> [TableInfo] + + internal init( + launch: JoinBuilderLaunchRequest, + connection: DatabaseConnection, + services: AppServices = .live, + listedRelations: @escaping @MainActor (DatabaseScope) -> [TableInfo] = { scope in + DatabaseTreeMetadataService.shared.tables( + connectionId: scope.connectionId, database: scope.database, schema: scope.schema + ) + } + ) { self.launch = launch self.connection = connection self.services = services + self.listedRelations = listedRelations + } + + /// The glyph the table list draws for `table` in `style`: the sidebar's for its kind, a table when the + /// sidebar has not listed it. + internal func objectIcon(for table: String, style: ObjectIconStyle) -> ObjectIcon { + ObjectIconProvider.icon(for: .relation(relationTypes[table] ?? .table), style: style) } internal var scopeDescription: String { @@ -147,6 +167,10 @@ internal final class JoinBuilderViewModel: ObservableObject { internal func adopt(_ catalog: Catalog, scope: DatabaseScope) { graph = catalog.graph columnTypes = catalog.columnTypes + relationTypes = Dictionary( + listedRelations(scope).map { ($0.name, $0.type) }, + uniquingKeysWith: { first, _ in first } + ) // Picking a schema in the sidebar does not move SQL Server's name resolution, so qualify as browsing does. qualifyingSchema = SchemaQualifiedName.explicitSchema(scope.schema, databaseType: connection.type) var seeded = JoinQueryDraft() diff --git a/apple/TablePro/Views/JoinBuilder/JoinBuilderSheet.swift b/apple/TablePro/Views/JoinBuilder/JoinBuilderSheet.swift index 502e301406..8f275011e5 100644 --- a/apple/TablePro/Views/JoinBuilder/JoinBuilderSheet.swift +++ b/apple/TablePro/Views/JoinBuilder/JoinBuilderSheet.swift @@ -113,6 +113,12 @@ internal struct JoinBuilderSheet: View { private struct JoinBuilderTableList: View { @ObservedObject var model: JoinBuilderViewModel + /// Observed so the glyphs follow the object icon style while the sheet is open. + @ObservedObject private var settings = AppSettingsManager.shared + + init(model: JoinBuilderViewModel) { + self.model = model + } var body: some View { VStack(spacing: 0) { @@ -144,9 +150,15 @@ private struct JoinBuilderTableList: View { get: { model.isIncluded(table) }, set: { model.setIncluded($0, table: table) } )) { - Label(table, systemImage: "tablecells") - .lineLimit(1) - .truncationMode(.middle) + let icon = model.objectIcon(for: table, style: settings.appearance.objectIconStyle) + Label { + Text(table) + .lineLimit(1) + .truncationMode(.middle) + } icon: { + icon.image + .objectIconTint(icon) + } } .toggleStyle(.checkbox) .accessibilityIdentifier("join-builder-table-\(table)") diff --git a/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift b/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift index b815faa15a..5157c5745a 100644 --- a/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift +++ b/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift @@ -89,6 +89,37 @@ struct JoinBuilderOpeningTests { #expect(!model.scopeDescription.contains("/tmp/")) } + /// The catalog read names tables and views alike, so the kind comes from the sidebar's own list. + @Test("The table list draws each relation with its kind's glyph in the chosen icon style") + func tableListFollowsKindAndStyle() { + let connection = TestFixtures.makeConnection(name: "Shop", database: "shop", type: .mysql) + let asked = ScopeRecorder() + let model = JoinBuilderViewModel( + launch: JoinBuilderLaunchRequest(database: "shop", schema: nil, tables: []), + connection: connection, + listedRelations: { scope in + asked.scopes.append(scope) + return [ + TableInfo(name: "orders", type: .table, rowCount: nil), + TableInfo(name: "v_low_stock", type: .view, rowCount: nil), + ] + } + ) + let scope = DatabaseScope(connectionId: connection.id, database: "shop", schema: nil) + + model.adopt(JoinBuilderViewModel.Catalog(graph: .empty, columnTypes: [:]), scope: scope) + + #expect(asked.scopes == [scope]) + let standardView = ObjectIconProvider.icon(for: .relation(.view), style: .standard) + #expect(model.objectIcon(for: "orders", style: .standard) == ObjectIcon(symbolName: "tablecells")) + #expect(model.objectIcon(for: "v_low_stock", style: .standard) == standardView) + #expect(standardView.symbolName != "tablecells", "A view is not drawn as a table") + #expect(model.objectIcon(for: "orders", style: .colorful) == ObjectIconProvider.colorfulIcon(for: .relation(.table))) + #expect(model.objectIcon(for: "v_low_stock", style: .colorful) == ObjectIconProvider.colorfulIcon(for: .relation(.view))) + #expect(model.objectIcon(for: "v_low_stock", style: .colorful).tint != nil) + #expect(model.objectIcon(for: "unlisted", style: .colorful) == ObjectIconProvider.colorfulIcon(for: .relation(.table))) + } + @Test("Only an engine with SQL and foreign keys gets the builder") func eligibility() { let dialect = SQLDialectDescriptor(identifierQuote: "\"", keywords: [], functions: [], dataTypes: []) @@ -99,3 +130,8 @@ struct JoinBuilderOpeningTests { #expect(!JoinBuilderEligibility.supportsJoinBuilder(editorLanguage: .javascript, dialect: dialect, supportsForeignKeys: true)) } } + +@MainActor +private final class ScopeRecorder { + var scopes: [DatabaseScope] = [] +} From aef97d262ce16baee23388deae3b366bd830a956 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:06:38 +0700 Subject: [PATCH 101/123] feat(toolbar): offer to take the connection and database out of the toolbar Settings > General gets "Show connection and database in the toolbar", on by default. Off, the two capsules leave every open connection window's toolbar and its default set, the way the Objects buttons come and go: written once per change of the setting, so Customize Toolbar keeps the last word, and still allowed and built while off, because toolbars sharing the identifier replay each edit by index. On, they go back beside each other after the flexible space that centres them. The switchers find no anchor then and open in the floating panel, so the Database menu keeps working. The Navigator Layout turns the setting off and Standard Layout turns it back on. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainSplitViewController.swift | 1 + .../Infrastructure/MainWindowToolbar.swift | 97 +++++- .../Core/Storage/AppSettingsManager.swift | 3 + .../Models/Settings/GeneralSettings.swift | 9 + .../Settings/NavigatorLayoutPreset.swift | 5 +- .../Views/Settings/GeneralSettingsView.swift | 9 +- .../ToolbarLocationItemsTests.swift | 314 ++++++++++++++++++ .../Models/GeneralSettingsTests.swift | 1 + .../Models/NavigatorLayoutPresetTests.swift | 12 +- .../Settings/SettingsFieldDecodingTests.swift | 16 + 10 files changed, 461 insertions(+), 6 deletions(-) create mode 100644 apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index 3f76a9527f..e4b2c7c98d 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -531,6 +531,7 @@ internal final class MainSplitViewController: NSSplitViewController { window.toolbar = owner.managedToolbar owner.reconcileDebugItems() owner.reconcileObjectKindItems() + owner.reconcileLocationItems() owner.reconcileDisplayMode() /// The item set every window starts from is the full one, because `isHidden` is never /// persisted, so the context is applied the moment the items exist rather than on the first diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index 69f598df00..4c6b5c017e 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -108,6 +108,13 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal var labelsRecord = ToolbarLabelsRecord() + // Whether Settings keeps the connection and database capsules in the toolbar; they leave it while this is off. + internal var locationItemsEnabled: @MainActor () -> Bool = { + AppSettingsManager.shared.general.showsToolbarLocationItems + } + + internal var locationItemsRecord = ToolbarLocationItemsRecord() + /// `NSMenu.delegate` is weak, and the safe-mode control's menu is built here rather than by the /// menu bar, so this toolbar is what keeps its delegate alive. internal let safeModeMenuDelegate = SafeModeMenuDelegate() @@ -466,6 +473,9 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { nonisolated static let objectKindItemIdentifiers: [NSToolbarItem.Identifier] = [ objectTables, objectViews, objectFunctions, objectUsers, objectQuery, objectBackup, ] + // The centred pair a General setting can take out. Still vended and still allowed while it is off: toolbars sharing + // the identifier replay a removal and an insertion by index, and one that refused either would fault on the next. + nonisolated static let locationItemIdentifiers: [NSToolbarItem.Identifier] = [connection, database] // The buttons that name what the front tab shows. Query and Backup start something new, so neither stays selected. nonisolated static let selectableObjectKindItemIdentifiers: [NSToolbarItem.Identifier] = [ objectTables, objectViews, objectFunctions, objectUsers, @@ -554,14 +564,21 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { ] // Ahead of the Actions pull-down, in the content run Refresh and the commit control leave empty on a debug tab. - nonisolated internal static func defaultItems(includingDebugItems: Bool) -> [NSToolbarItem.Identifier] { - let items = defaultItemIdentifiers + // Without the connection and database, the two flexible spaces that centred them stay and split the room evenly. + nonisolated internal static func defaultItems( + includingDebugItems: Bool, + includingLocationItems: Bool = true + ) -> [NSToolbarItem.Identifier] { + var items = defaultItemIdentifiers + if !includingLocationItems { + items.removeAll { locationItemIdentifiers.contains($0) } + } guard includingDebugItems, let index = items.firstIndex(of: actions) else { return items } return Array(items[.. [NSToolbarItem.Identifier] { - Self.defaultItems(includingDebugItems: debugItemsEnabled()) + Self.defaultItems(includingDebugItems: debugItemsEnabled(), includingLocationItems: locationItemsEnabled()) } internal func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { @@ -605,6 +622,17 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } } + // Pushed by the General setting's own write, like the Objects buttons. A window whose context hid the database + // capsule gets it back hidden, so the context is applied again once the pair is in. + internal static func applyLocationItemsSettingChange() { + for window in NSApp.windows { + guard let owner = window.toolbar?.delegate as? MainWindowToolbar else { continue } + owner.reconcileLocationItems() + window.layoutIfNeeded() + owner.refreshContext(forcing: true) + } + } + // Pushed by the General setting's own write, like the Objects buttons. The labels also decide whether a content // command that cannot act hides or dims in place, so the visibility is applied again. internal static func applyToolbarLabelsSettingChange() { @@ -708,6 +736,49 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { } } + // The Objects buttons' rule for the connection and database: written once per change of the setting, so a pair the + // user took out or put back with Customize Toolbar stays as they left it. Each identifier is looked up afresh before + // it is removed or inserted, since AppKit throws on a second item with one the toolbar holds and every toolbar sharing + // the identifier replays the edit at the same index. They come back beside each other, after the flexible space that + // centres them, which is the first one past the sidebar's strip. + internal func reconcileLocationItems() { + guard windowController?.view.window != nil || isInWindow() else { return } + let hidden = !locationItemsEnabled() + guard locationItemsRecord.isApplied != hidden else { return } + locationItemsRecord.record(hidden) + if hidden { + let items = managedToolbar.items.map(\.itemIdentifier) + for index in items.indices.reversed() where Self.locationItemIdentifiers.contains(items[index]) { + managedToolbar.removeItem(at: index) + } + return + } + for identifier in Self.locationItemIdentifiers { + let items = managedToolbar.items.map(\.itemIdentifier) + guard !items.contains(identifier) else { continue } + managedToolbar.insertItem(withItemIdentifier: identifier, at: Self.locationInsertionIndex(for: identifier, in: items)) + } + } + + // Beside its partner when the partner is there, else after the first flexible space past the sidebar's strip, else + // ahead of Refresh, else at the end. + nonisolated internal static func locationInsertionIndex( + for identifier: NSToolbarItem.Identifier, + in items: [NSToolbarItem.Identifier] + ) -> Int { + if identifier == connection, let partner = items.firstIndex(of: database) { + return partner + } + if identifier == database, let partner = items.firstIndex(of: connection) { + return partner + 1 + } + let start = items.firstIndex(of: .sidebarTrackingSeparator).map { $0 + 1 } ?? 0 + if let space = items[start...].firstIndex(of: .flexibleSpace) { + return space + 1 + } + return items.firstIndex(of: refresh) ?? items.count + } + // AppKit draws the toolbar's selected item on a rounded highlight and reports it to VoiceOver as the toolbar's // selected child. AppKit also selects a selectable button when it is clicked, so the front tab decides here, and a // click whose tab did not follow is put right on the next pass. Written only when it moves. @@ -762,6 +833,26 @@ internal struct ToolbarObjectKindsRecord { } } +// Whether the connection and database were last taken out of the shared arrangement, kept for the same reasons as the +// debug items' record. Missing reads as not taken out, which is what every arrangement saved before the setting holds. +internal struct ToolbarLocationItemsRecord { + static let key = "com.TablePro.main.toolbar.v4.locationItemsHidden" + + let defaults: UserDefaults + + init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { + self.defaults = defaults + } + + var isApplied: Bool { + defaults.bool(forKey: Self.key) + } + + func record(_ applied: Bool) { + defaults.set(applied, forKey: Self.key) + } +} + // The Navigator Layout's labels last written into the shared display mode, kept for the same reasons as the debug items' // record: a mode the user picks afterwards from the toolbar's menu outlives the next launch. internal struct ToolbarLabelsRecord { diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 59b513bf1c..60379ebff1 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -27,6 +27,9 @@ final class AppSettingsManager: ObservableObject { if oldValue.showsToolbarLabels != general.showsToolbarLabels { MainWindowToolbar.applyToolbarLabelsSettingChange() } + if oldValue.showsToolbarLocationItems != general.showsToolbarLocationItems { + MainWindowToolbar.applyLocationItemsSettingChange() + } syncTracker.markDirty(.settings, id: AppSettingsCategory.general) } } diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index f9bb295454..06fb0fa61b 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -66,6 +66,9 @@ struct GeneralSettings: Codable, Equatable { var showsObjectToolbar: Bool // Written only by the Layout buttons. The toolbar's own menu is where a person picks labels, so there is no toggle. var showsToolbarLabels: Bool + // The connection and database capsules centred in the toolbar. Off where the tree, the query bar and the tab + // titles already name both. + var showsToolbarLocationItems: Bool var showObjectComments: Bool var showObjectIcons: Bool var showSystemContainers: Bool @@ -87,6 +90,7 @@ struct GeneralSettings: Codable, Equatable { showsObjectsOnSelection: false, showsObjectToolbar: false, showsToolbarLabels: false, + showsToolbarLocationItems: true, showObjectComments: true, showObjectIcons: true, showSystemContainers: false, @@ -109,6 +113,7 @@ struct GeneralSettings: Codable, Equatable { showsObjectsOnSelection: Bool = false, showsObjectToolbar: Bool = false, showsToolbarLabels: Bool = false, + showsToolbarLocationItems: Bool = true, showObjectComments: Bool = true, showObjectIcons: Bool = true, showSystemContainers: Bool = false, @@ -129,6 +134,7 @@ struct GeneralSettings: Codable, Equatable { self.showsObjectsOnSelection = showsObjectsOnSelection self.showsObjectToolbar = showsObjectToolbar self.showsToolbarLabels = showsToolbarLabels + self.showsToolbarLocationItems = showsToolbarLocationItems self.showObjectComments = showObjectComments self.showObjectIcons = showObjectIcons self.showSystemContainers = showSystemContainers @@ -155,6 +161,9 @@ struct GeneralSettings: Codable, Equatable { ) showsObjectToolbar = container.decodeSetting(.showsObjectToolbar, default: fallback.showsObjectToolbar) showsToolbarLabels = container.decodeSetting(.showsToolbarLabels, default: fallback.showsToolbarLabels) + showsToolbarLocationItems = container.decodeSetting( + .showsToolbarLocationItems, default: fallback.showsToolbarLocationItems + ) showObjectComments = container.decodeSetting(.showObjectComments, default: fallback.showObjectComments) showObjectIcons = container.decodeSetting(.showObjectIcons, default: fallback.showObjectIcons) showSystemContainers = container.decodeSetting(.showSystemContainers, default: fallback.showSystemContainers) diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index 2aa3be9a61..eaaea953cb 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -7,7 +7,8 @@ import Foundation /// The Layout buttons in Settings > General: table details, favorite tables at the top of the tree, /// the Objects tab on selection, the Objects toolbar buttons, labels under the toolbar's icons, the -/// saved connections in the tree and Tree as the default sidebar layout, on or off in one step. The +/// toolbar without its connection and database capsules, the saved connections in the tree and Tree +/// as the default sidebar layout, on or off in one step. The /// same buttons switch the table tab's data view and the query bar (`applyDataView`). /// /// The tree lists the saved connections itself, so the layout keeps the separate connections column @@ -23,6 +24,7 @@ internal enum NavigatorLayoutPreset { settings.showsObjectsOnSelection = true settings.showsObjectToolbar = true settings.showsToolbarLabels = true + settings.showsToolbarLocationItems = false settings.showsConnectionsInTree = true settings.showsConnectionNavigator = false defaultLayout = .tree @@ -35,6 +37,7 @@ internal enum NavigatorLayoutPreset { settings.showsObjectsOnSelection = standard.showsObjectsOnSelection settings.showsObjectToolbar = standard.showsObjectToolbar settings.showsToolbarLabels = standard.showsToolbarLabels + settings.showsToolbarLocationItems = standard.showsToolbarLocationItems settings.showsConnectionsInTree = standard.showsConnectionsInTree settings.showsConnectionNavigator = standard.showsConnectionNavigator defaultLayout = .flat diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 87e278de88..72d5d12808 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -81,7 +81,8 @@ struct GeneralSettingsView: View { Text(String(localized: """ Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects \ tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the \ - tree, and makes Tree the default sidebar layout. In table tabs it shows column types in \ + tree, takes the connection and database out of the toolbar, and makes Tree the default \ + sidebar layout. In table tabs it shows column types in \ the header, the sort and a Text mode in the filter panel, opens that panel with each table, \ puts the result bar above the grid and names the database and connection in tab titles. \ In query tabs it shows the query bar on two rows, and object icons turn colorful. \ @@ -114,6 +115,12 @@ struct GeneralSettingsView: View { Toggle("Show object buttons in the toolbar", isOn: $settings.showsObjectToolbar) .help("Adds Tables, Views, Functions, Users, Query and Backup buttons to the connection window's toolbar. Customize Toolbar can move or remove them.") + Toggle("Show connection and database in the toolbar", isOn: $settings.showsToolbarLocationItems) + .help(String(localized: """ + Shows the connection and the database in the middle of the toolbar. Off, the sidebar, the \ + query bar and the tab titles still name them, and the Database menu still switches them. + """)) + 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.") diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift new file mode 100644 index 0000000000..8dc59c43e7 --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift @@ -0,0 +1,314 @@ +// +// ToolbarLocationItemsTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import Testing + +/// The connection and database capsules a General setting takes out of the toolbar, where the tree, +/// the query bar and the tab titles already name both. Written once per change of the setting, like +/// the Objects buttons, so what a person does with Customize Toolbar afterwards stays. +@MainActor +struct ToolbarLocationItemsTests { + private static let connection = MainWindowToolbar.connection + private static let database = MainWindowToolbar.database + + /// The default arrangement without the sidebar's divider, which only a split view window can hold. + private static let defaultArrangement: [NSToolbarItem.Identifier] = [ + .toggleSidebar, .flexibleSpace, connection, database, .flexibleSpace, + MainWindowToolbar.refresh, MainWindowToolbar.actions, + ] + + /// A toolbar restored with `placed`, on an identifier that never autosaves: the test host shares the + /// app's defaults, so a toolbar named like the app's own would carry the edit into the next launch. + private static func restoredToolbar( + _ placed: [NSToolbarItem.Identifier] = defaultArrangement, + identifier: String = "com.TablePro.tests.locationItems.\(UUID().uuidString)", + settingOn: Bool, + record: ToolbarLocationItemsRecord + ) -> MainWindowToolbar { + let toolbar = NSToolbar(identifier: identifier) + toolbar.autosavesConfiguration = false + let owner = MainWindowToolbar(managedToolbar: toolbar) + owner.isInWindow = { true } + owner.locationItemsRecord = record + owner.locationItemsEnabled = { settingOn } + for identifier in placed { + toolbar.insertItem(withItemIdentifier: identifier, at: toolbar.items.count) + } + return owner + } + + private static func identifiers(of owner: MainWindowToolbar) -> [NSToolbarItem.Identifier] { + owner.managedToolbar.items.map { $0.itemIdentifier } + } + + private static func holdsThePair(_ owner: MainWindowToolbar) -> Bool { + let placed = identifiers(of: owner) + return placed.contains(connection) || placed.contains(database) + } + + // MARK: - Off and on + + @Test("Turning the setting off takes the connection and database out, once") + func turningOffRemovesThePairOnce() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLocationItemsRecord(defaults: storage.defaults) + let owner = Self.restoredToolbar(settingOn: false, record: record) + + owner.reconcileLocationItems() + + #expect(!Self.holdsThePair(owner)) + #expect(Self.identifiers(of: owner) == [ + .toggleSidebar, .flexibleSpace, .flexibleSpace, MainWindowToolbar.refresh, MainWindowToolbar.actions, + ]) + #expect(record.isApplied) + + let later = Self.restoredToolbar(settingOn: false, record: record) + later.reconcileLocationItems() + #expect(Self.holdsThePair(later), "The change was already written into the arrangement") + } + + @Test("Turning it back on puts the pair back where it centres, after the first flexible space") + func turningOnRestoresThePair() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLocationItemsRecord(defaults: storage.defaults) + record.record(true) + let owner = Self.restoredToolbar( + [.toggleSidebar, .flexibleSpace, .flexibleSpace, MainWindowToolbar.refresh, MainWindowToolbar.actions], + settingOn: true, + record: record + ) + + owner.reconcileLocationItems() + + #expect(Self.identifiers(of: owner) == Self.defaultArrangement) + #expect(!record.isApplied) + } + + @Test("With the setting on and never turned off, an arrangement is left as it was and nothing is written") + func settingOnLeavesTheArrangementAlone() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLocationItemsRecord(defaults: storage.defaults) + let owner = Self.restoredToolbar([.toggleSidebar, Self.database, .flexibleSpace], settingOn: true, record: record) + let before = Self.identifiers(of: owner) + + owner.reconcileLocationItems() + + #expect(Self.identifiers(of: owner) == before, "A pair the user changed by hand stays as they left it") + #expect(storage.defaults.object(forKey: ToolbarLocationItemsRecord.key) == nil) + } + + /// A customized arrangement may hold one of the pair, or none, and AppKit throws on a second item with + /// an identifier the toolbar already holds. + @Test("Turning it on adds only the missing half, beside the other") + func turningOnAddsOnlyTheMissingHalf() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLocationItemsRecord(defaults: storage.defaults) + record.record(true) + let owner = Self.restoredToolbar( + [.toggleSidebar, .flexibleSpace, Self.database, .flexibleSpace, MainWindowToolbar.refresh], + settingOn: true, + record: record + ) + + owner.reconcileLocationItems() + + #expect(Self.identifiers(of: owner) == [ + .toggleSidebar, .flexibleSpace, Self.connection, Self.database, .flexibleSpace, MainWindowToolbar.refresh, + ]) + } + + @Test("A customized toolbar without either flexible space still takes the pair, ahead of Refresh") + func customizedToolbarTakesThePair() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLocationItemsRecord(defaults: storage.defaults) + let owner = Self.restoredToolbar( + [.toggleSidebar, Self.connection, MainWindowToolbar.history, Self.database, MainWindowToolbar.refresh], + settingOn: false, + record: record + ) + + owner.reconcileLocationItems() + #expect(Self.identifiers(of: owner) == [.toggleSidebar, MainWindowToolbar.history, MainWindowToolbar.refresh]) + + owner.locationItemsEnabled = { true } + owner.reconcileLocationItems() + #expect(Self.identifiers(of: owner) == [ + .toggleSidebar, MainWindowToolbar.history, Self.connection, Self.database, MainWindowToolbar.refresh, + ]) + } + + @Test("Where each half goes back, in every arrangement") + func insertionIndex() { + let index = MainWindowToolbar.locationInsertionIndex + #expect(index(Self.connection, [.toggleSidebar, .flexibleSpace, Self.database]) == 2) + #expect(index(Self.database, [.toggleSidebar, .flexibleSpace, Self.connection, .flexibleSpace]) == 3) + #expect(index(Self.connection, [.toggleSidebar, .sidebarTrackingSeparator, MainWindowToolbar.objectTables, + .flexibleSpace, .flexibleSpace]) == 4) + #expect(index(Self.connection, [.flexibleSpace, .sidebarTrackingSeparator, MainWindowToolbar.refresh]) == 2) + #expect(index(Self.connection, [.toggleSidebar, MainWindowToolbar.actions]) == 2) + } + + @Test("A toolbar outside a window leaves the change for the next one") + func noWindowLeavesTheChangeForTheNextOne() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLocationItemsRecord(defaults: storage.defaults) + let owner = Self.restoredToolbar(settingOn: false, record: record) + owner.isInWindow = { false } + + owner.reconcileLocationItems() + #expect(Self.holdsThePair(owner)) + #expect(!record.isApplied) + } + + // MARK: - What the delegate offers + + /// Toolbars sharing the identifier replay a removal or an insertion by index, so every member has to + /// accept the pair whatever the setting says, and Customize Toolbar can still put it back. + @Test("Off, the default set loses the pair while the delegate still allows and builds it") + func offKeepsThePairAllowed() throws { + let storage = try EphemeralDefaults() + let owner = Self.restoredToolbar([], settingOn: false, record: ToolbarLocationItemsRecord(defaults: storage.defaults)) + let defaults = owner.toolbarDefaultItemIdentifiers(owner.managedToolbar) + let allowed = owner.toolbarAllowedItemIdentifiers(owner.managedToolbar) + + #expect(!defaults.contains(Self.connection)) + #expect(!defaults.contains(Self.database)) + let spaces = { (identifiers: [NSToolbarItem.Identifier]) in identifiers.filter { $0 == .flexibleSpace }.count } + #expect( + spaces(defaults) == spaces(MainWindowToolbar.defaultItemIdentifiers), + "The spaces that centred the pair stay" + ) + #expect(allowed.contains(Self.connection)) + #expect(allowed.contains(Self.database)) + for identifier in [Self.connection, Self.database] { + let built = owner.toolbar(owner.managedToolbar, itemForItemIdentifier: identifier, willBeInsertedIntoToolbar: true) + #expect(built != nil, "\(identifier.rawValue) must still be built") + } + + owner.locationItemsEnabled = { true } + #expect(owner.toolbarDefaultItemIdentifiers(owner.managedToolbar) == MainWindowToolbar.defaultItemIdentifiers) + } + + // MARK: - Toolbars sharing an identifier + + /// Every connection window's toolbar shares one identifier, and AppKit copies an edit made to one into + /// the others by index. Whatever reaches each window first, the arrangements have to stay identical, + /// or a later removal by index faults. + @Test("Two windows sharing a toolbar identifier stay in step through off and on") + func sharedIdentifierStaysInStep() throws { + let storage = try EphemeralDefaults() + let identifier = "com.TablePro.tests.locationItems.family.\(UUID().uuidString)" + let setting = SettingBox() + func make() -> (MainWindowToolbar, NSWindow) { + let owner = Self.restoredToolbar( + identifier: identifier, settingOn: true, record: ToolbarLocationItemsRecord(defaults: storage.defaults) + ) + owner.locationItemsEnabled = { setting.isOn } + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 1_200, height: 400), + styleMask: [.titled], backing: .buffered, defer: false + ) + window.isReleasedWhenClosed = false + window.toolbar = owner.managedToolbar + return (owner, window) + } + let (first, firstWindow) = make() + let (second, secondWindow) = make() + defer { + firstWindow.orderOut(nil) + secondWindow.orderOut(nil) + } + // A toolbar reaching its window takes the delegate's default set, which holds the pair while it is on. + let original = Self.identifiers(of: first) + #expect(Self.holdsThePair(first)) + + setting.isOn = false + for owner in [first, second] { + owner.reconcileLocationItems() + } + #expect(!Self.holdsThePair(first)) + #expect(!Self.holdsThePair(second)) + #expect(Self.identifiers(of: first) == Self.identifiers(of: second)) + + setting.isOn = true + for owner in [second, first] { + owner.reconcileLocationItems() + } + #expect(Self.identifiers(of: first) == original, "The pair is back where it was") + #expect(Self.identifiers(of: second) == Self.identifiers(of: first)) + + first.managedToolbar.removeItem(at: Self.identifiers(of: first).count - 1) + #expect(Self.identifiers(of: second) == Self.identifiers(of: first), "A later edit by index still lands") + } +} + +@MainActor +private final class SettingBox { + var isOn = true +} + +extension GlobalStateSuites { + /// The setting flipped the way Settings flips it, reaching connection windows that are already open. + @MainActor + struct ToolbarLocationItemsSettingTests { + @Test( + "The General setting takes the pair out of every open window and puts it back", + .appSettings { $0.general.showsToolbarLocationItems = true } + ) + func settingReachesEveryOpenWindow() throws { + let windows = try (0 ..< 2).map { _ in try OffscreenConnectionWindow(size: CGSize(width: 1_512, height: 861)) } + defer { windows.forEach { $0.tearDown() } } + var storages: [EphemeralDefaults] = [] + for fixture in windows { + let storage = try EphemeralDefaults() + storages.append(storage) + fixture.toolbarOwner.locationItemsRecord = ToolbarLocationItemsRecord(defaults: storage.defaults) + } + let pair = Set(MainWindowToolbar.locationItemIdentifiers) + func pairs() throws -> [[NSToolbarItem.Identifier]] { + try windows.map { fixture in + try #require(fixture.window.toolbar).items.map { $0.itemIdentifier }.filter { pair.contains($0) } + } + } + #expect(try pairs() == [MainWindowToolbar.locationItemIdentifiers, MainWindowToolbar.locationItemIdentifiers]) + + AppSettingsManager.shared.general.showsToolbarLocationItems = false + #expect(try pairs() == [[], []], "Turning the setting off reaches both open windows") + + AppSettingsManager.shared.general.showsToolbarLocationItems = true + #expect(try pairs() == [MainWindowToolbar.locationItemIdentifiers, MainWindowToolbar.locationItemIdentifiers]) + for fixture in windows { + let identifiers = try #require(fixture.window.toolbar).items.map { $0.itemIdentifier } + let connection = try #require(identifiers.firstIndex(of: MainWindowToolbar.connection)) + #expect(identifiers[connection - 1] == .flexibleSpace, "The pair is centred again") + #expect(identifiers[connection + 2] == .flexibleSpace) + } + withExtendedLifetime(storages) {} + } + + /// The switchers anchor on the capsules when they are in the toolbar and fall back to the floating + /// panel when not, so the Database menu keeps working with the pair taken out. + @Test( + "With the pair out, the switchers find no anchor and take the floating panel", + .appSettings { $0.general.showsToolbarLocationItems = true } + ) + func switchersFallBackWithoutThePair() throws { + let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_512, height: 861)) + defer { fixture.tearDown() } + let storage = try EphemeralDefaults() + fixture.toolbarOwner.locationItemsRecord = ToolbarLocationItemsRecord(defaults: storage.defaults) + let visibility = ToolbarVisibility() + + #expect(ToolbarSwitcherPresenter.anchor(in: fixture.window, MainWindowToolbar.connection, hiddenBy: visibility) != nil) + + AppSettingsManager.shared.general.showsToolbarLocationItems = false + + #expect(ToolbarSwitcherPresenter.anchor(in: fixture.window, MainWindowToolbar.connection, hiddenBy: visibility) == nil) + #expect(ToolbarSwitcherPresenter.anchor(in: fixture.window, MainWindowToolbar.database, hiddenBy: visibility) == nil) + } + } +} diff --git a/apple/TableProTests/Models/GeneralSettingsTests.swift b/apple/TableProTests/Models/GeneralSettingsTests.swift index f6a837acae..80853a8960 100644 --- a/apple/TableProTests/Models/GeneralSettingsTests.swift +++ b/apple/TableProTests/Models/GeneralSettingsTests.swift @@ -68,6 +68,7 @@ struct GeneralSettingsBoolSettingTests { BoolSetting(key: "showsObjectsOnSelection", defaultValue: false), BoolSetting(key: "showsObjectToolbar", defaultValue: false), BoolSetting(key: "showsToolbarLabels", defaultValue: false), + BoolSetting(key: "showsToolbarLocationItems", defaultValue: true), BoolSetting(key: "showObjectComments", defaultValue: true), BoolSetting(key: "showObjectIcons", defaultValue: true), BoolSetting(key: "showSystemContainers", defaultValue: false), diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index 4257b57c11..69b2fe6c18 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -18,12 +18,13 @@ struct NavigatorLayoutPresetTests { expected.showsObjectsOnSelection = true expected.showsObjectToolbar = true expected.showsToolbarLabels = true + expected.showsToolbarLocationItems = false expected.showsConnectionsInTree = true expected.showsConnectionNavigator = false return expected } - @Test("Use Navigator Layout turns on all six features and makes Tree the default layout") + @Test("Use Navigator Layout turns on all six features, takes the location out of the toolbar and makes Tree the default layout") func applyTurnsEverythingOn() { var settings = GeneralSettings.default var layout = SidebarLayout.flat @@ -35,6 +36,7 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsObjectsOnSelection) #expect(settings.showsObjectToolbar) #expect(settings.showsToolbarLabels) + #expect(!settings.showsToolbarLocationItems, "The tree, the query bar and the tab titles name both") #expect(settings.showsConnectionsInTree) #expect(layout == .tree) } @@ -66,6 +68,7 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsObjectsOnSelection == GeneralSettings.default.showsObjectsOnSelection) #expect(settings.showsObjectToolbar == GeneralSettings.default.showsObjectToolbar) #expect(!settings.showsToolbarLabels, "Standard Layout is icons only") + #expect(settings.showsToolbarLocationItems, "Standard Layout puts the connection and database back") #expect(settings.showsConnectionsInTree == GeneralSettings.default.showsConnectionsInTree) #expect(settings.showsConnectionNavigator == GeneralSettings.default.showsConnectionNavigator) #expect(settings == GeneralSettings.default) @@ -203,6 +206,7 @@ extension GlobalStateSuites { $0.general.showsObjectsOnSelection = false $0.general.showsObjectToolbar = false $0.general.showsToolbarLabels = false + $0.general.showsToolbarLocationItems = true $0.general.showsConnectionNavigator = false $0.general.showsConnectionsInTree = false } @@ -213,7 +217,11 @@ extension GlobalStateSuites { let storage = try EphemeralDefaults() fixture.toolbarOwner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) fixture.toolbarOwner.labelsRecord = ToolbarLabelsRecord(defaults: storage.defaults) + fixture.toolbarOwner.locationItemsRecord = ToolbarLocationItemsRecord(defaults: storage.defaults) let toolbar = try #require(fixture.window.toolbar) + let location = Set(MainWindowToolbar.locationItemIdentifiers) + let hasLocation = { toolbar.items.contains { location.contains($0.itemIdentifier) } } + #expect(hasLocation()) #expect(toolbar.displayMode == .iconOnly) let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) let hasButtons = { toolbar.items.contains { objectKinds.contains($0.itemIdentifier) } } @@ -226,12 +234,14 @@ extension GlobalStateSuites { #expect(hasButtons(), "The Objects buttons reach the open window") #expect(toolbar.displayMode == .iconAndLabel, "Labels go under the toolbar's icons") + #expect(!hasLocation(), "The connection and database leave the open window's toolbar") #expect(railChanges == 1, "The connections column is told the tree now lists the connections") NavigatorLayoutPreset.restore(to: &AppSettingsManager.shared.general, defaultLayout: &layout) #expect(!hasButtons(), "The Objects buttons leave the open window") #expect(toolbar.displayMode == .iconOnly, "Standard Layout puts the icons back alone") + #expect(hasLocation(), "Standard Layout puts the connection and database back") #expect(railChanges == 2, "The connections column is told the tree stops listing them") } } diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index 4669f7c10f..eb35b1797a 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -31,6 +31,22 @@ struct SettingsFieldDecodingTests { #expect(settings.queryTimeoutSeconds == 120) } + @Test("General settings saved before the toolbar's location setting keep the connection and database in it") + func toolbarLocationItemsDefaultOn() throws { + let legacy = try decode(GeneralSettings.self, #"{"showsObjectToolbar":true,"showsToolbarLabels":true}"#) + #expect(legacy.showsToolbarLocationItems == true) + #expect(legacy.showsObjectToolbar == true) + #expect(GeneralSettings.default.showsToolbarLocationItems == true) + + let bad = try decode(GeneralSettings.self, #"{"showsToolbarLocationItems":"no","showsToolbarLabels":true}"#) + #expect(bad.showsToolbarLocationItems == true) + #expect(bad.showsToolbarLabels == true) + + let chosen = GeneralSettings(showsToolbarLocationItems: false) + let decoded = try decode(GeneralSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.showsToolbarLocationItems == false) + } + @Test("A bad Editor value falls back alone") func editorKeepsOtherFields() throws { let settings = try decode( From 6292ac0e147e5b44e0a97fcc63a14a4b1f2f2e44 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 13:09:09 +0700 Subject: [PATCH 102/123] chore(l10n): add the toolbar location and query bar strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Resources/Localizable.xcstrings | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 1797ebdd45..1fc1b4e6f2 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -113804,6 +113804,9 @@ }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, takes the connection and database out of the toolbar, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter panel, opens that panel with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { @@ -165806,6 +165809,9 @@ } } } + }, + "Show connection and database in the toolbar" : { + }, "Show connections" : { "comment" : "A checkbox that toggles whether the sidebar shows a list of open connections.", @@ -167920,6 +167926,9 @@ } } } + }, + "Shows the connection and the database in the middle of the toolbar. Off, the sidebar, the query bar and the tab titles still name them, and the Database menu still switches them." : { + }, "Shows the version and Check for Updates under the app icon. An available update is shown either way." : { "localizations" : { From 17e420e181c93da7fa0e743b52c94f3376dd960e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 14:02:21 +0700 Subject: [PATCH 103/123] fix(toolbar): skip an arrangement edit while the toolbar family is out of step The full Unit plan crashed the host in ObjectKindsSettingTests. AppKit copies every insertion and removal of a toolbar into each other toolbar of its identifier at the same index, and raises "_itemAtIndex: index >= 0 && index < count" when one holds fewer items. The unit host keeps windows from earlier tests that still carry the connection window's toolbar after its owner went ("Rail width" and other hosts that set the content to nil): with no delegate they build nothing for those copies and hold only the two items AppKit draws. A settings flip then edited a live connection window's toolbar past them, the connection and database at index 6 and 7 first, and the raise went up through the setting's write and the test, leaving the host to die later in currentVisibilityKey(). The Objects buttons are inserted at index 2, inside those items, which is why nothing tripped it before the location items existed. The debug items, the Objects buttons and the location items now edit the arrangement only while every open window's toolbar of the identifier holds the same items as this one. Out of step, the change is logged and not recorded, so the next reconcile makes it once the family is back in step. Taking the orphaned toolbars off in the tests' teardown instead over-released the toolbar in the Agent mode window tests, so the guard lives where the edit is made. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Infrastructure/MainWindowToolbar.swift | 29 +++++++++++++++++-- .../ObjectKindsToolbarTests.swift | 25 ++++++++++++++++ .../ToolbarLocationItemsTests.swift | 23 +++++++++++++++ 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index 4c6b5c017e..070fab0886 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -601,6 +601,29 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { // Replaced under test, where no window hosts the toolbar. internal var isInWindow: @MainActor () -> Bool = { false } + // The arrangement of every open window's toolbar that carries `identifier`, this one's included. Replaced under test. + internal var familyArrangements: @MainActor (NSToolbar.Identifier) -> [[NSToolbarItem.Identifier]] = { identifier in + NSApp.windows.compactMap(\.toolbar) + .filter { $0.identifier == identifier } + .map { toolbar in toolbar.items.map(\.itemIdentifier) } + } + + /// Whether an insertion or a removal can be made now. AppKit copies each one into every other toolbar of this + /// identifier at the same index, and raises `_itemAtIndex` when one of them holds fewer items. A toolbar whose + /// owner went while it stayed on its window builds nothing for those copies and falls out of step, which the + /// unit host's window tests leave behind: the raise went up through the setting's write and took the process + /// down. Out of step, the change is not recorded, so the next reconcile, with the family back in step, makes it. + internal func familyIsInStep() -> Bool { + let own = managedToolbar.items.map(\.itemIdentifier) + let inStep = familyArrangements(managedToolbar.identifier).allSatisfy { $0 == own } + if !inStep { + Self.lifecycleLogger.error( + "toolbar arrangement edit skipped: another toolbar of \(self.managedToolbar.identifier, privacy: .public) is out of step" + ) + } + return inStep + } + // Pushed by the one writer of a module's state, so no toolbar listens for module changes while the module is off. internal static func applyModuleChange() { for window in NSApp.windows { @@ -685,7 +708,7 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal func reconcileDebugItems() { guard windowController?.view.window != nil || isInWindow() else { return } let wanted = debugItemsEnabled() - guard debugItemsRecord.isApplied != wanted else { return } + guard debugItemsRecord.isApplied != wanted, familyIsInStep() else { return } debugItemsRecord.record(wanted) let debugIdentifiers = Set(Self.debugItemIdentifiers) if wanted { @@ -708,7 +731,7 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal func reconcileObjectKindItems() { guard windowController?.view.window != nil || isInWindow() else { return } let wanted = objectKindsEnabled() - guard objectKindsRecord.isApplied != wanted else { return } + guard objectKindsRecord.isApplied != wanted, familyIsInStep() else { return } objectKindsRecord.record(wanted) let objectKinds = Set(Self.objectKindItemIdentifiers) if wanted { @@ -744,7 +767,7 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { internal func reconcileLocationItems() { guard windowController?.view.window != nil || isInWindow() else { return } let hidden = !locationItemsEnabled() - guard locationItemsRecord.isApplied != hidden else { return } + guard locationItemsRecord.isApplied != hidden, familyIsInStep() else { return } locationItemsRecord.record(hidden) if hidden { let items = managedToolbar.items.map(\.itemIdentifier) diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift index 038c7fdb6f..683bc59c74 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarTests.swift @@ -802,6 +802,31 @@ struct ObjectKindsToolbarTests { #expect(toolbar.selectedItemIdentifier == MainWindowToolbar.objectTables) } + /// Removing the buttons from a toolbar whose family held one toolbar left without its owner raised + /// `_itemAtIndex` in AppKit's copy of the removal and took the unit host down. + @Test("The buttons wait while another toolbar of the identifier is out of step") + func outOfStepFamilyDefersTheButtons() throws { + let storage = try EphemeralDefaults() + let record = ToolbarObjectKindsRecord(defaults: storage.defaults) + record.record(true) + let (owner, toolbar) = Self.restoredToolbar( + including: MainWindowToolbar.objectKindItemIdentifiers, + settingOn: false, + record: record + ) + let before = Self.identifiers(of: toolbar) + owner.familyArrangements = { _ in [before, [.toggleSidebar]] } + + owner.reconcileObjectKindItems() + #expect(Self.identifiers(of: toolbar) == before) + #expect(record.isApplied, "Still recorded as in, so the next reconcile takes them out") + + owner.familyArrangements = { _ in [] } + owner.reconcileObjectKindItems() + #expect(Self.buttons(in: toolbar).isEmpty) + #expect(!record.isApplied) + } + /// A change made while no connection window is open is left for the first window that opens, /// which restores its arrangement before it reconciles. @Test("A toolbar outside a window leaves the change for the next one") diff --git a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift index 8dc59c43e7..5c91c91e95 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ToolbarLocationItemsTests.swift @@ -152,6 +152,29 @@ struct ToolbarLocationItemsTests { #expect(index(Self.connection, [.toggleSidebar, MainWindowToolbar.actions]) == 2) } + /// A toolbar left on its window after its owner went holds only the items AppKit draws itself. AppKit copies a + /// removal into it at the same index and raises when it holds fewer items, which took the unit host down from + /// inside a setting's write. + @Test("The change waits while another toolbar of the identifier is out of step, and lands once it is back") + func outOfStepFamilyDefersTheChange() throws { + let storage = try EphemeralDefaults() + let record = ToolbarLocationItemsRecord(defaults: storage.defaults) + let owner = Self.restoredToolbar(settingOn: false, record: record) + let before = Self.identifiers(of: owner) + owner.familyArrangements = { _ in [before, [.toggleSidebar, .sidebarTrackingSeparator]] } + + #expect(!owner.familyIsInStep()) + owner.reconcileLocationItems() + #expect(Self.identifiers(of: owner) == before, "No edit AppKit would copy into the short toolbar") + #expect(!record.isApplied, "Nothing is recorded, so the next reconcile makes the change") + + owner.familyArrangements = { _ in [before] } + #expect(owner.familyIsInStep()) + owner.reconcileLocationItems() + #expect(!Self.holdsThePair(owner)) + #expect(record.isApplied) + } + @Test("A toolbar outside a window leaves the change for the next one") func noWindowLeavesTheChangeForTheNextOne() throws { let storage = try EphemeralDefaults() From 80089078632a17fede803e1c5f940b62819ec98f Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 14:21:05 +0700 Subject: [PATCH 104/123] feat(appearance): draw the remaining sidebar rows and Objects buttons in the icon style The colorful object icons now reach the sidebar's Recent, Temporary, Favorites and Folders section rows, the columns, indexes, keys and checks listed under an expanded table with their groups, and the toolbar's Objects buttons. ObjectIconProvider gains a kind for each, and its standard glyphs are the ones those rows drew before, so the standard style draws exactly what it did. The Objects buttons keep their own glyph and hue in the standard style and draw the sidebar's kind in the colorful one; Backup opens no kind of object and keeps its own. The Appearance setting's write pushes the new glyph to every open toolbar, overflowed buttons included. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../MainWindowToolbar+Items.swift | 54 +++++++-- .../Infrastructure/StatefulToolbarItem.swift | 3 +- .../Core/Storage/AppSettingsManager.swift | 1 + apple/TablePro/Models/UI/ObjectIcon.swift | 56 ++++++++- .../Views/Sidebar/DatabaseTreeRowView.swift | 8 +- .../Views/Sidebar/TableDetailRowView.swift | 27 ++--- .../ObjectKindsToolbarIconStyleTests.swift | 107 ++++++++++++++++++ .../Models/ObjectIconProviderTests.swift | 59 +++++++++- 8 files changed, 285 insertions(+), 30 deletions(-) create mode 100644 apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarIconStyleTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift index 2f32569dde..195c3ef972 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar+Items.swift @@ -363,6 +363,7 @@ extension MainWindowToolbar { label: String(localized: "Tables"), symbol: SidebarObjectKind.table.iconName, tint: .systemBlue, + iconKind: ObjectIconKind(.table), action: #selector(MainWindowToolbar.performShowTables(_:)) ), ObjectKindButton( @@ -370,6 +371,7 @@ extension MainWindowToolbar { label: String(localized: "Views"), symbol: SidebarObjectKind.view.iconName, tint: .systemTeal, + iconKind: ObjectIconKind(.view), action: #selector(MainWindowToolbar.performShowViews(_:)) ), ObjectKindButton( @@ -377,6 +379,7 @@ extension MainWindowToolbar { label: String(localized: "Functions"), symbol: SidebarObjectKind.function.iconName, tint: .systemPurple, + iconKind: ObjectIconKind(.function), action: #selector(MainWindowToolbar.performShowFunctions(_:)) ), ObjectKindButton( @@ -384,6 +387,7 @@ extension MainWindowToolbar { label: String(localized: "Users"), symbol: "person.2", tint: .systemOrange, + iconKind: .user, action: #selector(MainWindowToolbar.performShowUsers(_:)) ), ObjectKindButton( @@ -391,6 +395,7 @@ extension MainWindowToolbar { label: String(localized: "Query"), symbol: "doc.text", tint: .systemGreen, + iconKind: .query, action: #selector(MainWindowToolbar.performNewQuery(_:)), shortcut: .newTab ), @@ -405,8 +410,35 @@ extension MainWindowToolbar { } /// The hue a button draws its glyph in, and nil for every item outside the Objects run, which stays a template. - static func objectKindTint(for identifier: NSToolbarItem.Identifier) -> NSColor? { - objectKindButtons.first { $0.identifier == identifier }?.tint + static func objectKindTint( + for identifier: NSToolbarItem.Identifier, + style: ObjectIconStyle = AppSettingsManager.shared.appearance.objectIconStyle + ) -> NSColor? { + objectKindButtons.first { $0.identifier == identifier }.map { objectKindIcon($0, style: style).tint } + } + + /// The glyph and hue a button draws in an icon style. The standard style keeps the button's own pair, which is what + /// the run drew before the style existed; the colorful one draws the kind as the sidebar does. Backup opens no kind + /// of object, so it keeps its own pair in both. + static func objectKindIcon(_ button: ObjectKindButton, style: ObjectIconStyle) -> (symbolName: String, tint: NSColor) { + guard let kind = button.iconKind else { return (button.symbol, button.tint) } + let icon = ObjectIconProvider.icon(for: kind, style: style, standard: button.symbol) + return (icon.symbolName, icon.tint?.nsColor ?? button.tint) + } + + /// Pushed by the Appearance setting's own write, as the General settings push theirs. A validation pass redraws only + /// the buttons placed in the bar, so each one, the overflowed included, takes its new glyph here. + internal static func applyObjectIconStyleChange() { + for window in NSApp.windows { + (window.toolbar?.delegate as? MainWindowToolbar)?.refreshObjectKindGlyphs() + } + } + + internal func refreshObjectKindGlyphs() { + let objectKinds = Set(Self.objectKindItemIdentifiers) + for item in managedToolbar.items where objectKinds.contains(item.itemIdentifier) { + (item as? StatefulToolbarItem)?.refreshGlyph() + } } /// Built like every other command, so each button keeps its own action, tooltip and overflow entry and AppKit dims @@ -426,11 +458,16 @@ extension MainWindowToolbar { } /// A system hue per kind, so the run reads at a glance. The color resolves when the glyph draws, in the toolbar's own - /// appearance, so it follows light and dark; an inactive window greys it as it greys every glyph. - static func objectKindGlyph(_ button: ObjectKindButton) -> ToolbarGlyph { - ToolbarGlyph(key: button.symbol) { - let image = NSImage(systemSymbolName: button.symbol, accessibilityDescription: button.label)? - .withSymbolConfiguration(NSImage.SymbolConfiguration(hierarchicalColor: button.tint)) + /// appearance, so it follows light and dark; an inactive window greys it as it greys every glyph. The style is read + /// on every pass and names the glyph's key, so a pass after the setting changes draws the new one. + static func objectKindGlyph( + _ button: ObjectKindButton, + style: ObjectIconStyle = AppSettingsManager.shared.appearance.objectIconStyle + ) -> ToolbarGlyph { + let icon = objectKindIcon(button, style: style) + return ToolbarGlyph(key: style.rawValue + "/" + icon.symbolName) { + let image = NSImage(systemSymbolName: icon.symbolName, accessibilityDescription: button.label)? + .withSymbolConfiguration(NSImage.SymbolConfiguration(hierarchicalColor: icon.tint)) image?.isTemplate = false return image } @@ -556,8 +593,11 @@ extension MainWindowToolbar { internal struct ObjectKindButton { let identifier: NSToolbarItem.Identifier let label: String + /// The glyph and hue the standard icon style draws. let symbol: String let tint: NSColor + /// What the button opens, which decides its glyph and hue in the colorful style. Nil for Backup, which opens none. + var iconKind: ObjectIconKind? let action: Selector var shortcut: ShortcutAction? } diff --git a/apple/TablePro/Core/Services/Infrastructure/StatefulToolbarItem.swift b/apple/TablePro/Core/Services/Infrastructure/StatefulToolbarItem.swift index b1099cac85..14f2a4fae6 100644 --- a/apple/TablePro/Core/Services/Infrastructure/StatefulToolbarItem.swift +++ b/apple/TablePro/Core/Services/Infrastructure/StatefulToolbarItem.swift @@ -71,7 +71,8 @@ internal final class StatefulToolbarItem: NSToolbarItem { } private var symbolSource = ToolbarSymbolSource() - private var appliedGlyphKey: String? + /// What the glyph on show depicts, as its provider named it. + internal private(set) var appliedGlyphKey: String? override internal func validate() { super.validate() diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 60379ebff1..c39c9d6e31 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -43,6 +43,7 @@ final class AppSettingsManager: ObservableObject { ) if oldValue.objectIconStyle != appearance.objectIconStyle { appEvents.objectIconStyleChanged.send(appearance.objectIconStyle) + MainWindowToolbar.applyObjectIconStyleChange() } syncTracker.markDirty(.settings, id: AppSettingsCategory.appearance) } diff --git a/apple/TablePro/Models/UI/ObjectIcon.swift b/apple/TablePro/Models/UI/ObjectIcon.swift index 0fcb99aa37..329d46730e 100644 --- a/apple/TablePro/Models/UI/ObjectIcon.swift +++ b/apple/TablePro/Models/UI/ObjectIcon.swift @@ -6,7 +6,7 @@ import Foundation /// What an object glyph stands for, on every surface that draws one: the sidebar, the editor tabs, -/// the Objects list, the quick switcher and the recent tab switcher. +/// the Objects list, the quick switcher, the recent tab switcher and the toolbar's Objects buttons. internal enum ObjectIconKind: Hashable, Sendable { case database case systemDatabase @@ -23,6 +23,18 @@ internal enum ObjectIconKind: Hashable, Sendable { case query case savedQuery case user + /// The sidebar sections that list tables by how the reader came to them rather than by kind. + case recentSection + case temporarySection + case favoritesSection + /// What an expanded table lists under it: its columns, its indexes and its constraints, and the + /// group that holds each kind. A primary key's column and its index share one glyph. + case column + case primaryKey + case index + case foreignKey + case checkConstraint + case tableDetailGroup(TableDetailGroupKind) /// The kind a section, an Objects tab or a menu of one kind of object stands for. internal init(_ kind: SidebarObjectKind) { @@ -50,6 +62,15 @@ internal enum ObjectIconKind: Hashable, Sendable { } } + internal init(_ item: TableDetailItem) { + switch item { + case .column(let column): self = column.isPrimaryKey ? .primaryKey : .column + case .index(let index): self = index.isPrimary ? .primaryKey : .index + case .foreignKey: self = .foreignKey + case .check: self = .checkConstraint + } + } + /// The object a tab shows, or nil for a tool tab that shows none, such as the ER diagram. internal init?(tab: QueryTab) { switch tab.tabType { @@ -136,6 +157,16 @@ internal enum ObjectIconProvider { case .query: return "doc.text" case .savedQuery: return "star" case .user: return "person.2" + case .recentSection: return "clock" + case .temporarySection: return "hourglass" + case .favoritesSection: return "star" + case .column: return "rectangle.portrait" + case .primaryKey: return "key" + case .index: return "list.bullet" + case .foreignKey: return "link" + case .checkConstraint: return "checkmark.shield" + case .tableDetailGroup(.columns): return "tablecells" + case .tableDetailGroup(let group): return standardSymbolName(for: Self.detailKind(of: group)) } } @@ -157,6 +188,29 @@ internal enum ObjectIconProvider { case .tableFolder: return ObjectIcon(symbolName: "folder.fill", tint: .blue) case .query, .savedQuery: return ObjectIcon(symbolName: "doc.text.fill", tint: .orange) case .user: return ObjectIcon(symbolName: "person.fill", tint: .brown) + case .recentSection: return ObjectIcon(symbolName: "clock.fill", tint: .indigo) + case .temporarySection: return ObjectIcon(symbolName: "hourglass.bottomhalf.filled", tint: .orange) + case .favoritesSection: return ObjectIcon(symbolName: "star.fill", tint: .yellow) + case .column: return ObjectIcon(symbolName: "rectangle.portrait.fill", tint: .teal) + case .primaryKey: return ObjectIcon(symbolName: "key.fill", tint: .yellow) + case .index: return ObjectIcon(symbolName: "list.bullet.rectangle.fill", tint: .mint) + case .foreignKey: return ObjectIcon(symbolName: "link.circle.fill", tint: .indigo) + case .checkConstraint: return ObjectIcon(symbolName: "checkmark.shield.fill", tint: .green) + // A group under a table is drawn like a section: a folder in the hue of what it holds. + case .tableDetailGroup(let group): + return ObjectIcon(symbolName: "folder.fill", tint: colorfulIcon(for: Self.detailKind(of: group)).tint) + } + } + + /// The kind of row a detail group under a table holds. + private static func detailKind(of group: TableDetailGroupKind) -> ObjectIconKind { + switch group { + case .columns: return .column + case .indexes: return .index + case .foreignKeys: return .foreignKey + case .checks: return .checkConstraint + case .triggers: return .trigger + case .partitions: return .partition } } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift index 8782243c4c..8f7ddf89bf 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift @@ -99,13 +99,13 @@ struct DatabaseTreeRowView: View { case .savedConnection(let ref): ConnectionNavigatorConnectionLabel(row: ref.row, glyphSide: context.rowSize.iconPointSize) case .recentSection: - sectionHeader(String(localized: "Recent"), icon: ObjectIcon(symbolName: "clock")) + sectionHeader(String(localized: "Recent"), icon: objectIcon(.recentSection)) case .recentTable(let ref), .favoriteTable(let ref): tableRow(ref) case .favoritesSection: - sectionHeader(String(localized: "Favorites"), icon: ObjectIcon(symbolName: "star")) + sectionHeader(String(localized: "Favorites"), icon: objectIcon(.favoritesSection)) case .temporarySection: - sectionHeader(String(localized: "Temporary"), icon: ObjectIcon(symbolName: "hourglass")) + sectionHeader(String(localized: "Temporary"), icon: objectIcon(.temporarySection)) case .temporaryTable(let ref): TableRow( table: ref.table, @@ -115,7 +115,7 @@ struct DatabaseTreeRowView: View { accessibilityKind: String(localized: "Temporary Table") ) case .foldersSection: - sectionHeader(String(localized: "Folders"), icon: ObjectIcon(symbolName: "folder")) + sectionHeader(String(localized: "Folders"), icon: objectIcon(.tableFolder)) case .tableFolder(let ref): folderRow(ref) case .database(let metadata): diff --git a/apple/TablePro/Views/Sidebar/TableDetailRowView.swift b/apple/TablePro/Views/Sidebar/TableDetailRowView.swift index fdc16311c1..079a746198 100644 --- a/apple/TablePro/Views/Sidebar/TableDetailRowView.swift +++ b/apple/TablePro/Views/Sidebar/TableDetailRowView.swift @@ -20,24 +20,13 @@ internal enum TableDetailRowLogic { } } + /// The standard style's glyph, which `ObjectIconProvider` owns with every other object's. static func iconName(for kind: TableDetailGroupKind) -> String { - switch kind { - case .columns: "tablecells" - case .indexes: "list.bullet" - case .foreignKeys: "link" - case .checks: "checkmark.shield" - case .triggers: SidebarObjectKind.trigger.iconName - case .partitions: SidebarPartitionRow.iconName - } + ObjectIconProvider.standardSymbolName(for: .tableDetailGroup(kind)) } static func iconName(for item: TableDetailItem) -> String { - switch item { - case .column(let column): column.isPrimaryKey ? "key" : "rectangle.portrait" - case .index(let index): index.isPrimary ? "key" : iconName(for: .indexes) - case .foreignKey: iconName(for: .foreignKeys) - case .check: iconName(for: .checks) - } + ObjectIconProvider.standardSymbolName(for: ObjectIconKind(item)) } static func caption(for item: TableDetailItem) -> String? { @@ -105,7 +94,11 @@ struct TableDetailGroupRowView: View { } } } icon: { - Image(systemName: TableDetailRowLogic.iconName(for: kind)) + let icon = ObjectIconProvider.icon( + for: .tableDetailGroup(kind), + style: settingsManager.appearance.objectIconStyle + ) + icon.image.objectIconTint(icon) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) .accessibilityElement(children: .combine) @@ -136,7 +129,9 @@ struct TableDetailRowView: View { } } } icon: { - Image(systemName: TableDetailRowLogic.iconName(for: item)) + let icon = ObjectIconProvider.icon(for: ObjectIconKind(item), style: settingsManager.appearance.objectIconStyle) + icon.image + .objectIconTint(icon) .frame(width: 16) } .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) diff --git a/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarIconStyleTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarIconStyleTests.swift new file mode 100644 index 0000000000..880133dae3 --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/ObjectKindsToolbarIconStyleTests.swift @@ -0,0 +1,107 @@ +// +// ObjectKindsToolbarIconStyleTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import Testing + +extension GlobalStateSuites { + /// The Objects buttons under Settings > Appearance > Object Icons. The standard style is the run as it was drawn + /// before the setting existed; the colorful one draws each kind the way the sidebar does. + @Suite(.appSettings { $0.appearance.objectIconStyle = .standard }) + @MainActor + struct ObjectKindsToolbarIconStyleTests { + private typealias Drawn = (identifier: NSToolbarItem.Identifier, symbolName: String, tint: NSColor) + + private static let standardRun: [Drawn] = [ + (MainWindowToolbar.objectTables, "tablecells", .systemBlue), + (MainWindowToolbar.objectViews, "eye", .systemTeal), + (MainWindowToolbar.objectFunctions, "function", .systemPurple), + (MainWindowToolbar.objectUsers, "person.2", .systemOrange), + (MainWindowToolbar.objectQuery, "doc.text", .systemGreen), + (MainWindowToolbar.objectBackup, "archivebox", .systemBrown), + ] + + private static let colorfulRun: [Drawn] = [ + (MainWindowToolbar.objectTables, "tablecells.fill", .systemBlue), + (MainWindowToolbar.objectViews, "eyeglasses", .systemCyan), + (MainWindowToolbar.objectFunctions, "function", .systemPurple), + (MainWindowToolbar.objectUsers, "person.fill", .systemBrown), + (MainWindowToolbar.objectQuery, "doc.text.fill", .systemOrange), + (MainWindowToolbar.objectBackup, "archivebox", .systemBrown), + ] + + private static func button(_ identifier: NSToolbarItem.Identifier) throws -> ObjectKindButton { + try #require(MainWindowToolbar.objectKindButtons.first { $0.identifier == identifier }) + } + + private static func expectRun(_ run: [Drawn], style: ObjectIconStyle) throws { + #expect(run.map { $0.identifier } == MainWindowToolbar.objectKindItemIdentifiers) + for drawn in run { + let icon = MainWindowToolbar.objectKindIcon(try button(drawn.identifier), style: style) + let name = drawn.identifier.rawValue + #expect(icon.symbolName == drawn.symbolName, "\(name)") + #expect(icon.tint == drawn.tint, "\(name)") + #expect(MainWindowToolbar.objectKindTint(for: drawn.identifier, style: style) == drawn.tint, "\(name)") + } + } + + @Test("The standard style draws each button's glyph and hue from before the style existed") + func standardStyleKeepsTheRun() throws { + try Self.expectRun(Self.standardRun, style: .standard) + for drawn in Self.standardRun { + #expect(MainWindowToolbar.objectKindTint(for: drawn.identifier) == drawn.tint, "The setting starts standard") + } + } + + @Test("The colorful style draws each kind as the sidebar does, and Backup, which opens no kind, as it was") + func colorfulStyleDrawsTheKinds() throws { + try Self.expectRun(Self.colorfulRun, style: .colorful) + let tables = try Self.button(MainWindowToolbar.objectTables) + let sidebar = ObjectIconProvider.icon(for: .relation(.table), style: .colorful) + #expect(MainWindowToolbar.objectKindIcon(tables, style: .colorful).symbolName == sidebar.symbolName) + } + + @Test("Every glyph either style draws is a symbol the system has") + func everyGlyphExists() { + for button in MainWindowToolbar.objectKindButtons { + for style in ObjectIconStyle.allCases { + let glyph = MainWindowToolbar.objectKindGlyph(button, style: style) + #expect(glyph.image() != nil, "\(button.identifier.rawValue) in \(style.rawValue)") + } + } + } + + @Test( + "An open window's buttons take the new style the moment the setting changes", + .appSettings { $0.general.showsObjectToolbar = false } + ) + func settingReachesAnOpenWindow() throws { + let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_512, height: 861)) + defer { fixture.tearDown() } + let storage = try EphemeralDefaults() + fixture.toolbarOwner.objectKindsRecord = ToolbarObjectKindsRecord(defaults: storage.defaults) + AppSettingsManager.shared.general.showsObjectToolbar = true + let toolbar = try #require(fixture.window.toolbar) + let objectKinds = Set(MainWindowToolbar.objectKindItemIdentifiers) + let keys = { + Dictionary(uniqueKeysWithValues: toolbar.items.filter { objectKinds.contains($0.itemIdentifier) }.map { + ($0.itemIdentifier, ($0 as? StatefulToolbarItem)?.appliedGlyphKey) + }) + } + #expect(keys().count == objectKinds.count) + #expect(keys()[MainWindowToolbar.objectTables] == "standard/tablecells") + + AppSettingsManager.shared.appearance.objectIconStyle = .colorful + #expect(keys()[MainWindowToolbar.objectTables] == "colorful/tablecells.fill") + #expect(keys()[MainWindowToolbar.objectViews] == "colorful/eyeglasses") + #expect(keys()[MainWindowToolbar.objectBackup] == "colorful/archivebox") + + AppSettingsManager.shared.appearance.objectIconStyle = .standard + #expect(keys()[MainWindowToolbar.objectTables] == "standard/tablecells") + #expect(keys()[MainWindowToolbar.objectViews] == "standard/eye") + } + } +} diff --git a/apple/TableProTests/Models/ObjectIconProviderTests.swift b/apple/TableProTests/Models/ObjectIconProviderTests.swift index fa5cd473c3..ad70ec80f2 100644 --- a/apple/TableProTests/Models/ObjectIconProviderTests.swift +++ b/apple/TableProTests/Models/ObjectIconProviderTests.swift @@ -50,6 +50,20 @@ struct ObjectIconProviderTests { (.query, "doc.text"), (.savedQuery, "star"), (.user, "person.2"), + (.recentSection, "clock"), + (.temporarySection, "hourglass"), + (.favoritesSection, "star"), + (.column, "rectangle.portrait"), + (.primaryKey, "key"), + (.index, "list.bullet"), + (.foreignKey, "link"), + (.checkConstraint, "checkmark.shield"), + (.tableDetailGroup(.columns), "tablecells"), + (.tableDetailGroup(.indexes), "list.bullet"), + (.tableDetailGroup(.foreignKeys), "link"), + (.tableDetailGroup(.checks), "checkmark.shield"), + (.tableDetailGroup(.triggers), "bolt"), + (.tableDetailGroup(.partitions), "rectangle.split.3x1.fill"), ] private static let colorfulIcons: [(ObjectIconKind, ObjectIcon)] = [ @@ -79,18 +93,30 @@ struct ObjectIconProviderTests { (.query, ObjectIcon(symbolName: "doc.text.fill", tint: .orange)), (.savedQuery, ObjectIcon(symbolName: "doc.text.fill", tint: .orange)), (.user, ObjectIcon(symbolName: "person.fill", tint: .brown)), + (.recentSection, ObjectIcon(symbolName: "clock.fill", tint: .indigo)), + (.temporarySection, ObjectIcon(symbolName: "hourglass.bottomhalf.filled", tint: .orange)), + (.favoritesSection, ObjectIcon(symbolName: "star.fill", tint: .yellow)), + (.column, ObjectIcon(symbolName: "rectangle.portrait.fill", tint: .teal)), + (.primaryKey, ObjectIcon(symbolName: "key.fill", tint: .yellow)), + (.index, ObjectIcon(symbolName: "list.bullet.rectangle.fill", tint: .mint)), + (.foreignKey, ObjectIcon(symbolName: "link.circle.fill", tint: .indigo)), + (.checkConstraint, ObjectIcon(symbolName: "checkmark.shield.fill", tint: .green)), + (.tableDetailGroup(.columns), ObjectIcon(symbolName: "folder.fill", tint: .teal)), + (.tableDetailGroup(.triggers), ObjectIcon(symbolName: "folder.fill", tint: .yellow)), ] /// Every kind there is, so a glyph added to either style is checked against the system. private static var everyKind: [ObjectIconKind] { var kinds: [ObjectIconKind] = [ .database, .systemDatabase, .schema, .externalSchema, .partition, .trigger, .tableFolder, - .query, .savedQuery, .user, + .query, .savedQuery, .user, .recentSection, .temporarySection, .favoritesSection, + .column, .primaryKey, .index, .foreignKey, .checkConstraint, ] kinds += TableInfo.TableType.allCases.map { .relation($0) } kinds += RoutineInfo.Kind.allCases.map { .routine($0) } kinds += UserDefinedTypeInfo.Kind.allCases.map { .userType($0) } kinds += SidebarObjectKind.allCases.map { .section($0) } + kinds += TableDetailGroupKind.allCases.map { .tableDetailGroup($0) } return kinds } @@ -135,6 +161,37 @@ struct ObjectIconProviderTests { } } + @Test("A group under a table is a folder in the hue of the rows it holds") + func detailGroupsTakeTheirRowsHue() { + let rows: [(TableDetailGroupKind, ObjectIconKind)] = [ + (.columns, .column), (.indexes, .index), (.foreignKeys, .foreignKey), + (.checks, .checkConstraint), (.triggers, .trigger), (.partitions, .partition), + ] + #expect(rows.count == TableDetailGroupKind.allCases.count) + for (group, row) in rows { + let folder = ObjectIconProvider.icon(for: .tableDetailGroup(group), style: .colorful) + #expect(folder.symbolName == "folder.fill") + #expect(folder.tint == ObjectIconProvider.icon(for: row, style: .colorful).tint, "\(group)") + } + } + + @Test("A column or index that is the primary key draws the key, in both styles") + func detailRowsNameTheirKind() { + let column = TestFixtures.makeColumnInfo(name: "total", isPrimaryKey: false) + let key = TestFixtures.makeColumnInfo(name: "id", isPrimaryKey: true) + let primary = IndexInfo(name: "orders_pkey", columns: ["id"], isUnique: true, isPrimary: true, type: "BTREE") + let plain = IndexInfo(name: "by_total", columns: ["total"], isUnique: false, isPrimary: false, type: "BTREE") + + #expect(ObjectIconKind(TableDetailItem.column(column)) == .column) + #expect(ObjectIconKind(TableDetailItem.column(key)) == .primaryKey) + #expect(ObjectIconKind(TableDetailItem.index(primary)) == .primaryKey) + #expect(ObjectIconKind(TableDetailItem.index(plain)) == .index) + #expect(ObjectIconProvider.icon(for: ObjectIconKind(TableDetailItem.column(key)), style: .colorful) + == ObjectIcon(symbolName: "key.fill", tint: .yellow)) + #expect(ObjectIconProvider.icon(for: ObjectIconKind(TableDetailItem.column(column)), style: .standard) + == ObjectIcon(symbolName: "rectangle.portrait")) + } + @Test("Every glyph in both styles is a symbol the system has") func everySymbolExists() { for kind in Self.everyKind { From 5c09c4995d184011ce38c7e4097fa4514f006d7c Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 14:24:10 +0700 Subject: [PATCH 105/123] fix(filter): open the filter panel with a temporary table too With "Open the filter panel with each table" on, a table tab opens its filter panel when it first opens. A temporary table skipped the whole restore, because saved filters are keyed by a name it shares with the permanent table it hides, so it skipped the panel as well. It still restores no saved filters, and now opens the panel on its first open like any other table. Going back to it later leaves a closed panel closed. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Core/Coordinators/FilterCoordinator.swift | 15 ++++- .../Main/TemporaryTableFilterPanelTests.swift | 55 +++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 apple/TableProTests/Views/Main/TemporaryTableFilterPanelTests.swift diff --git a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift index 14f7eac957..0668f86044 100644 --- a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift @@ -260,10 +260,14 @@ final class FilterCoordinator: ObservableObject { /// `executedFilters`, which is the record of what the rows on screen were fetched with. That /// tab has no rows. Its first selection runs the first load, which rebuilds the query properly. func restoreFilters(forTabAt index: Int) { - // Saved filters are keyed by name, which a temporary table shares with the permanent table it hides. guard index < parent.tabManager.tabs.count, - !parent.tabManager.tabs[index].tableContext.isTemporary, let tableName = parent.tabManager.tabs[index].tableContext.tableName else { return } + // Saved filters are keyed by name, which a temporary table shares with the permanent table it hides, so a + // temporary table restores none of them and takes only the panel every table opens with. + guard !parent.tabManager.tabs[index].tableContext.isTemporary else { + openPanelForOpeningTable(at: index) + return + } restoreLastFilters(for: tableName, at: index) restoreBrowseSearch(for: tableName, at: index) guard parent.tabManager.selectedTabIndex == index else { return } @@ -600,6 +604,13 @@ final class FilterCoordinator: ObservableObject { ) } + /// `DataGridSettings.opensFilterPanelForTables` for a table with nothing to restore. Like the restore, this runs + /// only as a table opens, so a panel the reader closed stays closed across tab switches. + private func openPanelForOpeningTable(at index: Int) { + guard AppSettingsManager.shared.dataGrid.opensFilterPanelForTables else { return } + mutateFilterState(at: index) { $0.isVisible = true } + } + private func restoreLastFilters(for tableName: String, at index: Int) { let settings = FilterSettingsStorage.shared.loadSettings() guard index < parent.tabManager.tabs.count else { return } diff --git a/apple/TableProTests/Views/Main/TemporaryTableFilterPanelTests.swift b/apple/TableProTests/Views/Main/TemporaryTableFilterPanelTests.swift new file mode 100644 index 0000000000..bcd5f92405 --- /dev/null +++ b/apple/TableProTests/Views/Main/TemporaryTableFilterPanelTests.swift @@ -0,0 +1,55 @@ +// +// TemporaryTableFilterPanelTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +extension GlobalStateSuites { + /// A temporary table restores no saved filters, since they are keyed by a name it shares with the permanent table + /// it hides, and still opens its filter panel when the data view setting asks for one with each table. + @Suite(.appSettings { $0.dataGrid.opensFilterPanelForTables = true }) + @MainActor + struct TemporaryTableFilterPanelTests { + private let fixture = CoordinatorFixture() + private let temporary = TableInfo(name: "orders", type: .table, rowCount: nil, isTemporary: true) + + private func openTab() throws -> QueryTab { + try #require(fixture.tabManager.selectedTab) + } + + @Test("A temporary table opens with the filter panel, as every table does") + func opensThePanel() throws { + fixture.coordinator.openTableTab(temporary) + + let tab = try openTab() + #expect(tab.tableContext.isTemporary) + #expect(tab.filterState.isVisible) + #expect(tab.filterState.filters.isEmpty) + } + + @Test("Going back to an open temporary table leaves a panel the reader closed closed") + func opensOnlyOnFirstOpen() throws { + fixture.coordinator.openTableTab(temporary) + let index = try #require(fixture.tabManager.selectedTabIndex) + fixture.tabManager.mutate(at: index) { $0.filterState.isVisible = false } + + fixture.coordinator.openTableTab(temporary) + + #expect(fixture.tabManager.tabs.count == 1) + #expect(try openTab().filterState.isVisible == false) + } + + @Test( + "With the setting off a temporary table opens without the panel", + .appSettings { $0.dataGrid.opensFilterPanelForTables = false } + ) + func settingOffLeavesThePanelClosed() throws { + fixture.coordinator.openTableTab(temporary) + + #expect(try openTab().filterState.isVisible == false) + } + } +} From 4700c04f5643b1714e5ea29e34f63bc50559bf33 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 14:30:03 +0700 Subject: [PATCH 106/123] feat(editor): confirm a connection pick in the two-row query bar Choosing another connection in the query bar moved the tab at once. It now asks first, in a sheet on the tab's window that names the tab, the connection it leaves and the one it moves to, with Move and Cancel. A target tagged production or held to a Safe Mode level says so, and there Cancel comes first and keeps Return, as quitting with unsaved edits does. Choosing the connection the tab is on still does nothing, and Database > Move Tab to Connection is unchanged. The question goes through MainContentCoordinator.askToMoveQueryTab, so tests answer it without a window. QueryConnectionMenuTests' pick case now answers the question before it expects the move. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Query/QueryConnectionMenu.swift | 12 +- .../Query/QueryTabMoveConfirmation.swift | 73 ++++++++++ .../Views/Editor/QueryConnectionPicker.swift | 2 +- .../MainContentCoordinator+QueryBar.swift | 22 ++- .../Views/Main/MainContentCoordinator.swift | 5 + .../Query/QueryConnectionMenuTests.swift | 73 +++++++--- .../Query/QueryTabMoveConfirmationTests.swift | 133 ++++++++++++++++++ .../Editor/QueryEditorPaneLayoutTests.swift | 1 + 8 files changed, 292 insertions(+), 29 deletions(-) create mode 100644 apple/TablePro/Models/Query/QueryTabMoveConfirmation.swift create mode 100644 apple/TableProTests/Models/Query/QueryTabMoveConfirmationTests.swift diff --git a/apple/TablePro/Models/Query/QueryConnectionMenu.swift b/apple/TablePro/Models/Query/QueryConnectionMenu.swift index 9be7eaa855..eaa697d97d 100644 --- a/apple/TablePro/Models/Query/QueryConnectionMenu.swift +++ b/apple/TablePro/Models/Query/QueryConnectionMenu.swift @@ -54,9 +54,10 @@ internal enum QueryConnectionMenu { /// The connection a query tab runs on, and what picking another one in the bar does. /// -/// A pick moves the tab, the way Database > Move Tab to Connection does, through the `move` the bar -/// is handed: `MainContentCoordinator.moveQueryTab(_:toConnection:)`, which ends in -/// `WindowManager.moveQueryTab`, the only route a tab takes between connections. +/// A pick asks first, through the `confirm` the bar is handed: the menu sits a click from the editor, +/// and the move sends the tab's next run elsewhere. A yes moves the tab, the way Database > Move Tab +/// to Connection does, through `move`: `MainContentCoordinator.moveQueryTab(_:toConnection:)`, which +/// ends in `WindowManager.moveQueryTab`, the only route a tab takes between connections. internal struct QueryConnectionPickerModel { internal let connectionId: UUID internal let name: String @@ -64,6 +65,8 @@ internal struct QueryConnectionPickerModel { /// `canMoveTabToConnection`: a running tab, or one whose grid edits would stay behind, keeps its /// connection until that is settled. internal let canMove: Bool + /// `MainContentCoordinator.confirmQueryTabMove(_:to:)`: true once the reader agreed to the move. + internal let confirm: @MainActor (UUID) async -> Bool internal let move: @MainActor (UUID) -> Void internal var hint: String { @@ -74,8 +77,9 @@ internal struct QueryConnectionPickerModel { } @MainActor - internal func choose(_ id: UUID) { + internal func choose(_ id: UUID) async { guard canMove, id != connectionId else { return } + guard await confirm(id) else { return } move(id) } } diff --git a/apple/TablePro/Models/Query/QueryTabMoveConfirmation.swift b/apple/TablePro/Models/Query/QueryTabMoveConfirmation.swift new file mode 100644 index 0000000000..d70de5a3ec --- /dev/null +++ b/apple/TablePro/Models/Query/QueryTabMoveConfirmation.swift @@ -0,0 +1,73 @@ +// +// QueryTabMoveConfirmation.swift +// TablePro +// + +import AppKit + +/// How a query bar pick puts its question: a sheet on the tab's window in the app, and an answer without one under +/// test, where an app-modal alert would hold the run. +internal typealias QueryTabMoveConfirming = @MainActor (QueryTabMoveConfirmation, NSWindow?) async -> Bool + +/// The question the two-row query bar asks before a pick moves a tab to another connection. +/// +/// The menu sits in the editor, a click away from the text, so a slip would send the tab's next run somewhere the +/// reader did not mean. A target the reader marked as needing care, by a production tag or a Safe Mode level, says so, +/// and there Return cancels rather than moves. +internal struct QueryTabMoveConfirmation: Equatable { + internal let title: String + internal let message: String + internal let cancelIsDefault: Bool + + @MainActor + internal init(tabTitle: String, sourceName: String, target: DatabaseConnection, targetTags: [ConnectionTag]) { + title = String(format: String(localized: "Move “%@” to “%@”?"), tabTitle, target.name) + var sentences = [ + String(format: String(localized: "The tab leaves “%@”, and its next run goes to “%@”."), sourceName, target.name), + ] + let production = targetTags.first { Self.isProductionTag($0) } + if let production { + sentences.append(String(format: String(localized: "“%@” is tagged %@."), target.name, production.name)) + } + let level = target.safeModeLevel + if level != .silent { + sentences.append( + String(format: String(localized: "“%@” has its Safe Mode level set to %@."), target.name, level.displayName) + ) + } + message = sentences.joined(separator: " ") + cancelIsDefault = production != nil || level != .silent + } + + /// The preset's name, which every Mac maps to one record, compared the way tag names are matched. + internal static func isProductionTag(_ tag: ConnectionTag) -> Bool { + tag.name.trimmingCharacters(in: .whitespacesAndNewlines).caseInsensitiveCompare("production") == .orderedSame + } + + /// Built apart from its presentation, so a test reads the buttons with no window. Over a marked target Cancel comes + /// first and keeps Return, as quitting with unsaved edits does, and Move takes a deliberate click. + @MainActor + internal func makeAlert() -> (alert: NSAlert, moveResponse: NSApplication.ModalResponse) { + let alert = NSAlert() + alert.messageText = title + alert.informativeText = message + let move = String(localized: "Move") + let cancel = String(localized: "Cancel") + guard cancelIsDefault else { + alert.alertStyle = .informational + alert.addButton(withTitle: move) + AlertHelper.addCancelButton(to: alert, title: cancel) + return (alert, .alertFirstButtonReturn) + } + alert.alertStyle = .warning + alert.addButton(withTitle: cancel).keyEquivalent = "\r" + alert.addButton(withTitle: move).keyEquivalent = "" + return (alert, .alertSecondButtonReturn) + } + + @MainActor + internal static func present(_ confirmation: QueryTabMoveConfirmation, in window: NSWindow?) async -> Bool { + let (alert, moveResponse) = confirmation.makeAlert() + return await AlertHelper.response(to: alert, in: window) == moveResponse + } +} diff --git a/apple/TablePro/Views/Editor/QueryConnectionPicker.swift b/apple/TablePro/Views/Editor/QueryConnectionPicker.swift index cdd01a45f3..d30ee8f40e 100644 --- a/apple/TablePro/Views/Editor/QueryConnectionPicker.swift +++ b/apple/TablePro/Views/Editor/QueryConnectionPicker.swift @@ -63,7 +63,7 @@ struct QueryConnectionPicker: View { Menu(name) { menuContent(children) } case .connection(let id, let name, let color): Button { - model.choose(id) + Task { await model.choose(id) } } label: { if id == model.connectionId { Label(name, systemImage: "checkmark") diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift index 13c75644f6..4e11c9a74d 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryBar.swift @@ -12,7 +12,7 @@ extension MainContentCoordinator { /// /// Each command is the one the rest of the app already runs: Save is Cmd+S, Query Builder is the /// Join Builder sheet, a saved query goes in the way completion inserts a favorite, and a - /// connection pick is Move Tab to Connection. + /// connection pick is Move Tab to Connection once the reader confirms it. func queryBarTwoRowInput(forTab tabId: UUID) -> QueryEditorBar.TwoRowInput { QueryEditorBar.TwoRowInput( connection: QueryConnectionPickerModel( @@ -20,6 +20,10 @@ extension MainContentCoordinator { name: connection.name, color: connection.color, canMove: canMoveTabToConnection(tabId), + confirm: { [weak self] target in + guard let self else { return false } + return await self.confirmQueryTabMove(tabId, to: target) + }, move: { [weak self] target in self?.moveQueryTab(tabId, toConnection: target) } ), savedQueries: ConnectionDataCache.shared(for: connectionId), @@ -30,4 +34,20 @@ extension MainContentCoordinator { } ) } + + /// The question a pick in the query bar asks before the tab moves. The target is read from the + /// library when picked, so the question names the tag and Safe Mode level it has now. The menu lists + /// only saved connections, so a target missing here was deleted since, and it is refused unasked. + func confirmQueryTabMove(_ tabId: UUID, to targetId: UUID) async -> Bool { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), + let target = services.connectionStorage.loadConnections().first(where: { $0.id == targetId }) + else { return false } + let confirmation = QueryTabMoveConfirmation( + tabTitle: tab.title, + sourceName: connection.name, + target: target, + targetTags: services.tagStorage.tags(for: target.tagIds) + ) + return await askToMoveQueryTab(confirmation, contentWindow) + } } diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 7b257b6851..9794459937 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -312,6 +312,11 @@ final class MainContentCoordinator: ObservableObject { AlertHelper.showErrorSheet(title: title, message: message, window: window) } + // Injectable for the same reason: the two-row query bar's question before a pick moves a tab. + var askToMoveQueryTab: QueryTabMoveConfirming = { confirmation, window in + await QueryTabMoveConfirmation.present(confirmation, in: window) + } + // MARK: - Internal State // Published on purpose: busy state is derived from membership here, and every claim, settle and invalidate is a write. diff --git a/apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift b/apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift index 951b71144a..4bdac0ece3 100644 --- a/apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift +++ b/apple/TableProTests/Models/Query/QueryConnectionMenuTests.swift @@ -32,39 +32,66 @@ struct QueryConnectionMenuTests { ]) } - @Test("Choosing another connection moves the tab there through the move it was handed") - func choosingMovesTheTab() { - let current = UUID() - let target = UUID() + /// What a pick asked and what it moved, so a case reads both. + private final class PickLog { + var asked: [UUID] = [] var moves: [UUID] = [] - let model = QueryConnectionPickerModel( - connectionId: current, + } + + private static func picker( + connectionId: UUID = UUID(), + canMove: Bool = true, + answer: Bool, + log: PickLog + ) -> QueryConnectionPickerModel { + QueryConnectionPickerModel( + connectionId: connectionId, name: "Shop", color: .none, - canMove: true, - move: { moves.append($0) } + canMove: canMove, + confirm: { target in + log.asked.append(target) + return answer + }, + move: { log.moves.append($0) } ) + } - model.choose(target) - model.choose(current) + @Test("Choosing another connection asks first, and a yes moves the tab through the move it was handed") + func confirmedPickMovesTheTab() async { + let current = UUID() + let target = UUID() + let log = PickLog() + let model = Self.picker(connectionId: current, answer: true, log: log) - #expect(moves == [target], "The connection the tab is on is no move") + await model.choose(target) + await model.choose(current) + + #expect(log.asked == [target], "The connection the tab is on is no move, so nothing is asked") + #expect(log.moves == [target]) } - @Test("A tab that cannot move stays put, and the picker says why") - func busyTabStaysPut() { - var moves: [UUID] = [] - let model = QueryConnectionPickerModel( - connectionId: UUID(), - name: "Shop", - color: .none, - canMove: false, - move: { moves.append($0) } - ) + @Test("Cancelling the question leaves the tab where it is") + func cancelledPickMovesNothing() async { + let target = UUID() + let log = PickLog() + let model = Self.picker(answer: false, log: log) + + await model.choose(target) + + #expect(log.asked == [target]) + #expect(log.moves.isEmpty) + } + + @Test("A tab that cannot move stays put without a question, and the picker says why") + func busyTabStaysPut() async { + let log = PickLog() + let model = Self.picker(canMove: false, answer: true, log: log) - model.choose(UUID()) + await model.choose(UUID()) - #expect(moves.isEmpty) + #expect(log.asked.isEmpty) + #expect(log.moves.isEmpty) #expect(model.hint.contains("cannot move")) } diff --git a/apple/TableProTests/Models/Query/QueryTabMoveConfirmationTests.swift b/apple/TableProTests/Models/Query/QueryTabMoveConfirmationTests.swift new file mode 100644 index 0000000000..e06e184835 --- /dev/null +++ b/apple/TableProTests/Models/Query/QueryTabMoveConfirmationTests.swift @@ -0,0 +1,133 @@ +// +// QueryTabMoveConfirmationTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct QueryTabMoveConfirmationTests { + private static let productionTag = ConnectionTag(name: "production", isPreset: true, color: .red) + + private static func confirmation( + tags: [ConnectionTag] = [], + level: SafeModeLevel = .silent + ) -> QueryTabMoveConfirmation { + var target = TestFixtures.makeConnection(name: "Orders") + target.safeModeLevel = level + return QueryTabMoveConfirmation(tabTitle: "Query 1", sourceName: "Shop", target: target, targetTags: tags) + } + + @Test("The question names the tab, the connection it leaves and the one it moves to") + func namesTheTabAndTheTarget() { + let plain = Self.confirmation() + + #expect(plain.title.contains("Query 1")) + #expect(plain.title.contains("Orders")) + #expect(plain.message.contains("Shop")) + #expect(plain.message.contains("Orders")) + #expect(!plain.cancelIsDefault) + } + + @Test("An ordinary target asks with Move as the default and Escape on Cancel") + func ordinaryTargetDefaultsToMove() { + let (alert, moveResponse) = Self.confirmation().makeAlert() + + #expect(alert.buttons.map { $0.title } == [String(localized: "Move"), String(localized: "Cancel")]) + #expect(alert.buttons[0].keyEquivalent == "\r") + #expect(alert.buttons[1].keyEquivalent == "\u{1B}") + #expect(moveResponse == .alertFirstButtonReturn) + #expect(alert.alertStyle == .informational) + } + + @Test("A target tagged production says so, and Return cancels there") + func productionTargetDefaultsToCancel() { + let marked = Self.confirmation(tags: [ConnectionTag(name: "local"), Self.productionTag]) + let (alert, moveResponse) = marked.makeAlert() + + #expect(marked.message.contains("production")) + #expect(marked.cancelIsDefault) + #expect(alert.buttons.map { $0.title } == [String(localized: "Cancel"), String(localized: "Move")]) + #expect(alert.buttons[0].keyEquivalent == "\r") + #expect(alert.buttons[1].keyEquivalent.isEmpty) + #expect(moveResponse == .alertSecondButtonReturn) + #expect(alert.alertStyle == .warning) + } + + @Test("A target held to a Safe Mode level names the level, and Return cancels there") + func safeModeTargetDefaultsToCancel() { + let marked = Self.confirmation(level: .safeMode) + + #expect(marked.message.contains(SafeModeLevel.safeMode.displayName)) + #expect(marked.cancelIsDefault) + #expect(marked.makeAlert().moveResponse == .alertSecondButtonReturn) + } + + @Test("A tag only matches production by its name", arguments: [ + ("production", true), (" Production ", true), ("prod", false), ("development", false), + ]) + func productionTagMatch(name: String, matches: Bool) { + #expect(QueryTabMoveConfirmation.isProductionTag(ConnectionTag(name: name)) == matches) + } +} + +extension GlobalStateSuites { + /// The coordinator reads the target from the connection library, so the saved list is swapped for the case. + @MainActor + struct QueryBarMoveConfirmationTests { + private static let productionTagId = UUID(uuidString: "00000000-0000-0000-0000-000000000003") + + private final class Questions { + var asked: [QueryTabMoveConfirmation] = [] + } + + @Test("A pick in the query bar asks the coordinator's question about the saved target before anything moves") + func pickAsksAboutTheSavedTarget() async throws { + var target = TestFixtures.makeConnection(name: "Orders Live") + target.tagIds = try [#require(Self.productionTagId)] + let saved = ConnectionStorage.shared.loadConnections() + ConnectionStorage.shared.saveConnections(saved + [target]) + defer { ConnectionStorage.shared.saveConnections(saved) } + + let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(name: "Shop")) + let tab = fixture.addTab(QueryTab(title: "Monthly totals", tabType: .query)) + let questions = Questions() + fixture.coordinator.askToMoveQueryTab = { confirmation, _ in + questions.asked.append(confirmation) + return false + } + let picker = fixture.coordinator.queryBarTwoRowInput(forTab: tab.id).connection + #expect(picker.canMove) + + await picker.choose(target.id) + await picker.choose(fixture.connection.id) + + #expect(questions.asked.count == 1, "The connection the tab is on asks nothing") + let question = try #require(questions.asked.first) + #expect(question.title.contains("Monthly totals")) + #expect(question.title.contains("Orders Live")) + #expect(question.message.contains("Shop")) + #expect(question.cancelIsDefault, "The target carries the production tag") + #expect(fixture.tabManager.tabs.map { $0.id } == [tab.id]) + } + + @Test("A target no longer in the library asks nothing and moves nothing") + func unknownTargetAsksNothing() async { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(QueryTab(title: "Query 1", tabType: .query)) + let questions = Questions() + fixture.coordinator.askToMoveQueryTab = { confirmation, _ in + questions.asked.append(confirmation) + return true + } + + let confirmed = await fixture.coordinator.confirmQueryTabMove(tab.id, to: UUID()) + + #expect(!confirmed) + #expect(questions.asked.isEmpty) + } + } +} diff --git a/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift b/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift index 275143c11c..584bb606d8 100644 --- a/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift +++ b/apple/TableProTests/Views/Editor/QueryEditorPaneLayoutTests.swift @@ -74,6 +74,7 @@ enum QueryEditorPaneFixture { name: "Shop Demo", color: .blue, canMove: true, + confirm: { _ in false }, move: { _ in } ), savedQueries: ConnectionDataCache.shared(for: connectionId), From 53d4a734c455985dd3159235cb55290ab12e615f Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 14:31:14 +0700 Subject: [PATCH 107/123] fix(settings): call the filter bar by its name in the data view settings The two data view toggles, their section header and the Navigator Layout footer said "filter panel", while the View menu and the filter settings call the same control the filter bar. They now read "Show sort criteria in the filter bar", "Open the filter bar with each table" and "Filter Bar". The settings keys and property names are unchanged, so saved settings still load. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Views/Settings/GeneralSettingsView.swift | 2 +- .../TablePro/Views/Settings/Sections/DataGridSection.swift | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 72d5d12808..2184a31ca3 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -83,7 +83,7 @@ struct GeneralSettingsView: View { tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the \ tree, takes the connection and database out of the toolbar, and makes Tree the default \ sidebar layout. In table tabs it shows column types in \ - the header, the sort and a Text mode in the filter panel, opens that panel with each table, \ + the header, the sort and a Text mode in the filter bar, opens that bar with each table, \ puts the result bar above the grid and names the database and connection in tab titles. \ In query tabs it shows the query bar on two rows, and object icons turn colorful. \ Standard Layout turns them off again. Open connections switch layout too. diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 22394b70de..afd18503a2 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -60,11 +60,11 @@ struct DataGridSection: View { } Section { - Toggle("Show sort criteria in the filter panel", isOn: $settings.showsSortInFilterPanel) + Toggle("Show sort criteria in the filter bar", isOn: $settings.showsSortInFilterPanel) .help(String(localized: "Edit the filters and the sort together, write the filter as text, and apply both at once")) - Toggle("Open the filter panel with each table", isOn: $settings.opensFilterPanelForTables) + Toggle("Open the filter bar with each table", isOn: $settings.opensFilterPanelForTables) } header: { - Text("Filter Panel") + Text("Filter Bar") } Section { From 6e1d8ca3ec14f07597352653c5b0f14f67e3a66b Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 14:33:59 +0700 Subject: [PATCH 108/123] chore(l10n): add the icon style, move confirmation and filter bar strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../TablePro/Resources/Localizable.xcstrings | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 1fc1b4e6f2..b0c9bc5e89 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -764,6 +764,16 @@ }, "“%@” changed since you last synced" : { + }, + "“%@” has its Safe Mode level set to %@." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "“%1$@” has its Safe Mode level set to %2$@." + } + } + } }, "“%@” holds no file to import." : { @@ -1069,6 +1079,16 @@ } } }, + "“%@” is tagged %@." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "“%1$@” is tagged %2$@." + } + } + } + }, "“%@” isn't a port or a range of ports, such as 4000-4999." : { "extractionState" : "manual", "generatesSymbol" : false @@ -82543,6 +82563,9 @@ } } } + }, + "Filter Bar" : { + }, "Filter by name" : { "localizations" : { @@ -111744,6 +111767,19 @@ "extractionState" : "manual", "generatesSymbol" : false }, + "Move" : { + + }, + "Move “%@” to “%@”?" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Move “%1$@” to “%2$@”?" + } + } + } + }, "Move “%@” to Connection" : { }, @@ -113804,6 +113840,9 @@ }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, takes the connection and database out of the toolbar, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter bar, opens that bar with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, takes the connection and database out of the toolbar, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter panel, opens that panel with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { @@ -129284,6 +129323,9 @@ } } } + }, + "Open the filter bar with each table" : { + }, "Open the filter panel with each table" : { @@ -167018,6 +167060,9 @@ } } } + }, + "Show sort criteria in the filter bar" : { + }, "Show sort criteria in the filter panel" : { @@ -194272,6 +194317,16 @@ } } }, + "The tab leaves “%@”, and its next run goes to “%@”." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "The tab leaves “%1$@”, and its next run goes to “%2$@”." + } + } + } + }, "The table %@ was already created with different columns. Choose another name." : { "localizations" : { "fr" : { From d29fa5d25f8191d91fe5f2e5dba4ef09011fde5e Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 15:31:28 +0700 Subject: [PATCH 109/123] feat(results): record what each statement of a query run did Every run path in a query tab now records a per-statement log beside the results it installs: the statement, rows returned or affected, the error, a stop, the status and server output, the time, and the result it made. Single statements, parameterized statements, multi-statement runs, batches and Explain all record it. A re-read of a result (sort, reload) keeps the run's log and moves its pointer to the new result. What runs and which results are kept is unchanged. A stopped run, which settles nothing, still records which statement it interrupted, unless a newer run owns the tab. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../QueryExecutionCoordinator+Batches.swift | 110 +++++- ...QueryExecutionCoordinator+Parameters.swift | 88 ++++- .../QueryExecutionCoordinator+RunLog.swift | 55 +++ apple/TablePro/Models/Query/QueryRunLog.swift | 275 +++++++++++++++ .../TablePro/Models/Query/QueryTabState.swift | 18 + .../MainContentCoordinator+Explain.swift | 2 + .../MainContentCoordinator+QueryHelpers.swift | 13 +- .../Views/Main/MainContentCoordinator.swift | 8 +- .../Models/Query/QueryRunLogTests.swift | 319 ++++++++++++++++++ .../Main/QueryRunLogRecordingTests.swift | 195 +++++++++++ 10 files changed, 1059 insertions(+), 24 deletions(-) create mode 100644 apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+RunLog.swift create mode 100644 apple/TablePro/Models/Query/QueryRunLog.swift create mode 100644 apple/TableProTests/Models/Query/QueryRunLogTests.swift create mode 100644 apple/TableProTests/Views/Main/QueryRunLogRecordingTests.swift diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift index 71a653a965..11ba7ee940 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift @@ -149,9 +149,14 @@ extension QueryExecutionCoordinator { let sessionNotice = Self.runNotice(outcome: run.outcome, sessionState: run.sessionState) switch run.outcome { case .cancelled(let outputs): - guard parent.tabExecution.settle(claim) else { return } + guard parent.tabExecution.settle(claim) else { + recordStoppedBatches(prepared, outputs: outputs, claim: claim) + return + } parent.retireQueryTask(.claim(claim)) - keepStoppedBatches(prepared, outputs: outputs, parameters: parameters, tabId: tabId, sessionNotice: sessionNotice) + keepStoppedBatches( + prepared, outputs: outputs, parameters: parameters, claim: claim, sessionNotice: sessionNotice + ) parent.reportEndedExecutions([ EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) ]) @@ -376,31 +381,84 @@ extension QueryExecutionCoordinator { outcome: .succeeded(OperationSummary(rowsAffected: totalRowsAffected, statementCount: outputs.count)) ) recordBatchHistory(prepared, outputs: outputs, parameters: parameters, tabId: tabId, failedIndex: nil) + let groups = batchResultSetGroups(prepared, outputs: outputs, tabId: tabId) presentMultiStatementResults( tabId: tabId, timing: PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }), totalRowsAffected: totalRowsAffected, - newResultSets: batchResultSets(prepared, outputs: outputs, tabId: tabId), + newResultSets: groups.flatMap { $0 }, sessionNotice: sessionNotice ) + recordRunLog( + Self.runLogEntries(prepared, outputs: outputs, groups: groups), + tabId: tabId, + startedAt: claim.startedAt, + notice: sessionNotice + ) } private func keepStoppedBatches( _ prepared: [PreparedBatch], outputs: [BatchOutput], parameters: [QueryParameter], - tabId: UUID, + claim: TabExecutionClaim, sessionNotice: String? ) { - guard !outputs.isEmpty else { return } + let tabId = claim.tabId + guard !outputs.isEmpty else { + recordStoppedBatches(prepared, outputs: [], claim: claim) + return + } recordBatchHistory(prepared, outputs: outputs, parameters: parameters, tabId: tabId, failedIndex: nil) + let groups = batchResultSetGroups(prepared, outputs: outputs, tabId: tabId) presentMultiStatementResults( tabId: tabId, timing: PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }), totalRowsAffected: outputs.reduce(0) { $0 + $1.rowsAffected }, - newResultSets: batchResultSets(prepared, outputs: outputs, tabId: tabId), + newResultSets: groups.flatMap { $0 }, sessionNotice: sessionNotice ) + recordRunLog( + QueryRunLog.entries( + statements: prepared.map(\.batch.sql), + finished: Self.runLogEntries(prepared, outputs: outputs, groups: groups), + ending: .stopped + ), + tabId: tabId, + startedAt: claim.startedAt, + notice: sessionNotice + ) + } + + /// A stopped run installs none of its results, so its entries point at none. + private func recordStoppedBatches(_ prepared: [PreparedBatch], outputs: [BatchOutput], claim: TabExecutionClaim) { + let finished = Self.runLogEntries(prepared, outputs: outputs, groups: []) + recordRunLog( + QueryRunLog.entries(statements: prepared.map(\.batch.sql), finished: finished, ending: .stopped), + tabId: claim.tabId, + startedAt: claim.startedAt + ) + } + + /// One entry per batch, as history keeps one per batch: the batch is what ran. It points at the first result the + /// batch produced, and counts the rows of all of them. + private static func runLogEntries( + _ prepared: [PreparedBatch], + outputs: [BatchOutput], + groups: [[ResultSet]] + ) -> [QueryRunLogEntry] { + zip(prepared, outputs).enumerated().map { index, pair in + let (entry, output) = pair + let returned = output.resultSets.reduce(0) { $0 + $1.rows.count } + return QueryRunLogEntry( + statement: entry.batch.sql, + outcome: output.resultSets.isEmpty ? .affectedRows(output.rowsAffected) : .returnedRows(returned), + executionTime: output.executionTime, + statusMessage: output.resultSets.compactMap(\.statusMessage).first, + serverOutput: output.serverOutput, + resultSetId: groups.indices.contains(index) ? groups[index].first?.id : nil + ) + } } private func handleBatchFailure( @@ -427,7 +485,12 @@ extension QueryExecutionCoordinator { errorResult.failedQuery = report.failedSQL errorResult.statementAnchor = failedBatch?.batch.anchor - guard parent.tabExecution.settle(claim) else { return } + guard parent.tabExecution.settle(claim) else { + // A Stop during a batch surfaces as that batch failing, after the claim has already ended. + let finished = outputs.prefix { $0.errors.isEmpty } + recordStoppedBatches(prepared, outputs: Array(finished), claim: claim) + return + } parent.retireQueryTask(.claim(claim)) reportOperation(kind: .queryBatch, claim: claim, outcome: .failed(reason: context.errorDescription)) recordBatchHistory( @@ -441,15 +504,14 @@ extension QueryExecutionCoordinator { let timing = PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }) parent.flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) + let groups = batchResultSetGroups(prepared, outputs: outputs, tabId: tabId) parent.tabManager.mutate(tabId: tabId) { tab in // The Error result carries the failure, so the banner stays on it rather than over every other result. tab.execution.errorMessage = nil tab.execution.errorQuery = nil tab.execution.executionTime = timing.total tab.execution.lastExecutedAt = Date() - tab.display.replaceUnpinnedResults( - with: batchResultSets(prepared, outputs: outputs, tabId: tabId) + [errorResult] - ) + tab.display.replaceUnpinnedResults(with: groups.flatMap { $0 } + [errorResult]) if tab.display.isResultsCollapsed { tab.display.isResultsCollapsed = false } @@ -460,6 +522,21 @@ extension QueryExecutionCoordinator { parent.toolbarState.recordQueryTiming(timing, for: tabId) parent.announceQueryError(report.message) } + // The batch that answered with an error is among the outputs, and is reported as the failure, not as run. + let succeeded = BatchStatementOutcome.failed( + results: outputs, failure: context.failure, errorDescription: context.errorDescription + ).succeededCount + recordRunLog( + QueryRunLog.entries( + statements: prepared.map(\.batch.sql), + finished: Self.runLogEntries( + Array(prepared.prefix(succeeded)), outputs: Array(outputs.prefix(succeeded)), groups: groups + ), + ending: .failed(statement: failedBatch?.batch.sql ?? report.failedSQL, message: message, resultSetId: errorResult.id) + ), + tabId: tabId, + startedAt: claim.startedAt + ) } /// One history entry per batch, because the batch is what ran. A failed batch is recorded as failed, with the @@ -494,17 +571,19 @@ extension QueryExecutionCoordinator { } } - /// Each batch's result sets in the order it returned them. A batch whose shape pins each result set to one of its - /// queries names them after it and points back at it; any other batch numbers them and points at the batch. - private func batchResultSets( + /// Each batch's result sets in the order it returned them, one group per batch. A batch whose shape pins each + /// result set to one of its queries names them after it and points back at it; any other batch numbers them and + /// points at the batch. + private func batchResultSetGroups( _ prepared: [PreparedBatch], outputs: [BatchOutput], tabId: UUID - ) -> [ResultSet] { + ) -> [[ResultSet]] { let databaseType = parent.connection.type let grammar = parent.lexicalGrammar let firstNumber = parent.tabManager.tabs.first { $0.id == tabId }?.display.pinnedResultCount ?? 0 var resultSets: [ResultSet] = [] + var groups: [[ResultSet]] = [] for (entry, output) in zip(prepared, outputs) { let isPlainQuery = { (sql: String) in QueryExecutor.qualifiesForRowCap(sql: sql, tabType: .query, databaseType: databaseType) @@ -543,8 +622,9 @@ extension QueryExecutionCoordinator { } produced.last?.serverOutput = output.serverOutput resultSets += produced + groups.append(produced) } - return resultSets + return groups } private static func runNotice( diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift index 106b20e0d8..4d88868701 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift @@ -195,6 +195,7 @@ extension QueryExecutionCoordinator { ) let readsView = tab.tableContext.knowsView(named: tableName) + let loggedStatement = install.source == .newSource ? originalSQL ?? sql : nil let boundValues = BoundParameterValues(values: parameters) let failureOutput = ServerOutputBox() let grammar = parent.lexicalGrammar @@ -282,7 +283,12 @@ extension QueryExecutionCoordinator { ) await MainActor.run { [weak self] in guard let self else { return } - guard parent.tabExecution.settle(claim) else { return } + guard parent.tabExecution.settle(claim) else { + if let loggedStatement { + recordStatementCancelled(loggedStatement, tabId: tabId, startedAt: claim.startedAt) + } + return + } parent.tabManager.mutate(tabId: tabId) { tab in tab.pagination.isLoadingMore = false } @@ -291,6 +297,9 @@ extension QueryExecutionCoordinator { parent.reportEndedExecutions([ EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) ]) + if let loggedStatement { + recordStatementCancelled(loggedStatement, tabId: tabId, startedAt: claim.startedAt) + } return } handleQueryExecutionError( @@ -300,6 +309,9 @@ extension QueryExecutionCoordinator { connection: conn, serverOutput: failureOutput.output ) + if let loggedStatement { + recordStatementFailure(loggedStatement, error: error, tabId: tabId, startedAt: claim.startedAt) + } reportOperation(kind: .query, claim: claim, outcome: .failed(reason: error.localizedDescription)) } } @@ -425,13 +437,17 @@ extension QueryExecutionCoordinator { switch outcome { case .cancelled(let results): - guard parent.tabExecution.settle(claim) else { return } + guard parent.tabExecution.settle(claim) else { + recordStoppedStatements(sent, results: results, claim: claim) + return + } parent.retireQueryTask(.claim(claim)) keepStoppedStatements( history: ExecutedStatementHistory( prepared: sent, results: results, parameters: parameters, connection: conn ), tabId: tabId, + claim: claim, sessionNotice: sessionNotice ) parent.reportEndedExecutions([ @@ -611,17 +627,48 @@ extension QueryExecutionCoordinator { private func keepStoppedStatements( history: ExecutedStatementHistory, tabId: UUID, + claim: TabExecutionClaim, sessionNotice: String? ) { - guard !history.results.isEmpty else { return } + guard !history.results.isEmpty else { + recordStoppedStatements(history.prepared, results: [], claim: claim) + return + } recordExecutedStatements(history, tabId: tabId, commitOutcomeIsUnknown: false) + let resultSets = statementResultSets(history, tabId: tabId) + let finished = Self.runLogEntries(history.prepared, resultSets: resultSets) presentMultiStatementResults( tabId: tabId, timing: PluginQueryTiming.batch(of: history.results), totalRowsAffected: history.results.reduce(0) { $0 + $1.rowsAffected }, - newResultSets: statementResultSets(history, tabId: tabId), + newResultSets: resultSets, sessionNotice: sessionNotice ) + recordRunLog( + QueryRunLog.entries(statements: history.prepared.map(\.originalSQL), finished: finished, ending: .stopped), + tabId: tabId, + startedAt: claim.startedAt, + notice: sessionNotice + ) + } + + /// A stopped run installs none of its results, so its entries point at none. + private func recordStoppedStatements(_ sent: [PreparedStatement], results: [QueryResult], claim: TabExecutionClaim) { + let finished = zip(sent, results).map { statement, result in + QueryRunLogEntry(statement: statement.originalSQL, result: result) + } + recordRunLog( + QueryRunLog.entries(statements: sent.map(\.originalSQL), finished: finished, ending: .stopped), + tabId: claim.tabId, + startedAt: claim.startedAt + ) + } + + // Read before the run's notice is added to each result, so the log carries the notice once rather than per statement. + private static func runLogEntries(_ prepared: [PreparedStatement], resultSets: [ResultSet]) -> [QueryRunLogEntry] { + zip(prepared, resultSets).map { statement, resultSet in + QueryRunLogEntry(statement: statement.originalSQL, resultSet: resultSet) + } } /// Settles first, then writes. Everything below the gate belongs to a batch that still owns its @@ -645,13 +692,16 @@ extension QueryExecutionCoordinator { ) ) recordExecutedStatements(history, tabId: tabId, commitOutcomeIsUnknown: false) + let resultSets = statementResultSets(history, tabId: tabId) + let finished = Self.runLogEntries(history.prepared, resultSets: resultSets) presentMultiStatementResults( tabId: tabId, timing: PluginQueryTiming.batch(of: history.results), totalRowsAffected: totalRowsAffected, - newResultSets: statementResultSets(history, tabId: tabId), + newResultSets: resultSets, sessionNotice: sessionNotice ) + recordRunLog(finished, tabId: tabId, startedAt: claim.startedAt, notice: sessionNotice) } private func statementResultSets(_ history: ExecutedStatementHistory, tabId: UUID) -> [ResultSet] { @@ -761,6 +811,10 @@ extension QueryExecutionCoordinator { absentCells: fetchResult.absentCells ) + if install.source == .newSource { + recordStatementRun(originalSQL ?? sql, tabId: tabId, startedAt: claim.startedAt) + } + let parameterValues = nativeParameters.map { $0 as? String } let statement = originalSQL.map { NamedParameterStatement(sql: $0, parameters: originalParameters) } parent.tabManager.mutate(tabId: tabId) { @@ -794,7 +848,11 @@ extension QueryExecutionCoordinator { .flatMap { anchors.indices.contains($0) ? anchors[$0] : nil } let failedStatementSQL = report.failedSQL - guard parent.tabExecution.settle(claim) else { return } + guard parent.tabExecution.settle(claim) else { + // A Stop during a statement surfaces as that statement failing, after the claim has already ended. + recordStoppedStatements(history.prepared, results: history.results, claim: claim) + return + } parent.retireQueryTask(.claim(claim)) /// Below the settle gate for the same reason the success arm is: a superseded batch @@ -808,6 +866,7 @@ extension QueryExecutionCoordinator { ) parent.flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) + let resultSets = statementResultSets(history, tabId: tabId) parent.tabManager.mutate(tabId: tabId) { tab in // The Error result carries the failure, so the banner stays on it rather than over every other result. tab.execution.errorMessage = nil @@ -815,7 +874,7 @@ extension QueryExecutionCoordinator { tab.execution.executionTime = cumulativeTime tab.execution.lastExecutedAt = Date() - tab.display.replaceUnpinnedResults(with: statementResultSets(history, tabId: tabId) + [errorRS]) + tab.display.replaceUnpinnedResults(with: resultSets + [errorRS]) if tab.display.isResultsCollapsed { tab.display.isResultsCollapsed = false } @@ -826,6 +885,21 @@ extension QueryExecutionCoordinator { parent.toolbarState.recordQueryTiming(timing, for: tabId) parent.announceQueryError(report.message) } + recordRunLog( + QueryRunLog.entries( + statements: history.prepared.map(\.originalSQL), + finished: Self.runLogEntries(history.prepared, resultSets: resultSets), + ending: .failed( + statement: report.failedStatementIndex + .flatMap { history.prepared.indices.contains($0) ? history.prepared[$0].originalSQL : nil } + ?? report.failedSQL, + message: contextMsg, + resultSetId: errorRS.id + ) + ), + tabId: tabId, + startedAt: claim.startedAt + ) guard let rawSQL = failedStatementSQL else { return } let recordSQL = rawSQL.hasSuffix(";") ? rawSQL : rawSQL + ";" diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+RunLog.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+RunLog.swift new file mode 100644 index 0000000000..975c46f6be --- /dev/null +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+RunLog.swift @@ -0,0 +1,55 @@ +// +// QueryExecutionCoordinator+RunLog.swift +// TablePro +// + +import Foundation + +/// The run log is written beside the results, never instead of them: each path installs its results as it always +/// has and then records what every statement came to here. +extension QueryExecutionCoordinator { + /// A run whose claim was settled writes here below its settle gate. A run the user stopped settles nothing, so it + /// writes here too, and the two guards keep it from covering a newer run: a run still executing on the tab will + /// write its own log, and one that already finished started later than this one. + func recordRunLog( + _ entries: [QueryRunLogEntry], + tabId: UUID, + startedAt: ContinuousClock.Instant, + notice: String? = nil + ) { + guard !entries.isEmpty, !parent.tabExecution.isExecuting(tabId), + let tab = parent.tabManager.tabs.first(where: { $0.id == tabId }), + tab.tabType == .query else { return } + let log = QueryRunLog(startedAt: startedAt, entries: entries, notice: notice) + guard tab.display.admitsRunLog(log) else { return } + parent.tabManager.mutate(tabId: tabId) { $0.display.installRunLog(log) } + } + + /// The single-statement paths install one result and make it active, so the entry reads it back from the tab. + func recordStatementRun(_ statement: String, tabId: UUID, startedAt: ContinuousClock.Instant) { + guard let resultSet = parent.tabManager.tabs.first(where: { $0.id == tabId })?.display.activeResultSet else { + return + } + recordRunLog( + [QueryRunLogEntry(statement: statement, resultSet: resultSet)], + tabId: tabId, + startedAt: startedAt + ) + } + + /// Reads the message the failure left on the tab, so the log says exactly what the banner says. + func recordStatementFailure( + _ statement: String, + error: Error, + tabId: UUID, + startedAt: ContinuousClock.Instant + ) { + let message = parent.tabManager.tabs.first(where: { $0.id == tabId })?.execution.errorMessage + ?? error.localizedDescription + recordRunLog([.failed(statement, message: message)], tabId: tabId, startedAt: startedAt) + } + + func recordStatementCancelled(_ statement: String, tabId: UUID, startedAt: ContinuousClock.Instant) { + recordRunLog([.cancelled(statement)], tabId: tabId, startedAt: startedAt) + } +} diff --git a/apple/TablePro/Models/Query/QueryRunLog.swift b/apple/TablePro/Models/Query/QueryRunLog.swift new file mode 100644 index 0000000000..ae2d128015 --- /dev/null +++ b/apple/TablePro/Models/Query/QueryRunLog.swift @@ -0,0 +1,275 @@ +// +// QueryRunLog.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +/// What one statement of a run came to. A row set counts as rows returned even when it is empty: the +/// statement answered with columns, so its result is a grid rather than a count. +enum QueryStatementOutcome: Equatable, Sendable { + case returnedRows(Int) + case affectedRows(Int) + case plan + case failed(message: String) + case cancelled + + var isFailure: Bool { + if case .failed = self { return true } + return false + } +} + +/// One statement or batch of a run, as the Message and Summary tabs report it. +/// +/// A copy of the facts rather than a reference to the `ResultSet`: a page turn or a sort rebuilds the +/// result, and the log describes the run as it ended. +struct QueryRunLogEntry: Equatable, Identifiable, Sendable { + /// The position in the run, from 1. Set by `QueryRunLog`, which numbers its entries. + var ordinal = 0 + let statement: String + let outcome: QueryStatementOutcome + var executionTime: TimeInterval? + var statusMessage: String? + var serverOutput: PluginServerOutput = .none + /// The result this statement produced, so a Summary row can open it. Nil for a statement whose + /// result was never installed: a stopped run keeps the previous results on screen. + var resultSetId: UUID? + + var id: Int { ordinal } + + init( + statement: String, + outcome: QueryStatementOutcome, + executionTime: TimeInterval? = nil, + statusMessage: String? = nil, + serverOutput: PluginServerOutput = .none, + resultSetId: UUID? = nil + ) { + self.statement = statement + self.outcome = outcome + self.executionTime = executionTime + self.statusMessage = statusMessage + self.serverOutput = serverOutput + self.resultSetId = resultSetId + } + + @MainActor + init(statement: String, resultSet: ResultSet) { + let outcome: QueryStatementOutcome + if let error = resultSet.errorMessage { + outcome = .failed(message: error) + } else if resultSet.isExplainResult { + outcome = .plan + } else if resultSet.resultColumns.isEmpty { + outcome = .affectedRows(resultSet.rowsAffected) + } else { + outcome = .returnedRows(resultSet.tableRows.count) + } + self.init( + statement: statement, + outcome: outcome, + executionTime: resultSet.executionTime, + statusMessage: resultSet.statusMessage, + serverOutput: resultSet.serverOutput, + resultSetId: resultSet.id + ) + } + + /// A statement that ran in a run whose results were not installed, so it points at no result. + init(statement: String, result: QueryResult) { + self.init( + statement: statement, + outcome: result.columns.isEmpty ? .affectedRows(result.rowsAffected) : .returnedRows(result.rows.count), + executionTime: result.executionTime, + statusMessage: result.statusMessage, + serverOutput: result.serverOutput + ) + } + + static func failed(_ statement: String, message: String, resultSetId: UUID? = nil) -> Self { + QueryRunLogEntry(statement: statement, outcome: .failed(message: message), resultSetId: resultSetId) + } + + static func cancelled(_ statement: String) -> Self { + QueryRunLogEntry(statement: statement, outcome: .cancelled) + } +} + +/// How a run that sends its statements or batches one at a time ended. +enum QueryRunEnding: Equatable { + case completed + /// `statement` is nil when the run failed outside any statement: the connection, the transaction's start or its commit. + case failed(statement: String?, message: String, resultSetId: UUID?) + /// Stopped, or ended by something other than its own completion, before the next statement finished. + case stopped +} + +/// What the last run in a query tab did, statement by statement. Kept on the tab in memory and replaced by each run. +struct QueryRunLog: Equatable, Sendable { + /// When the run's claim was taken, so a run that ends late never covers the log of one that started after it. + let startedAt: ContinuousClock.Instant + let entries: [QueryRunLogEntry] + /// A note about the run as a whole, such as a transaction it left open. + let notice: String? + + init(startedAt: ContinuousClock.Instant, entries: [QueryRunLogEntry], notice: String? = nil) { + self.startedAt = startedAt + self.entries = entries.enumerated().map { index, entry in + var numbered = entry + numbered.ordinal = index + 1 + return numbered + } + self.notice = notice?.isEmpty == true ? nil : notice + } + + /// The Message tab is the answer when the run failed, stopped or returned no rows to look at. Otherwise + /// the result the run made active stays in front, as it does with the tabs off. + var opensOnMessage: Bool { + let interrupted = entries.contains { entry in + switch entry.outcome { + case .failed, .cancelled: return true + case .returnedRows, .affectedRows, .plan: return false + } + } + guard !interrupted else { return true } + return !entries.contains { entry in + switch entry.outcome { + case .returnedRows, .plan: return entry.resultSetId != nil + case .affectedRows, .failed, .cancelled: return false + } + } + } + + func resultSetId(ofEntry ordinal: Int) -> UUID? { + entries.first { $0.ordinal == ordinal }?.resultSetId + } + + /// A re-read swaps a result for a new one under the same tab, so the entry that produced it follows. + func replacingResult(_ outgoingId: UUID, with incomingId: UUID) -> QueryRunLog { + guard entries.contains(where: { $0.resultSetId == outgoingId }) else { return self } + let moved = entries.map { entry in + guard entry.resultSetId == outgoingId else { return entry } + var copy = entry + copy.resultSetId = incomingId + return copy + } + return QueryRunLog(startedAt: startedAt, entries: moved, notice: notice) + } + + /// The entries of a run that sends `statements` one at a time, of which `finished` ran to the end in order. + /// A stop names the statement it interrupted; the statements after it never ran and are left out. + static func entries( + statements: [String], + finished: [QueryRunLogEntry], + ending: QueryRunEnding + ) -> [QueryRunLogEntry] { + switch ending { + case .completed: + return finished + case let .failed(statement, message, resultSetId): + return finished + [.failed(statement ?? "", message: message, resultSetId: resultSetId)] + case .stopped: + guard statements.indices.contains(finished.count) else { return finished } + return finished + [.cancelled(statements[finished.count])] + } + } +} + +// MARK: - Text + +extension QueryRunLog { + static let statementCharacterLimit = 200 + private static let indent = " " + + /// The Message tab's text: each statement, what it came to, what it printed and how long it took. + var messageText: String { + var blocks = entries.map(Self.messageBlock(for:)) + if let notice { + blocks.append(notice) + } + return blocks.joined(separator: "\n\n") + } + + private static func messageBlock(for entry: QueryRunLogEntry) -> String { + var lines: [String] = [] + let statement = displayStatement(entry.statement) + lines.append(statement.isEmpty ? "[\(entry.ordinal)]" : "[\(entry.ordinal)] \(statement)") + lines += indented(outcomeText(for: entry)) + if let status = entry.statusMessage, !status.isEmpty, status != outcomeText(for: entry) { + lines += indented(status) + } + lines += entry.serverOutput.lines.map { indent + $0 } + if entry.serverOutput.isTruncated { + lines.append(indent + String(localized: "The output was cut short.")) + } + if let time = entry.executionTime { + lines.append(indent + timeText(time)) + } + return lines.joined(separator: "\n") + } + + private static func indented(_ text: String) -> [String] { + text.components(separatedBy: .newlines).map { indent + $0 } + } + + /// One line, with runs of whitespace collapsed and a long statement cut short. + static func displayStatement(_ statement: String) -> String { + let collapsed = statement + .split(whereSeparator: { $0.isWhitespace }) + .joined(separator: " ") + return ResultSetMenuModel.truncated(collapsed, limit: statementCharacterLimit) + } + + static func outcomeText(for entry: QueryRunLogEntry) -> String { + switch entry.outcome { + case .returnedRows(let count): + return String(format: String(localized: "%lld row(s) returned"), Int64(count)) + case .affectedRows(let count): + if count == 0, let status = entry.statusMessage, !status.isEmpty { + return status + } + guard count > 0 else { return String(localized: "OK") } + return String(format: String(localized: "OK, %lld row(s) affected"), Int64(count)) + case .plan: + return String(localized: "Query plan returned") + case .failed(let message): + return String(format: String(localized: "Error: %@"), message) + case .cancelled: + return String(localized: "Cancelled") + } + } + + static func statusText(for outcome: QueryStatementOutcome) -> String { + switch outcome { + case .returnedRows, .affectedRows, .plan: + return String(localized: "OK") + case .failed: + return String(localized: "Error") + case .cancelled: + return String(localized: "Cancelled") + } + } + + /// Rows returned or affected, as the Summary's Rows column shows them. Nil when the statement reported neither. + static func rowCount(for outcome: QueryStatementOutcome) -> Int? { + switch outcome { + case .returnedRows(let count), .affectedRows(let count): + return count + case .plan, .failed, .cancelled: + return nil + } + } + + static func timeText(_ time: TimeInterval) -> String { + String(format: "%.3fs", time) + } +} + +/// Which page of a query tab's results pane is in front while the Message and Summary tabs are on. +enum ResultsPage: Equatable, Sendable { + case message + case summary + case result +} diff --git a/apple/TablePro/Models/Query/QueryTabState.swift b/apple/TablePro/Models/Query/QueryTabState.swift index a2522643f0..9a8cac7602 100644 --- a/apple/TablePro/Models/Query/QueryTabState.swift +++ b/apple/TablePro/Models/Query/QueryTabState.swift @@ -683,6 +683,10 @@ struct TabDisplayState: Equatable { var resultSets: [ResultSet] = [] var activeResultSetId: UUID? var highlightRulesPresentationRequest: Int = 0 + // What the last run did, statement by statement, for the Message and Summary tabs. Never saved. + var runLog: QueryRunLog? + // The page in front while those tabs are on. Off, the pane always shows the active result. + var resultsPage: ResultsPage = .result var activeResultSet: ResultSet? { guard let id = activeResultSetId else { return resultSets.last } @@ -708,9 +712,21 @@ struct TabDisplayState: Equatable { result.isPinned = resultSets[index].isPinned resultSets[index] = result activeResultSetId = result.id + runLog = runLog?.replacingResult(outgoingId, with: result.id) leaveOutputModeWithoutOutput() } + // A run that ends after a later one started has nothing to say about what is on screen now. + func admitsRunLog(_ log: QueryRunLog) -> Bool { + runLog.map { $0.startedAt <= log.startedAt } ?? true + } + + mutating func installRunLog(_ log: QueryRunLog) { + guard admitsRunLog(log) else { return } + runLog = log + resultsPage = log.opensOnMessage ? .message : .result + } + @MainActor mutating func replaceActiveServerOutput(_ output: PluginServerOutput) { activeResultSet?.serverOutput = output @@ -758,5 +774,7 @@ struct TabDisplayState: Equatable { && lhs.resultSets.map(\.id) == rhs.resultSets.map(\.id) && lhs.activeResultSetId == rhs.activeResultSetId && lhs.highlightRulesPresentationRequest == rhs.highlightRulesPresentationRequest + && lhs.runLog == rhs.runLog + && lhs.resultsPage == rhs.resultsPage } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift index 91c45884d3..180ef373f0 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift @@ -199,6 +199,7 @@ extension MainContentCoordinator { } seedBufferFromActiveResult(tabId: tabId) toolbarState.isResultsCollapsed = false + queryExecutionCoordinator.recordStatementRun(request.sql, tabId: tabId, startedAt: claim.startedAt) recordHistory( QueryHistoryRecordRequest( @@ -252,6 +253,7 @@ extension MainContentCoordinator { toolbarState.isResultsCollapsed = false announceQueryError(error.localizedDescription) } + queryExecutionCoordinator.recordStatementFailure(request.sql, error: error, tabId: tabId, startedAt: claim.startedAt) recordHistory( QueryHistoryRecordRequest( diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift index 45e6d2c25f..b1f692ee26 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift @@ -54,9 +54,14 @@ extension MainContentCoordinator { isAutoLoad: Bool, trigger: TableLoadTrigger, traceToken: TableLoadTraceToken?, - serverOutput: PluginServerOutput = .none + serverOutput: PluginServerOutput = .none, + recordsRun: Bool = false ) { guard tabExecution.settle(claim) else { + // Stop ends the claim before the statement unwinds, so a stopped run reports itself here. + if recordsRun { + queryExecutionCoordinator.recordStatementCancelled(sql, tabId: tabId, startedAt: claim.startedAt) + } traceStaleResultDropped(traceToken) return } @@ -73,6 +78,9 @@ extension MainContentCoordinator { reportEndedExecutions([ EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) ]) + if recordsRun { + queryExecutionCoordinator.recordStatementCancelled(sql, tabId: tabId, startedAt: claim.startedAt) + } return } if isAutoLoad, services.databaseManager.driver(for: connectionId)?.status != .connected { @@ -80,6 +88,9 @@ extension MainContentCoordinator { return } handleQueryExecutionError(error, sql: sql, tabId: tabId, connection: conn, serverOutput: serverOutput) + if recordsRun { + queryExecutionCoordinator.recordStatementFailure(sql, error: error, tabId: tabId, startedAt: claim.startedAt) + } reportQueryOperation( claim: claim, trigger: trigger, outcome: .failed(reason: error.localizedDescription) ) diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 9794459937..d64d6c8edc 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -1240,6 +1240,7 @@ final class MainContentCoordinator: ObservableObject { return } let isTableTab = tab.tabType == .table + let recordsRun = source == .newSource && tab.tabType == .query && !isAutoLoad let readsView = tab.tableContext.knowsView(named: tableName) let (grammar, lengthColumns) = (lexicalGrammar, unloadedValueLengthColumns(for: tab)) @@ -1333,6 +1334,10 @@ final class MainContentCoordinator: ObservableObject { absentCells: fetchResult.absentCells, unloadedCells: fetchResult.unloadedCells ) + // A re-read (a sort, a reload after a write) is not a run, so the log keeps describing the last one. + if recordsRun { + queryExecutionCoordinator.recordStatementRun(sql, tabId: tabId, startedAt: claim.startedAt) + } scheduleTraceCompletion(traceToken, outcome: .completed) reportFetchedQuery(claim: claim, trigger: trigger, result: fetchResult) @@ -1369,7 +1374,8 @@ final class MainContentCoordinator: ObservableObject { isAutoLoad: isAutoLoad, trigger: trigger, traceToken: traceToken, - serverOutput: failureOutput.output + serverOutput: failureOutput.output, + recordsRun: recordsRun ) } } diff --git a/apple/TableProTests/Models/Query/QueryRunLogTests.swift b/apple/TableProTests/Models/Query/QueryRunLogTests.swift new file mode 100644 index 0000000000..d9998666fd --- /dev/null +++ b/apple/TableProTests/Models/Query/QueryRunLogTests.swift @@ -0,0 +1,319 @@ +// +// QueryRunLogTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct QueryRunLogTests { + private static let select = "SELECT id, name FROM users" + private static let update = "UPDATE orders SET status = 'paid'" + private static let failing = "SELECT * FROM nope" + private static let later = "DELETE FROM sessions" + private static let script = [select, update, failing, later] + + private func rowsResult(rowCount: Int, time: TimeInterval = 0.012) -> ResultSet { + let rows = TableRows.from( + queryRows: (0 ..< rowCount).map { [PluginCellValue.text("\($0)"), .text("name \($0)")] }, + columns: ["id", "name"], + columnTypes: [.text(rawType: nil), .text(rawType: nil)] + ) + let result = ResultSet(label: "users", tableRows: rows) + result.executionTime = time + return result + } + + private func countResult(affected: Int, status: String? = nil) -> ResultSet { + let result = ResultSet(label: "UPDATE orders") + result.rowsAffected = affected + result.statusMessage = status + result.executionTime = 0.004 + return result + } + + @Test("A run that failed lists what ran, then the failure, and leaves out what never ran") + func failedRunListsEachStatement() { + let rows = rowsResult(rowCount: 3) + let count = countResult(affected: 12) + let errorId = UUID() + let finished = [ + QueryRunLogEntry(statement: Self.select, resultSet: rows), + QueryRunLogEntry(statement: Self.update, resultSet: count), + ] + + let log = QueryRunLog( + startedAt: .now, + entries: QueryRunLog.entries( + statements: Self.script, + finished: finished, + ending: .failed(statement: Self.failing, message: "relation \"nope\" does not exist", resultSetId: errorId) + ) + ) + + #expect(log.entries.map(\.ordinal) == [1, 2, 3]) + #expect(log.entries.map(\.statement) == [Self.select, Self.update, Self.failing]) + #expect(log.entries.map(\.outcome) == [ + .returnedRows(3), + .affectedRows(12), + .failed(message: "relation \"nope\" does not exist"), + ]) + #expect(log.entries.map(\.resultSetId) == [rows.id, count.id, errorId]) + #expect(log.entries.first?.executionTime == 0.012) + } + + @Test("A stopped run names the statement it interrupted as cancelled and leaves out the rest") + func stoppedRunNamesTheInterruptedStatement() { + let finished = [ + QueryRunLogEntry(statement: Self.select, resultSet: rowsResult(rowCount: 2)), + QueryRunLogEntry(statement: Self.update, resultSet: countResult(affected: 1)), + ] + + let entries = QueryRunLog.entries(statements: Self.script, finished: finished, ending: .stopped) + + #expect(entries.map(\.statement) == [Self.select, Self.update, Self.failing]) + #expect(entries.last?.outcome == .cancelled) + #expect(entries.last?.resultSetId == nil) + } + + @Test("A run stopped after its last statement finished lists only what ran") + func stopAfterTheLastStatementAddsNothing() { + let finished = [QueryRunLogEntry(statement: Self.select, resultSet: rowsResult(rowCount: 1))] + + #expect(QueryRunLog.entries(statements: [Self.select], finished: finished, ending: .stopped) == finished) + #expect(QueryRunLog.entries(statements: [Self.select], finished: finished, ending: .completed) == finished) + } + + @Test("A failure outside any statement still gets an entry") + func failureWithoutAStatement() { + let entries = QueryRunLog.entries( + statements: Self.script, + finished: [], + ending: .failed(statement: nil, message: "Connection reset", resultSetId: nil) + ) + + #expect(entries == [.failed("", message: "Connection reset")]) + } + + @Test("A statement whose results were not installed reads its counts from the driver's result") + func driverResultEntry() { + let returned = QueryResult( + columns: ["id"], columnTypes: [.integer(rawType: nil)], rows: [[.text("1")], [.text("2")]], + rowsAffected: 0, executionTime: 0.5, error: nil + ) + let written = QueryResult(columns: [], columnTypes: [], rows: [], rowsAffected: 7, executionTime: 0.1, error: nil) + + #expect(QueryRunLogEntry(statement: Self.select, result: returned).outcome == .returnedRows(2)) + #expect(QueryRunLogEntry(statement: Self.update, result: written).outcome == .affectedRows(7)) + #expect(QueryRunLogEntry(statement: Self.update, result: written).resultSetId == nil) + } + + @Test("An empty row set is still rows returned, an error result is a failure and a plan is a plan") + func outcomeFromResultSet() { + let empty = rowsResult(rowCount: 0) + let failed = ResultSet(label: "Error") + failed.errorMessage = "boom" + let plan = ResultSet(label: "Plan") + plan.explainRawText = "Seq Scan on users" + + #expect(QueryRunLogEntry(statement: Self.select, resultSet: empty).outcome == .returnedRows(0)) + #expect(QueryRunLogEntry(statement: Self.failing, resultSet: failed).outcome == .failed(message: "boom")) + #expect(QueryRunLogEntry(statement: "EXPLAIN SELECT 1", resultSet: plan).outcome == .plan) + } + + // MARK: - Summary + + @Test("Each Summary row maps to the result its statement produced") + func summaryRowsMapToResults() { + let first = rowsResult(rowCount: 5) + let second = countResult(affected: 2) + let third = rowsResult(rowCount: 0) + let log = QueryRunLog(startedAt: .now, entries: [ + QueryRunLogEntry(statement: Self.select, resultSet: first), + QueryRunLogEntry(statement: Self.update, resultSet: second), + QueryRunLogEntry(statement: Self.select, resultSet: third), + ]) + + #expect(log.resultSetId(ofEntry: 1) == first.id) + #expect(log.resultSetId(ofEntry: 2) == second.id) + #expect(log.resultSetId(ofEntry: 3) == third.id) + #expect(log.resultSetId(ofEntry: 4) == nil) + #expect(log.entries.map { QueryRunLog.rowCount(for: $0.outcome) } == [5, 2, 0]) + #expect(log.entries.map { QueryRunLog.statusText(for: $0.outcome) } == ["OK", "OK", "OK"]) + } + + @Test("Status and rows for a failure and a stop") + func summaryForFailureAndStop() { + #expect(QueryRunLog.statusText(for: .failed(message: "x")) == "Error") + #expect(QueryRunLog.statusText(for: .cancelled) == "Cancelled") + #expect(QueryRunLog.rowCount(for: .failed(message: "x")) == nil) + #expect(QueryRunLog.rowCount(for: .cancelled) == nil) + #expect(QueryRunLog.rowCount(for: .plan) == nil) + } + + @Test("A re-read result keeps its Summary row pointing at it") + func rereadKeepsTheMapping() { + let outgoing = UUID() + let incoming = UUID() + let other = UUID() + let log = QueryRunLog(startedAt: .now, entries: [ + QueryRunLogEntry(statement: Self.select, outcome: .returnedRows(1), resultSetId: outgoing), + QueryRunLogEntry(statement: Self.update, outcome: .affectedRows(1), resultSetId: other), + ]) + + let moved = log.replacingResult(outgoing, with: incoming) + + #expect(moved.entries.map(\.resultSetId) == [incoming, other]) + #expect(moved.startedAt == log.startedAt) + } + + // MARK: - Message + + @Test("The message log gives each statement, its outcome, its output and its time, in order") + func messageTextListsEveryStatement() { + let rows = rowsResult(rowCount: 120) + let count = countResult(affected: 12) + count.serverOutput = PluginServerOutput(lines: ["NOTICE: trigger fired"], isTruncated: false) + let log = QueryRunLog( + startedAt: .now, + entries: QueryRunLog.entries( + statements: Self.script, + finished: [ + QueryRunLogEntry(statement: Self.select, resultSet: rows), + QueryRunLogEntry(statement: Self.update, resultSet: count), + ], + ending: .stopped + ), + notice: "The open transaction was not committed." + ) + + let lines = log.messageText.components(separatedBy: "\n") + + #expect(lines == [ + "[1] SELECT id, name FROM users", + " 120 row(s) returned", + " 0.012s", + "", + "[2] UPDATE orders SET status = 'paid'", + " OK, 12 row(s) affected", + " NOTICE: trigger fired", + " 0.004s", + "", + "[3] SELECT * FROM nope", + " Cancelled", + "", + "The open transaction was not committed.", + ]) + } + + @Test("A failure's message keeps its lines, indented under the statement") + func failureMessageIsIndented() { + let log = QueryRunLog(startedAt: .now, entries: [ + .failed(Self.failing, message: "Statement 3/4 failed: boom\nOutput before the error:\nline"), + ]) + + #expect(log.messageText == """ + [1] SELECT * FROM nope + Error: Statement 3/4 failed: boom + Output before the error: + line + """) + } + + @Test("A statement with no rows affected shows the server's status, or OK") + func zeroAffectedShowsStatus() { + let withStatus = QueryRunLogEntry(statement: "CREATE TABLE t (id int)", outcome: .affectedRows(0), statusMessage: "CREATE TABLE") + let plain = QueryRunLogEntry(statement: "SET x = 1", outcome: .affectedRows(0)) + + #expect(QueryRunLog.outcomeText(for: withStatus) == "CREATE TABLE") + #expect(QueryRunLog.outcomeText(for: plain) == "OK") + #expect(QueryRunLog(startedAt: .now, entries: [withStatus]).messageText == "[1] CREATE TABLE t (id int)\n CREATE TABLE") + } + + @Test("A long statement is shortened to one line") + func longStatementIsShortened() { + let statement = "SELECT\n id,\n\tname\nFROM users " + #expect(QueryRunLog.displayStatement(statement) == "SELECT id, name FROM users") + + let long = "SELECT " + String(repeating: "column_name, ", count: 40) + "1" + let shown = QueryRunLog.displayStatement(long) + #expect(shown.count == QueryRunLog.statementCharacterLimit + 1) + #expect(shown.hasSuffix("…")) + } + + // MARK: - Page after a run + + @Test("The Message tab comes forward when a statement failed, the run stopped, or nothing returned rows") + func pageAfterARun() { + let rows = QueryRunLogEntry(statement: Self.select, outcome: .returnedRows(3), resultSetId: UUID()) + let emptyRows = QueryRunLogEntry(statement: Self.select, outcome: .returnedRows(0), resultSetId: UUID()) + let write = QueryRunLogEntry(statement: Self.update, outcome: .affectedRows(2), resultSetId: UUID()) + let plan = QueryRunLogEntry(statement: "EXPLAIN SELECT 1", outcome: .plan, resultSetId: UUID()) + let notShown = QueryRunLogEntry(statement: Self.select, outcome: .returnedRows(3)) + + func opensOnMessage(_ entries: [QueryRunLogEntry]) -> Bool { + QueryRunLog(startedAt: .now, entries: entries).opensOnMessage + } + + #expect(opensOnMessage([rows, write]) == false) + #expect(opensOnMessage([emptyRows]) == false) + #expect(opensOnMessage([plan]) == false) + #expect(opensOnMessage([write]) == true) + #expect(opensOnMessage([write, write]) == true) + #expect(opensOnMessage([rows, .failed(Self.failing, message: "boom")]) == true) + #expect(opensOnMessage([rows, .cancelled(Self.update)]) == true) + #expect(opensOnMessage([notShown]) == true) + } + + @Test("Installing a log brings the page the run calls for to the front") + func installChoosesThePage() { + var display = TabDisplayState() + let later = ContinuousClock.now + let earlier = later - .seconds(1) + + display.installRunLog(QueryRunLog(startedAt: earlier, entries: [ + QueryRunLogEntry(statement: Self.select, outcome: .returnedRows(1), resultSetId: UUID()), + ])) + #expect(display.resultsPage == .result) + + display.installRunLog(QueryRunLog(startedAt: later, entries: [.failed(Self.failing, message: "boom")])) + #expect(display.resultsPage == .message) + #expect(display.runLog?.entries.first?.outcome == .failed(message: "boom")) + } + + @Test("A run that ends after a later one started does not cover the later run's log") + func olderRunIsRefused() { + var display = TabDisplayState() + let later = ContinuousClock.now + let earlier = later - .seconds(1) + let newer = QueryRunLog(startedAt: later, entries: [ + QueryRunLogEntry(statement: Self.select, outcome: .returnedRows(1), resultSetId: UUID()), + ]) + display.installRunLog(newer) + + let stale = QueryRunLog(startedAt: earlier, entries: [.cancelled(Self.update)]) + #expect(display.admitsRunLog(stale) == false) + display.installRunLog(stale) + + #expect(display.runLog == newer) + #expect(display.resultsPage == .result) + } + + @Test("Replacing a result in place moves the log's pointer to the new one") + func replaceResultMovesTheLogPointer() { + var display = TabDisplayState() + let original = rowsResult(rowCount: 1) + display.replaceUnpinnedResults(with: [original]) + display.installRunLog(QueryRunLog(startedAt: .now, entries: [ + QueryRunLogEntry(statement: Self.select, resultSet: original), + ])) + + let reread = rowsResult(rowCount: 2) + display.replaceResult(original.id, with: reread) + + #expect(display.runLog?.entries.first?.resultSetId == reread.id) + } +} diff --git a/apple/TableProTests/Views/Main/QueryRunLogRecordingTests.swift b/apple/TableProTests/Views/Main/QueryRunLogRecordingTests.swift new file mode 100644 index 0000000000..46e20c13fa --- /dev/null +++ b/apple/TableProTests/Views/Main/QueryRunLogRecordingTests.swift @@ -0,0 +1,195 @@ +// +// QueryRunLogRecordingTests.swift +// TableProTests +// +// Each run path records what its statements came to beside the results it installs, without +// changing which results it installs. +// + +import Foundation +import TableProPluginKit +import TableProSQLGrammar +import TableProTestSupport +import Testing + +@testable import TablePro + +@MainActor +struct QueryRunLogRecordingTests { + @MainActor + private final class Harness { + let connection: DatabaseConnection + let tabManager = QueryTabManager() + let coordinator: MainContentCoordinator + let tabId: UUID + + init(driver: (DatabaseConnection) -> any DatabaseDriver, query: String = "") { + connection = TestFixtures.makeConnection() + var session = ConnectionSession(connection: connection, driver: driver(connection)) + session.status = .connected + session.browseDatabase = connection.database + DatabaseManager.shared.injectSession(session, for: connection.id) + coordinator = MainContentCoordinator( + connection: connection, + tabManager: tabManager, + changeManager: DataChangeManager(), + toolbarState: ConnectionToolbarState() + ) + let tab = QueryTab(title: "Query", query: query, tabType: .query) + tabManager.tabs.append(tab) + tabManager.selectedTabId = tab.id + tabId = tab.id + } + + var tab: QueryTab? { + tabManager.tabs.first { $0.id == tabId } + } + + func runStatements(_ script: String) { + coordinator.queryExecutionCoordinator.executeMultipleStatementsWithParameters( + SQLStatementScanner.executableStatements(in: script), + parameters: [] + ) + } + + func settled() async throws { + try await waitUntil { [self] in + !coordinator.tabExecution.isExecuting(tabId) && tab?.display.runLog != nil + } + } + + func tearDown() { + coordinator.cancelAllQueryTasks() + coordinator.teardown() + DatabaseManager.shared.removeSession(for: connection.id) + } + } + + private static func answering(_ connection: DatabaseConnection) -> ScriptAnsweringDriver { + ScriptAnsweringDriver(connection: connection, sendsBatchesWhole: false, statementAnswer: { sql in + guard sql.uppercased().hasPrefix("UPDATE") else { + return ScriptAnsweringDriver.resultSet(columns: ["id"], rows: [["1"], ["2"]]) + } + return QueryResult(columns: [], columnTypes: [], rows: [], rowsAffected: 3, executionTime: 0, error: nil) + }) + } + + private static func failing(_ connection: DatabaseConnection) -> MockDatabaseDriver { + let driver = MockDatabaseDriver(connection: connection) + driver.failsStatementContaining = ( + "nope", + NSError(domain: "test", code: 1, userInfo: [NSLocalizedDescriptionKey: "relation \"nope\" does not exist"]) + ) + return driver + } + + @Test("A run of a SELECT and an UPDATE logs both, each pointing at its result, and keeps today's result in front") + func mixedRunLogsEachStatement() async throws { + let harness = Harness(driver: Self.answering) + defer { harness.tearDown() } + + harness.runStatements("SELECT id FROM users;\nUPDATE orders SET paid = 1;") + try await harness.settled() + + let tab = try #require(harness.tab) + let log = try #require(tab.display.runLog) + #expect(log.entries.map(\.outcome) == [.returnedRows(2), .affectedRows(3)]) + #expect(log.entries.map(\.resultSetId) == tab.display.resultSets.map(\.id)) + #expect(log.entries.first?.statement.hasPrefix("SELECT id FROM users") == true) + #expect(tab.display.resultsPage == .result) + #expect(tab.display.activeResultSetId == tab.display.resultSets.last?.id) + } + + @Test("A script that fails logs the statement before it and the failure, and brings Message forward") + func failedScriptOpensOnMessage() async throws { + let harness = Harness(driver: Self.failing) + defer { harness.tearDown() } + + harness.runStatements("SELECT 1;\nSELECT * FROM nope;") + try await harness.settled() + + let tab = try #require(harness.tab) + let log = try #require(tab.display.runLog) + #expect(tab.display.resultSets.count == 2) + #expect(log.entries.count == 2) + #expect(log.entries.first?.resultSetId == tab.display.resultSets.first?.id) + #expect(log.entries.last?.outcome.isFailure == true) + #expect(log.entries.last?.statement.contains("nope") == true) + #expect(log.entries.last?.resultSetId == tab.display.resultSets.last?.id) + #expect(tab.display.resultsPage == .message) + } + + @Test("A single statement that fails logs the banner's message and brings Message forward") + func singleFailureIsLogged() async throws { + let harness = Harness(driver: Self.failing) + defer { harness.tearDown() } + + harness.coordinator.executeQueryInternal("SELECT * FROM nope") + try await harness.settled() + + let tab = try #require(harness.tab) + let message = try #require(tab.execution.errorMessage) + #expect(tab.display.runLog?.entries.map(\.outcome) == [.failed(message: message)]) + #expect(tab.display.resultsPage == .message) + } + + @Test("A single statement that returns rows logs one entry for its result, and a re-read of it starts no new log") + func singleRunAndReread() async throws { + let harness = Harness(driver: Self.answering) + defer { harness.tearDown() } + + harness.coordinator.executeQueryInternal("SELECT id FROM users") + try await harness.settled() + + let ran = try #require(harness.tab) + let log = try #require(ran.display.runLog) + let firstId = try #require(ran.display.activeResultSetId) + #expect(log.entries.map(\.outcome) == [.returnedRows(2)]) + #expect(log.entries.first?.resultSetId == firstId) + #expect(ran.display.resultsPage == .result) + + harness.coordinator.executeQueryInternal( + "SELECT id FROM users ORDER BY id", + source: .reread(RereadTarget( + tabId: harness.tabId, + resultId: firstId, + databaseName: ran.tableContext.databaseName, + schemaName: ran.tableContext.schemaName + )) + ) + try await waitUntil { + !harness.coordinator.tabExecution.isExecuting(harness.tabId) + && harness.tab?.display.activeResultSetId != firstId + } + + let reread = try #require(harness.tab) + #expect(reread.display.runLog?.startedAt == log.startedAt) + #expect(reread.display.runLog?.entries.first?.statement == "SELECT id FROM users") + #expect(reread.display.runLog?.entries.first?.resultSetId == reread.display.activeResultSetId) + } + + @Test("Stopping a run logs the statement it interrupted as cancelled and keeps the earlier results") + func stoppedRunIsLogged() async throws { + let harness = Harness(driver: { connection in + let driver = MockDatabaseDriver(connection: connection) + driver.executeDelaySeconds = 2 + return driver + }) + defer { harness.tearDown() } + let driver = try #require( + DatabaseManager.shared.driver(for: harness.connection.id) as? MockDatabaseDriver + ) + + harness.runStatements("UPDATE a SET x = 1;\nUPDATE b SET y = 2;") + try await waitUntil { driver.executedQueries.contains { $0.contains("UPDATE a") } } + harness.coordinator.stopExecution(for: harness.tabId) + try await harness.settled() + + let tab = try #require(harness.tab) + let log = try #require(tab.display.runLog) + #expect(log.entries.last?.outcome == .cancelled) + #expect(log.entries.allSatisfy { $0.resultSetId == nil }) + #expect(tab.display.resultSets.isEmpty) + #expect(tab.display.resultsPage == .message) + } +} From 638e9b1255f65a51f1924c4762a6de252cb43f28 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 15:31:38 +0700 Subject: [PATCH 110/123] feat(settings): add the Message and Summary tabs setting Settings > Editor gets "Show Message and Summary tabs above query results", off by default and off for settings saved before it existed. Use Navigator Layout turns it on and Use Standard Layout turns it off. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Models/Settings/EditorSettings.swift | 13 +++++++++++-- .../Settings/NavigatorLayoutPreset.swift | 5 ++++- .../Views/Settings/EditorSettingsView.swift | 5 +++++ .../Views/Settings/GeneralSettingsView.swift | 3 ++- .../Models/NavigatorLayoutPresetTests.swift | 5 ++++- .../Settings/SettingsFieldDecodingTests.swift | 18 ++++++++++++++++++ 6 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apple/TablePro/Models/Settings/EditorSettings.swift b/apple/TablePro/Models/Settings/EditorSettings.swift index fdf7cf58bf..21fc27b0ec 100644 --- a/apple/TablePro/Models/Settings/EditorSettings.swift +++ b/apple/TablePro/Models/Settings/EditorSettings.swift @@ -90,6 +90,9 @@ struct EditorSettings: Codable, Equatable { /// The query bar above the editor on two rows: Save, Query Builder, Format, Snippets and AI above /// the connection, the database and the run controls. Off keeps the single row. var queryBarTwoRows: Bool + /// Message, Summary and a tab per result above a query tab's results: what each statement of the last run did, + /// as a log and as a table. Off keeps the result tabs only, and only for two or more results. + var queryResultTabs: Bool static let `default` = EditorSettings( showLineNumbers: true, @@ -104,7 +107,8 @@ struct EditorSettings: Codable, Equatable { showStatementRunControls: true, showInvisibleCharacters: true, jsonViewerPreferredMode: .text, - queryBarTwoRows: false + queryBarTwoRows: false, + queryResultTabs: false ) init( @@ -120,7 +124,8 @@ struct EditorSettings: Codable, Equatable { showStatementRunControls: Bool = true, showInvisibleCharacters: Bool = true, jsonViewerPreferredMode: JSONViewMode = .text, - queryBarTwoRows: Bool = false + queryBarTwoRows: Bool = false, + queryResultTabs: Bool = false ) { self.showLineNumbers = showLineNumbers self.highlightCurrentLine = highlightCurrentLine @@ -135,6 +140,7 @@ struct EditorSettings: Codable, Equatable { self.showInvisibleCharacters = showInvisibleCharacters self.jsonViewerPreferredMode = jsonViewerPreferredMode self.queryBarTwoRows = queryBarTwoRows + self.queryResultTabs = queryResultTabs } init(from decoder: Decoder) throws { @@ -161,6 +167,7 @@ struct EditorSettings: Codable, Equatable { .jsonViewerPreferredMode, default: fallback.jsonViewerPreferredMode ) queryBarTwoRows = container.decodeSetting(.queryBarTwoRows, default: fallback.queryBarTwoRows) + queryResultTabs = container.decodeSetting(.queryResultTabs, default: fallback.queryResultTabs) } // Spelled out so `uppercaseKeywords` and `vimModeEnabled` stay on the wire after their properties became @@ -182,6 +189,7 @@ struct EditorSettings: Codable, Equatable { case showInvisibleCharacters case jsonViewerPreferredMode case queryBarTwoRows + case queryResultTabs } private static func decodeKeywordCase(from container: KeyedDecodingContainer) -> SQLKeywordCase { @@ -219,6 +227,7 @@ struct EditorSettings: Codable, Equatable { try container.encode(showInvisibleCharacters, forKey: .showInvisibleCharacters) try container.encode(jsonViewerPreferredMode, forKey: .jsonViewerPreferredMode) try container.encode(queryBarTwoRows, forKey: .queryBarTwoRows) + try container.encode(queryResultTabs, forKey: .queryResultTabs) } /// Clamped tab width (1-16) diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index eaaea953cb..a33a9f83f6 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -45,7 +45,8 @@ internal enum NavigatorLayoutPreset { /// The tabs' half of the layout: types under the column names, the sort and a Text mode in the /// filter panel, that panel open with each table, the result bar above the grid, tab titles that - /// name the database and connection, the query bar on two rows and colorful object icons. These + /// name the database and connection, the query bar on two rows, the Message and Summary tabs above + /// query results and colorful object icons. These /// live in the Data Grid, Tab, Editor and Appearance settings, so the caller passes those bindings /// beside the General one. internal static func applyDataView( @@ -60,6 +61,7 @@ internal enum NavigatorLayoutPreset { dataGrid.resultBarAtTop = true tabs.titleShowsLocation = true editor.queryBarTwoRows = true + editor.queryResultTabs = true appearance.objectIconStyle = .colorful } @@ -76,6 +78,7 @@ internal enum NavigatorLayoutPreset { dataGrid.resultBarAtTop = standardGrid.resultBarAtTop tabs.titleShowsLocation = TabSettings.default.titleShowsLocation editor.queryBarTwoRows = EditorSettings.default.queryBarTwoRows + editor.queryResultTabs = EditorSettings.default.queryResultTabs appearance.objectIconStyle = AppearanceSettings.default.objectIconStyle } diff --git a/apple/TablePro/Views/Settings/EditorSettingsView.swift b/apple/TablePro/Views/Settings/EditorSettingsView.swift index 6b7a83b58b..86ab2da582 100644 --- a/apple/TablePro/Views/Settings/EditorSettingsView.swift +++ b/apple/TablePro/Views/Settings/EditorSettingsView.swift @@ -26,6 +26,11 @@ struct EditorSettingsView: View { Puts Save, Query Builder, Format, Snippets and AI above the editor, and the connection, \ the database and the run controls on a second row. """)) + Toggle("Show Message and Summary tabs above query results", isOn: $settings.queryResultTabs) + .help(Text(""" + After a run, Message lists what each statement did and Summary puts the same in a table, \ + beside a tab for each result. + """)) } Section("Gutter") { diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 2184a31ca3..585e515aba 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -85,7 +85,8 @@ struct GeneralSettingsView: View { sidebar layout. In table tabs it shows column types in \ the header, the sort and a Text mode in the filter bar, opens that bar with each table, \ puts the result bar above the grid and names the database and connection in tab titles. \ - In query tabs it shows the query bar on two rows, and object icons turn colorful. \ + In query tabs it shows the query bar on two rows and Message and Summary tabs above the \ + results, and object icons turn colorful. \ Standard Layout turns them off again. Open connections switch layout too. """)) } diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index 69b2fe6c18..159fdcd549 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -105,7 +105,7 @@ struct NavigatorLayoutPresetTests { #expect(settings == before) } - @Test("Use Navigator Layout turns on the data view, the two-row query bar and colorful icons, and Standard Layout turns them off") + @Test("Use Navigator Layout turns on the data view, the two-row query bar, the run tabs and colorful icons, and Standard Layout turns them off") func dataViewFollowsTheButtons() { var tabs = TabSettings.default var grid = DataGridSettings.default @@ -120,6 +120,7 @@ struct NavigatorLayoutPresetTests { #expect(grid.resultBarAtTop) #expect(tabs.titleShowsLocation) #expect(editor.queryBarTwoRows) + #expect(editor.queryResultTabs) #expect(appearance.objectIconStyle == .colorful) NavigatorLayoutPreset.restoreDataView(tabs: &tabs, dataGrid: &grid, editor: &editor, appearance: &appearance) @@ -128,6 +129,7 @@ struct NavigatorLayoutPresetTests { #expect(tabs == TabSettings.default) #expect(editor == EditorSettings.default) #expect(!editor.queryBarTwoRows) + #expect(!editor.queryResultTabs) #expect(appearance == AppearanceSettings.default) } @@ -153,6 +155,7 @@ struct NavigatorLayoutPresetTests { #expect(grid.defaultPageSize == 250) var expectedEditor = editorBefore expectedEditor.queryBarTwoRows = true + expectedEditor.queryResultTabs = true #expect(editor == expectedEditor) #expect(appearance.objectIconStyle == .colorful) diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index eb35b1797a..8482971b10 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -117,6 +117,24 @@ struct SettingsFieldDecodingTests { #expect(decoded == chosen) } + @Test("Editor settings saved before the Message and Summary tabs keep them off, and the choice round-trips") + func queryResultTabsDefaultOff() throws { + let legacy = try decode(EditorSettings.self, #"{"wordWrap":true,"queryBarTwoRows":true}"#) + #expect(legacy.queryResultTabs == false) + #expect(legacy.queryBarTwoRows == true) + #expect(EditorSettings.default.queryResultTabs == false) + + let bad = try decode(EditorSettings.self, #"{"queryResultTabs":"yes","wordWrap":true}"#) + #expect(bad.queryResultTabs == false) + #expect(bad.wordWrap == true) + + var chosen = EditorSettings.default + chosen.queryResultTabs = true + let decoded = try decode(EditorSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.queryResultTabs == true) + #expect(decoded == chosen) + } + @Test("Data Grid settings saved before the result bar could move keep it below the grid") func resultBarAtTopDefaultsOff() throws { let legacy = try decode(DataGridSettings.self, #"{"showRowNumbers":false}"#) From 583277da89a4a3ba806d0ee6b0ef2b38a150d0c5 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 15:31:38 +0700 Subject: [PATCH 111/123] feat(results): show Message, Summary and Result tabs above query results With the setting on, a query tab's results pane opens with one tab row after its first run: Message, Summary, then a tab per result, with the result pull-down at the end. It takes the place of the result set tab row. Message is the last run as selectable monospaced text, Summary a table of each statement's status, rows and time, where double-clicking a row opens the result it produced. Message comes forward when a statement failed, the run stopped or nothing returned rows; otherwise the result the run made active stays in front. Each result page is the pane as it was. With the setting off the pane is unchanged: the result set tab row shows only for two or more results. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Query/QueryResultPresentation.swift | 20 +++ .../Models/Query/QueryRunTabStrip.swift | 71 ++++++++ .../Models/Query/ResultSetMenuModel.swift | 22 +++ .../Main/Child/MainEditorContentView.swift | 96 ++++++----- .../MainContentCoordinator+ResultsPage.swift | 48 ++++++ .../Views/Results/QueryRunPages.swift | 158 ++++++++++++++++++ .../Views/Results/QueryRunTabBar.swift | 155 +++++++++++++++++ .../Views/Results/ServerOutputTextView.swift | 7 +- .../Query/QueryResultPresentationTests.swift | 88 ++++++++++ .../Models/Query/QueryRunTabStripTests.swift | 71 ++++++++ .../Results/QueryRunTabBarLayoutTests.swift | 111 ++++++++++++ 11 files changed, 800 insertions(+), 47 deletions(-) create mode 100644 apple/TablePro/Models/Query/QueryRunTabStrip.swift create mode 100644 apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultsPage.swift create mode 100644 apple/TablePro/Views/Results/QueryRunPages.swift create mode 100644 apple/TablePro/Views/Results/QueryRunTabBar.swift create mode 100644 apple/TableProTests/Models/Query/QueryRunTabStripTests.swift create mode 100644 apple/TableProTests/Views/Results/QueryRunTabBarLayoutTests.swift diff --git a/apple/TablePro/Models/Query/QueryResultPresentation.swift b/apple/TablePro/Models/Query/QueryResultPresentation.swift index f099a8e232..15a1e8ec26 100644 --- a/apple/TablePro/Models/Query/QueryResultPresentation.swift +++ b/apple/TablePro/Models/Query/QueryResultPresentation.swift @@ -73,6 +73,10 @@ struct QueryResultInputs: Equatable { var hasAppliedFilters = false var isFilterPanelVisible = false var prefersStatusBarAtTop = false + // Settings > Editor's Message and Summary tabs. + var prefersRunTabs = false + var hasRunLog = false + var resultsPage: ResultsPage = .result } // Pure: every branch is decidable from `QueryResultInputs` alone, like `ResultStatusModel` and `ResultSetPolicy`. @@ -84,6 +88,10 @@ struct QueryResultPresentation: Equatable { let showsStatusBar: Bool let statusBarPlacement: StatusBarPlacement let showsErrorBanner: Bool + // Message, Summary and a tab per result, in place of the result set tab row. + let showsRunTabs: Bool + // Always `.result` while the run tabs are off, so the pane is the one it was before they existed. + let page: ResultsPage var showsResultSetSelector: Bool { resultSetChooser != .hidden } @@ -99,6 +107,14 @@ struct QueryResultPresentation: Equatable { showsStatusBar = true statusBarPlacement = inputs.prefersStatusBarAtTop ? .top : .bottom showsErrorBanner = Self.resolvedError(inputs) != nil + showsRunTabs = Self.resolvesRunTabs(inputs) + page = showsRunTabs ? inputs.resultsPage : .result + } + + // From the first run on, even with one result: the log is worth a tab whatever the run returned. + private static func resolvesRunTabs(_ inputs: QueryResultInputs) -> Bool { + guard inputs.prefersRunTabs, inputs.tabType == .query else { return false } + return inputs.hasRunLog || inputs.resultSetCount > 0 } // Same order as `QueryTab.shownError`: the tab's message is the newer failure. @@ -192,8 +208,12 @@ struct QueryResultPresentation: Equatable { } // One result still gets the pull-down: Pin, Unpin and Close live in its menu, and it costs no height inside the bar. + // With the run tabs on, the pull-down sits at the end of their row, whatever the count. private static func resolveResultSetChooser(_ inputs: QueryResultInputs) -> ResultSetChooserPlacement { guard inputs.tabType == .query, inputs.viewMode != .structure else { return .hidden } + if resolvesRunTabs(inputs) { + return inputs.resultSetCount > 0 ? .tabRow : .hidden + } switch inputs.resultSetCount { case 0: return .hidden case 1: return .statusBar diff --git a/apple/TablePro/Models/Query/QueryRunTabStrip.swift b/apple/TablePro/Models/Query/QueryRunTabStrip.swift new file mode 100644 index 0000000000..fbf1fd0eeb --- /dev/null +++ b/apple/TablePro/Models/Query/QueryRunTabStrip.swift @@ -0,0 +1,71 @@ +// +// QueryRunTabStrip.swift +// TablePro +// + +import Foundation + +/// The tab row above a query tab's results while the Message and Summary tabs are on: Message, Summary, then the +/// results. Pure, so which tab is lit and how the results fold is checked without mounting the control. +struct QueryRunTabStrip: Equatable { + enum Segment: Equatable { + case message + case summary + case result(ResultSetMenuEntry) + } + + let segments: [Segment] + /// -1 when no tab stands for the page in front, such as a result page with no results left. + let selectedIndex: Int + + /// `listsEachResult` false folds the results into one tab for the active result, and the pull-down at the end of + /// the row chooses which. The row folds when it is too narrow or the run made more results than tabs. + init(page: ResultsPage, results: ResultSetMenuModel, listsEachResult: Bool) { + let shown: [ResultSetMenuEntry] + if listsEachResult { + shown = results.entries + } else { + shown = (results.activeEntry ?? results.entries.last).map { [$0] } ?? [] + } + let segments = [Segment.message, .summary] + shown.map(Segment.result) + self.segments = segments + switch page { + case .message: + selectedIndex = 0 + case .summary: + selectedIndex = 1 + case .result: + selectedIndex = segments.firstIndex { segment in + guard case .result(let entry) = segment else { return false } + return entry.isActive + } ?? -1 + } + } + + /// HIG, Tab views: past six result tabs the pull-down alone lists them, as it does with the run tabs off. + static func canListEachResult(_ results: ResultSetMenuModel) -> Bool { + results.total <= ResultSetMenuModel.maximumTabCount + } + + static func title(of segment: Segment, in results: ResultSetMenuModel) -> String { + switch segment { + case .message: + return String(localized: "Message") + case .summary: + return String(localized: "Summary") + case .result(let entry): + return results.tabTitle(of: entry) + } + } + + static func toolTip(of segment: Segment, in results: ResultSetMenuModel) -> String { + switch segment { + case .message: + return String(localized: "What each statement of the last run did") + case .summary: + return String(localized: "Each statement of the last run, with its status, rows and time") + case .result(let entry): + return results.displayLabel(of: entry) + } + } +} diff --git a/apple/TablePro/Models/Query/ResultSetMenuModel.swift b/apple/TablePro/Models/Query/ResultSetMenuModel.swift index 65399f008e..14e2899d17 100644 --- a/apple/TablePro/Models/Query/ResultSetMenuModel.swift +++ b/apple/TablePro/Models/Query/ResultSetMenuModel.swift @@ -94,3 +94,25 @@ struct ResultSetMenuModel: Equatable { private static let compactTitleCharacterLimit = 16 private static let tabTitleCharacterLimit = 24 } + +extension ResultSetMenuModel { + /// The tab's results in order, the active one marked and numbered from 1. + @MainActor + init(resultSets: [ResultSet], activeId: UUID?, isComparable: (ResultSet) -> Bool) { + let entries = resultSets.enumerated().map { index, resultSet in + ResultSetMenuEntry( + id: resultSet.id, + label: resultSet.label, + isPinned: resultSet.isPinned, + isActive: resultSet.id == activeId, + ordinal: index + 1, + isComparable: isComparable(resultSet) + ) + } + self.init( + entries: entries, + activeOrdinal: entries.first(where: \.isActive)?.ordinal ?? entries.count, + total: entries.count + ) + } +} diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index d9d8a54579..f5ac6836d2 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -703,35 +703,53 @@ struct MainEditorContentView: View { let presentation = resultPresentation(for: tab, rows: rows) VStack(spacing: 0) { - if presentation.resultSetChooser == .tabRow { + if presentation.showsRunTabs { + QueryRunTabBar( + page: presentation.page, + results: resultSetEntriesModel(for: tab), + showsMenu: presentation.resultSetChooser == .tabRow, + actions: coordinator.runTabActions(forTab: tab.id) + ) + } else if presentation.resultSetChooser == .tabRow { ResultSetTabBar( model: resultSetMenuModel(for: tab, placedIn: .tabRow), - actions: resultSetActions(for: tab) + actions: coordinator.resultSetActions(forTab: tab.id) ) } - /// Above the error banner, so a failure appearing or being dismissed moves the grid and - /// never the bar. Below the result set tabs, which choose the result this bar describes. - if presentation.showsStatusBar(at: .top) { - statusBarSection(tab: tab, placement: .top) + if presentation.page == .result { + resultPage(tab: tab, rows: rows, presentation: presentation) + } else { + QueryRunPage(page: presentation.page, display: tab.display) { [coordinator, tabId = tab.id] in + coordinator.showRunResult($0, in: tabId) + } } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } - if presentation.showsErrorBanner { - executionErrorBanner(tab: tab) - } + @ViewBuilder + private func resultPage(tab: QueryTab, rows: TableRows, presentation: QueryResultPresentation) -> some View { + /// Above the error banner, so a failure appearing or being dismissed moves the grid and + /// never the bar. Below the result set tabs, which choose the result this bar describes. + if presentation.showsStatusBar(at: .top) { + statusBarSection(tab: tab, placement: .top) + } - if presentation.showsFilterChrome { - rowFilterChrome(tab: tab, rows: rows) - } + if presentation.showsErrorBanner { + executionErrorBanner(tab: tab) + } - resultContent(presentation.content, tab: tab, rows: rows) - .gridStandInBackground(isActive: presentation.content.standsInForGrid) + if presentation.showsFilterChrome { + rowFilterChrome(tab: tab, rows: rows) + } - if presentation.showsStatusBar(at: .bottom) { - statusBarSection(tab: tab, placement: .bottom) - } + resultContent(presentation.content, tab: tab, rows: rows) + .gridStandInBackground(isActive: presentation.content.standsInForGrid) + + if presentation.showsStatusBar(at: .bottom) { + statusBarSection(tab: tab, placement: .bottom) } - .frame(maxWidth: .infinity, maxHeight: .infinity) } private func statusBarSection(tab: QueryTab, placement: StatusBarPlacement) -> some View { @@ -870,9 +888,16 @@ struct MainEditorContentView: View { inputs.hasAppliedFilters = tab.filterState.hasAppliedFilters inputs.isFilterPanelVisible = tab.filterState.isVisible inputs.prefersStatusBarAtTop = settingsManager.dataGrid.resultBarAtTop + Self.fillRunTabInputs(&inputs, tab: tab, prefersRunTabs: settingsManager.editor.queryResultTabs) return QueryResultPresentation(inputs: inputs) } + private static func fillRunTabInputs(_ inputs: inout QueryResultInputs, tab: QueryTab, prefersRunTabs: Bool) { + inputs.prefersRunTabs = prefersRunTabs + inputs.hasRunLog = tab.display.runLog != nil + inputs.resultsPage = tab.display.resultsPage + } + // Filtering rebuilds and reruns the query, so a mode showing this panel gets filtered rows without knowing. @ViewBuilder private func rowFilterChrome(tab: QueryTab, rows: TableRows) -> some View { @@ -1058,29 +1083,19 @@ struct MainEditorContentView: View { isRefreshingSchema: schemaService.isRefreshing(connectionId: connectionId), viewMode: resultsViewModeBinding(for: tab), resultSetMenu: resultSetMenuModel(for: tab, placedIn: .statusBar), - resultSetActions: resultSetActions(for: tab), + resultSetActions: coordinator.resultSetActions(forTab: tab.id), onToggleFilters: { coordinator.toggleFilterPanel() }, onFetchAll: { coordinator.fetchAllRows() } ) } - private func resultSetActions(for tab: QueryTab) -> ResultSetActions { - let tabId = tab.id - return ResultSetActions( - activate: { coordinator.switchActiveResultSet(to: $0, in: tabId) }, - togglePin: { coordinator.togglePinResultSet(id: $0) }, - compare: { coordinator.compareResultSet(id: $0) }, - close: { coordinator.closeResultSet(id: $0) }, - closeOthers: { coordinator.closeOtherResultSets(keeping: $0) } - ) - } - // Only the three deciding fields, not a full `resultPresentation`, which would pull the whole row buffer for a row-free answer. private func resultSetChooser(for tab: QueryTab) -> ResultSetChooserPlacement { var selectorInputs = QueryResultInputs() selectorInputs.tabType = tab.tabType selectorInputs.viewMode = tab.display.resultsViewMode selectorInputs.resultSetCount = tab.display.resultSets.count + Self.fillRunTabInputs(&selectorInputs, tab: tab, prefersRunTabs: settingsManager.editor.queryResultTabs) return QueryResultPresentation(inputs: selectorInputs).resultSetChooser } @@ -1088,22 +1103,13 @@ struct MainEditorContentView: View { guard resultSetChooser(for: tab) == placement else { return ResultSetMenuModel(entries: [], activeOrdinal: 0, total: 0) } - let activeId = tab.display.activeResultSet?.id - let entries = tab.display.resultSets.enumerated().map { index, resultSet in - ResultSetMenuEntry( - id: resultSet.id, - label: resultSet.label, - isPinned: resultSet.isPinned, - isActive: resultSet.id == activeId, - ordinal: index + 1, - isComparable: coordinator.isComparable(resultSet, in: tab) - ) + return resultSetEntriesModel(for: tab) + } + + private func resultSetEntriesModel(for tab: QueryTab) -> ResultSetMenuModel { + ResultSetMenuModel(resultSets: tab.display.resultSets, activeId: tab.display.activeResultSet?.id) { + coordinator.isComparable($0, in: tab) } - return ResultSetMenuModel( - entries: entries, - activeOrdinal: entries.first(where: \.isActive)?.ordinal ?? entries.count, - total: entries.count - ) } private func resultsViewModeBinding(for tab: QueryTab) -> Binding { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultsPage.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultsPage.swift new file mode 100644 index 0000000000..c54046ae5e --- /dev/null +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultsPage.swift @@ -0,0 +1,48 @@ +// +// MainContentCoordinator+ResultsPage.swift +// TablePro +// + +import Foundation + +extension MainContentCoordinator { + /// The Message and Summary pages unmount the grid, so a cell being edited is committed first, as a view mode + /// switch commits it. + func showResultsPage(_ page: ResultsPage, in tabId: UUID) { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), tab.display.resultsPage != page else { return } + commitActiveGridEdit() + tabManager.mutate(tabId: tabId) { $0.display.resultsPage = page } + } + + /// A result chosen from the run tabs, their pull-down or a Summary row. The switch keeps its discard prompt. + func showRunResult(_ resultSetId: UUID, in tabId: UUID) { + showResultsPage(.result, in: tabId) + switchActiveResultSet(to: resultSetId, in: tabId) + } + + /// What the result tab row and the result pull-down do for one tab. + func resultSetActions(forTab tabId: UUID) -> ResultSetActions { + ResultSetActions( + activate: { [weak self] in self?.switchActiveResultSet(to: $0, in: tabId) }, + togglePin: { [weak self] in self?.togglePinResultSet(id: $0) }, + compare: { [weak self] in self?.compareResultSet(id: $0) }, + close: { [weak self] in self?.closeResultSet(id: $0) }, + closeOthers: { [weak self] in self?.closeOtherResultSets(keeping: $0) } + ) + } + + /// The same actions for the run tabs, where choosing a result also brings its page to the front. + func runTabActions(forTab tabId: UUID) -> QueryRunTabActions { + let resultActions = resultSetActions(forTab: tabId) + return QueryRunTabActions( + showPage: { [weak self] in self?.showResultsPage($0, in: tabId) }, + results: ResultSetActions( + activate: { [weak self] in self?.showRunResult($0, in: tabId) }, + togglePin: resultActions.togglePin, + compare: resultActions.compare, + close: resultActions.close, + closeOthers: resultActions.closeOthers + ) + ) + } +} diff --git a/apple/TablePro/Views/Results/QueryRunPages.swift b/apple/TablePro/Views/Results/QueryRunPages.swift new file mode 100644 index 0000000000..e966287733 --- /dev/null +++ b/apple/TablePro/Views/Results/QueryRunPages.swift @@ -0,0 +1,158 @@ +// +// QueryRunPages.swift +// TablePro +// + +import SwiftUI + +/// The Message or Summary page of a query tab's results pane. +struct QueryRunPage: View { + let page: ResultsPage + let display: TabDisplayState + let onShowResult: (UUID) -> Void + + var body: some View { + Group { + if page == .summary { + QueryRunSummaryView( + log: display.runLog, + openableResultIds: Set(display.resultSets.map(\.id)), + onShowResult: onShowResult + ) + } else { + QueryRunMessageView(log: display.runLog) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +/// The Message tab: the last run as selectable monospaced text, one block per statement. +struct QueryRunMessageView: View { + let log: QueryRunLog? + + var body: some View { + if let log { + ServerOutputTextView( + text: log.messageText, + accessibilityLabel: String(localized: "Messages"), + accessibilityIdentifier: "query-run-messages" + ) + } else { + QueryRunEmptyView() + } + } +} + +/// The Summary tab: one row per statement of the last run. Double-clicking a row whose statement produced a result +/// still on the tab opens that result. +struct QueryRunSummaryView: View { + let log: QueryRunLog? + /// The results still on the tab, so a row whose result was closed does not offer to open it. + let openableResultIds: Set + let onShowResult: (UUID) -> Void + + @State private var selection: Set = [] + + private static let numberTitle = "#" + + var body: some View { + if let log { + table(log) + } else { + QueryRunEmptyView() + } + } + + private func table(_ log: QueryRunLog) -> some View { + Table(log.entries, selection: $selection) { + TableColumn(Self.numberTitle) { entry in + Text(entry.ordinal, format: .number) + .monospacedDigit() + } + .width(min: 24, ideal: 32, max: 56) + + TableColumn(String(localized: "Query")) { entry in + Text(QueryRunLog.displayStatement(entry.statement)) + .lineLimit(1) + .truncationMode(.tail) + .help(entry.statement) + } + .width(min: 120, ideal: 360) + + TableColumn(String(localized: "Status")) { entry in + statusLabel(entry.outcome) + } + .width(min: 64, ideal: 88, max: 140) + + TableColumn(String(localized: "Rows")) { entry in + Text(QueryRunLog.rowCount(for: entry.outcome).map { String($0) } ?? "") + .monospacedDigit() + } + .width(min: 40, ideal: 72, max: 120) + + TableColumn(String(localized: "Time")) { entry in + Text(entry.executionTime.map(QueryRunLog.timeText) ?? "") + .monospacedDigit() + } + .width(min: 48, ideal: 72, max: 120) + } + .contextMenu(forSelectionType: QueryRunLogEntry.ID.self) { ordinals in + Button(String(localized: "Show Result")) { + if let id = openableResult(in: log, among: ordinals) { onShowResult(id) } + } + .disabled(openableResult(in: log, among: ordinals) == nil) + Button(String(localized: "Copy Statement")) { + copyStatements(in: log, among: ordinals) + } + .disabled(ordinals.isEmpty) + } primaryAction: { ordinals in + if let id = openableResult(in: log, among: ordinals) { onShowResult(id) } + } + .accessibilityIdentifier("query-run-summary") + } + + private func statusLabel(_ outcome: QueryStatementOutcome) -> some View { + HStack(spacing: 4) { + switch outcome { + case .returnedRows, .affectedRows, .plan: + Image(systemName: "checkmark.circle.fill").foregroundStyle(.green) + case .failed: + Image(systemName: "xmark.octagon.fill").foregroundStyle(.red) + case .cancelled: + Image(systemName: "stop.circle.fill").foregroundStyle(.orange) + } + Text(QueryRunLog.statusText(for: outcome)) + } + .help(Self.statusHelp(outcome)) + } + + private static func statusHelp(_ outcome: QueryStatementOutcome) -> String { + guard case .failed(let message) = outcome else { return QueryRunLog.statusText(for: outcome) } + return message + } + + // Of the rows acted on, the first whose result is still on the tab. + private func openableResult(in log: QueryRunLog, among ordinals: Set) -> UUID? { + log.entries + .filter { ordinals.contains($0.ordinal) } + .compactMap(\.resultSetId) + .first { openableResultIds.contains($0) } + } + + private func copyStatements(in log: QueryRunLog, among ordinals: Set) { + let statements = log.entries.filter { ordinals.contains($0.ordinal) }.map(\.statement) + guard !statements.isEmpty else { return } + ClipboardService.shared.writeText(statements.joined(separator: "\n")) + } +} + +private struct QueryRunEmptyView: View { + var body: some View { + UnavailableStateView( + String(localized: "No Run Yet"), + systemImage: "text.alignleft", + description: Text(String(localized: "Run a query to see what each statement did.")) + ) + } +} diff --git a/apple/TablePro/Views/Results/QueryRunTabBar.swift b/apple/TablePro/Views/Results/QueryRunTabBar.swift new file mode 100644 index 0000000000..bc38ee21b4 --- /dev/null +++ b/apple/TablePro/Views/Results/QueryRunTabBar.swift @@ -0,0 +1,155 @@ +// +// QueryRunTabBar.swift +// TablePro +// + +import AppKit +import SwiftUI + +struct QueryRunTabActions { + let showPage: (ResultsPage) -> Void + /// `activate` brings the result's page to the front as well as choosing the result. + let results: ResultSetActions + + static var none: QueryRunTabActions { + QueryRunTabActions(showPage: { _ in }, results: .none) + } +} + +// Message, Summary and a tab per result, with the result pull-down at the end of the row. Takes the place of +// `ResultSetTabBar` while Settings > Editor turns the tabs on. +struct QueryRunTabBar: View { + let page: ResultsPage + let results: ResultSetMenuModel + /// False in Structure mode, which chooses no result, as the result set tab row offers no pull-down there. + var showsMenu = true + let actions: QueryRunTabActions + + var body: some View { + VStack(spacing: 0) { + ViewThatFits(in: .horizontal) { + if QueryRunTabStrip.canListEachResult(results) { + row(listsEachResult: true, isSpelledOut: true) + row(listsEachResult: true, isSpelledOut: false) + } + row(listsEachResult: false, isSpelledOut: true) + row(listsEachResult: false, isSpelledOut: false) + } + .padding(.horizontal, StatusBarChrome.horizontalPadding) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: StatusBarChrome.height) + .paneBarBackground() + Divider() + } + } + + private func row(listsEachResult: Bool, isSpelledOut: Bool) -> some View { + HStack(spacing: StatusBarChrome.clusterSpacing) { + // SwiftUI sets a hosted control's size from its environment, so it is set here and not in the control. + QueryRunTabs( + strip: QueryRunTabStrip(page: page, results: results, listsEachResult: listsEachResult), + results: results, + onChoose: choose + ) + .controlSize(.small) + Spacer(minLength: 0) + if showsMenu, !results.isEmpty { + ResultSetMenu(model: results, isSpelledOut: isSpelledOut, actions: actions.results) + } + } + } + + private func choose(_ segment: QueryRunTabStrip.Segment) { + switch segment { + case .message: + actions.showPage(.message) + case .summary: + actions.showPage(.summary) + case .result(let entry): + actions.results.activate(entry.id) + } + } +} + +struct QueryRunTabs: NSViewRepresentable { + let strip: QueryRunTabStrip + let results: ResultSetMenuModel + let onChoose: (QueryRunTabStrip.Segment) -> Void + + func makeNSView(context: Context) -> QueryRunTabsControl { + QueryRunTabsControl() + } + + func updateNSView(_ control: QueryRunTabsControl, context: Context) { + control.onChoose = onChoose + control.apply(strip, results: results) + } + + // Always the width every tab needs, so `ViewThatFits` folds the results rather than squeezing the tabs. + func sizeThatFits(_ proposal: ProposedViewSize, nsView control: QueryRunTabsControl, context: Context) -> CGSize? { + control.intrinsicContentSize + } +} + +// AppKit on purpose, as `ResultSetTabsControl` is: a SwiftUI segmented or `.tabs` picker drops a segment's image, +// and a pinned result's tab shows its pin. +@MainActor +final class QueryRunTabsControl: NSSegmentedControl { + var onChoose: ((QueryRunTabStrip.Segment) -> Void)? + private var shownSegments: [QueryRunTabStrip.Segment] = [] + private var litIndex = -1 + + init() { + super.init(frame: .zero) + trackingMode = .selectOne + #if SDK_MACOS_27 + if #available(macOS 27.0, *) { + role = .tabs + } + #endif + target = self + action = #selector(segmentChosen(_:)) + setAccessibilityLabel(String(localized: "Results")) + setAccessibilityIdentifier("query-run-tabs") + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("QueryRunTabsControl does not support NSCoder init") + } + + func apply(_ strip: QueryRunTabStrip, results: ResultSetMenuModel) { + if segmentCount != strip.segments.count { + segmentCount = strip.segments.count + } + for (index, segment) in strip.segments.enumerated() { + let title = QueryRunTabStrip.title(of: segment, in: results) + if label(forSegment: index) != title { + setLabel(title, forSegment: index) + } + setImage(Self.isPinned(segment) ? Self.pinImage : nil, forSegment: index) + setToolTip(QueryRunTabStrip.toolTip(of: segment, in: results), forSegment: index) + } + shownSegments = strip.segments + litIndex = strip.selectedIndex + selectedSegment = litIndex + } + + @objc private func segmentChosen(_ sender: NSSegmentedControl) { + let chosen = selectedSegment + // The tab's state decides which segment is lit, so a switch the discard prompt cancels leaves it as it was. + selectedSegment = litIndex + guard shownSegments.indices.contains(chosen), chosen != litIndex else { return } + onChoose?(shownSegments[chosen]) + } + + private static func isPinned(_ segment: QueryRunTabStrip.Segment) -> Bool { + guard case .result(let entry) = segment else { return false } + return entry.isPinned + } + + private static let pinImage = NSImage( + systemSymbolName: "pin.fill", + accessibilityDescription: String(localized: "Pinned") + )?.withSymbolConfiguration(NSImage.SymbolConfiguration(scale: .small)) +} diff --git a/apple/TablePro/Views/Results/ServerOutputTextView.swift b/apple/TablePro/Views/Results/ServerOutputTextView.swift index 7acd9d1375..6b8908fe84 100644 --- a/apple/TablePro/Views/Results/ServerOutputTextView.swift +++ b/apple/TablePro/Views/Results/ServerOutputTextView.swift @@ -7,8 +7,11 @@ import AppKit import SwiftUI /// A read-only text view that holds thousands of lines of server output without laying them out as SwiftUI text. +/// The Message tab's run log uses it for the same reason. struct ServerOutputTextView: NSViewRepresentable { let text: String + var accessibilityLabel = String(localized: "Server output") + var accessibilityIdentifier = "server-output-text" func makeNSView(context: Context) -> NSScrollView { let scrollView = NSTextView.scrollableTextView() @@ -24,8 +27,8 @@ struct ServerOutputTextView: NSViewRepresentable { textView: textView, natives: ThemeTextViewStyle.Natives(of: textView) ) - textView.setAccessibilityLabel(String(localized: "Server output")) - textView.setAccessibilityIdentifier("server-output-text") + textView.setAccessibilityLabel(accessibilityLabel) + textView.setAccessibilityIdentifier(accessibilityIdentifier) textView.string = text return scrollView } diff --git a/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift b/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift index 05a6453555..dd075be8c9 100644 --- a/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift +++ b/apple/TableProTests/Models/Query/QueryResultPresentationTests.swift @@ -456,4 +456,92 @@ struct QueryResultPresentationTests { #expect(above.showsErrorBanner == below.showsErrorBanner) } } + + // MARK: - Message and Summary tabs + + @Test("With the setting off the pane is today's: no run tabs, the result page, and the tab row only for two or more") + func runTabsOffKeepsTodaysPane() { + var inputs = QueryResultInputs() + inputs.hasExecuted = true + inputs.hasRunLog = true + inputs.resultsPage = .message + let placements = (0 ... 3).map { count -> ResultSetChooserPlacement in + inputs.resultSetCount = count + let presentation = QueryResultPresentation(inputs: inputs) + #expect(presentation.showsRunTabs == false) + #expect(presentation.page == .result) + return presentation.resultSetChooser + } + + #expect(placements == [.hidden, .statusBar, .tabRow, .tabRow]) + } + + @Test("With the setting on, the run tabs show from the first run, even for one result, and carry the pull-down") + func runTabsOnShowAfterTheFirstRun() { + var inputs = QueryResultInputs() + inputs.prefersRunTabs = true + #expect(QueryResultPresentation(inputs: inputs).showsRunTabs == false) + + inputs.hasExecuted = true + inputs.hasRunLog = true + let failedFirstRun = QueryResultPresentation(inputs: inputs) + #expect(failedFirstRun.showsRunTabs) + #expect(failedFirstRun.resultSetChooser == .hidden) + + inputs.resultSetCount = 1 + let oneResult = QueryResultPresentation(inputs: inputs) + #expect(oneResult.showsRunTabs) + #expect(oneResult.resultSetChooser == .tabRow) + #expect(oneResult.showsStatusBar(at: .bottom)) + } + + @Test("The page in front follows the tab's choice only while the run tabs show") + func pageFollowsTheTab() { + var inputs = QueryResultInputs() + inputs.prefersRunTabs = true + inputs.hasExecuted = true + inputs.hasRunLog = true + inputs.resultSetCount = 2 + + for page in [ResultsPage.message, .summary, .result] { + inputs.resultsPage = page + #expect(QueryResultPresentation(inputs: inputs).page == page) + } + } + + @Test("A table tab never gets the run tabs") + func tableTabsKeepTheirPane() { + var inputs = QueryResultInputs() + inputs.tabType = .table + inputs.prefersRunTabs = true + inputs.hasRunLog = true + inputs.resultSetCount = 1 + inputs.resultsPage = .message + + let presentation = QueryResultPresentation(inputs: inputs) + #expect(presentation.showsRunTabs == false) + #expect(presentation.page == .result) + #expect(presentation.resultSetChooser == .hidden) + } + + @Test("Turning the run tabs on changes nothing about the result page itself") + func resultPageIsUnchanged() { + var inputs = QueryResultInputs() + inputs.hasExecuted = true + inputs.hasActiveResultSet = true + inputs.activeResultHasColumns = true + inputs.loadedColumnCount = 3 + inputs.loadedRowCount = 5 + inputs.resultSetCount = 2 + inputs.hasRunLog = true + let off = QueryResultPresentation(inputs: inputs) + inputs.prefersRunTabs = true + let on = QueryResultPresentation(inputs: inputs) + + #expect(on.content == off.content) + #expect(on.showsErrorBanner == off.showsErrorBanner) + #expect(on.showsFilterChrome == off.showsFilterChrome) + #expect(on.statusBarPlacement == off.statusBarPlacement) + #expect(on.resultSetChooser == off.resultSetChooser) + } } diff --git a/apple/TableProTests/Models/Query/QueryRunTabStripTests.swift b/apple/TableProTests/Models/Query/QueryRunTabStripTests.swift new file mode 100644 index 0000000000..5f5f18389d --- /dev/null +++ b/apple/TableProTests/Models/Query/QueryRunTabStripTests.swift @@ -0,0 +1,71 @@ +// +// QueryRunTabStripTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct QueryRunTabStripTests { + private static func results(_ labels: [String], activeIndex: Int = 0) -> ResultSetMenuModel { + let entries = labels.enumerated().map { index, label in + ResultSetMenuEntry( + id: UUID(), + label: label, + isPinned: false, + isActive: index == activeIndex, + ordinal: index + 1, + isComparable: true + ) + } + return ResultSetMenuModel(entries: entries, activeOrdinal: activeIndex + 1, total: entries.count) + } + + private static func titles(_ strip: QueryRunTabStrip, _ results: ResultSetMenuModel) -> [String] { + strip.segments.map { QueryRunTabStrip.title(of: $0, in: results) } + } + + @Test("Message and Summary lead the row, then a tab per result, even for one result") + func messageSummaryThenEachResult() { + let one = Self.results(["users"]) + let two = Self.results(["users", "orders"], activeIndex: 1) + + #expect(Self.titles(QueryRunTabStrip(page: .result, results: one, listsEachResult: true), one) + == ["Message", "Summary", "users"]) + #expect(Self.titles(QueryRunTabStrip(page: .result, results: two, listsEachResult: true), two) + == ["Message", "Summary", "users", "orders"]) + } + + @Test("The lit tab follows the page, and on a result page the active result") + func litTabFollowsThePage() { + let results = Self.results(["users", "orders", "Result 3"], activeIndex: 1) + + #expect(QueryRunTabStrip(page: .message, results: results, listsEachResult: true).selectedIndex == 0) + #expect(QueryRunTabStrip(page: .summary, results: results, listsEachResult: true).selectedIndex == 1) + #expect(QueryRunTabStrip(page: .result, results: results, listsEachResult: true).selectedIndex == 3) + #expect(QueryRunTabStrip(page: .result, results: results, listsEachResult: false).selectedIndex == 2) + } + + @Test("Folded, the results are one tab for the active result") + func foldedRowShowsTheActiveResult() { + let results = Self.results(["users", "orders", "invoices"], activeIndex: 2) + let strip = QueryRunTabStrip(page: .message, results: results, listsEachResult: false) + + #expect(Self.titles(strip, results) == ["Message", "Summary", "invoices"]) + } + + @Test("A run with no results left still offers Message and Summary, with no result tab lit") + func noResults() { + let none = ResultSetMenuModel(entries: [], activeOrdinal: 0, total: 0) + + #expect(QueryRunTabStrip(page: .result, results: none, listsEachResult: true).segments == [.message, .summary]) + #expect(QueryRunTabStrip(page: .result, results: none, listsEachResult: true).selectedIndex == -1) + } + + @Test("Up to six results get a tab each; past that the pull-down lists them") + func sixResultsAtMost() { + #expect(QueryRunTabStrip.canListEachResult(Self.results((1 ... 6).map { "r\($0)" }))) + #expect(!QueryRunTabStrip.canListEachResult(Self.results((1 ... 7).map { "r\($0)" }))) + } +} diff --git a/apple/TableProTests/Views/Results/QueryRunTabBarLayoutTests.swift b/apple/TableProTests/Views/Results/QueryRunTabBarLayoutTests.swift new file mode 100644 index 0000000000..445616d2ba --- /dev/null +++ b/apple/TableProTests/Views/Results/QueryRunTabBarLayoutTests.swift @@ -0,0 +1,111 @@ +import AppKit +import Foundation +import SwiftUI +import Testing + +@testable import TablePro + +@MainActor +struct QueryRunTabBarLayoutTests { + @Test("A wide pane shows Message, Summary and a tab per result, with the result lit") + func wideRowListsEachResult() throws { + let bar = QueryRunTabBar(page: .result, results: Self.model(labels: ["users", "orders"], activeIndex: 1), actions: .none) + let hosted = host(bar, width: 900) + let tabs = try #require(tabControls(in: hosted.view).first) + + #expect(tabs.segmentCount == 4) + #expect(tabs.label(forSegment: 0) == "Message") + #expect(tabs.label(forSegment: 1) == "Summary") + #expect(tabs.label(forSegment: 3) == "orders") + #expect(tabs.selectedSegment == 3) + } + + @Test("One result still gets its own tab beside Message and Summary") + func oneResultHasATab() throws { + let hosted = host(QueryRunTabBar(page: .message, results: Self.model(labels: ["users"]), actions: .none), width: 900) + let tabs = try #require(tabControls(in: hosted.view).first) + + #expect(tabs.segmentCount == 3) + #expect(tabs.selectedSegment == 0) + } + + @Test("A narrow pane folds the results into one tab rather than cutting the row off") + func narrowPaneFolds() throws { + let labels = (1 ... 6).map { "monthly_revenue_by_region_\($0)" } + let hosted = host(QueryRunTabBar(page: .summary, results: Self.model(labels: labels), actions: .none), width: 420) + let tabs = try #require(tabControls(in: hosted.view).first) + + #expect(tabs.segmentCount == 3) + #expect(tabs.selectedSegment == 1) + } + + @Test("Choosing a tab asks for its page or its result, and leaves the lit tab to the model") + func choosingReportsTheSegment() throws { + let model = Self.model(labels: ["users", "orders"]) + let recorder = ChoiceRecorder() + let actions = QueryRunTabActions( + showPage: { recorder.pages.append($0) }, + results: ResultSetActions( + activate: { recorder.results.append($0) }, + togglePin: { _ in }, compare: { _ in }, close: { _ in }, closeOthers: { _ in } + ) + ) + let hosted = host(QueryRunTabBar(page: .result, results: model, actions: actions), width: 900) + let tabs = try #require(tabControls(in: hosted.view).first) + + tabs.selectedSegment = 1 + tabs.sendAction(tabs.action, to: tabs.target) + tabs.selectedSegment = 3 + tabs.sendAction(tabs.action, to: tabs.target) + + #expect(recorder.pages == [.summary]) + #expect(recorder.results == [model.entries[1].id]) + #expect(tabs.selectedSegment == 2) + } + + private func host(_ content: some View, width: CGFloat) -> HostedRow { + let host = NSHostingView(rootView: AnyView(content)) + host.sizingOptions = [] + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: width, height: 40), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = host + host.frame = NSRect(x: 0, y: 0, width: width, height: 40) + host.layoutSubtreeIfNeeded() + return HostedRow(view: host, window: window) + } + + private func tabControls(in view: NSView) -> [QueryRunTabsControl] { + let own = (view as? QueryRunTabsControl).map { [$0] } ?? [] + return own + view.subviews.flatMap { tabControls(in: $0) }.filter { !$0.isHiddenOrHasHiddenAncestor } + } + + private static func model(labels: [String], activeIndex: Int = 0) -> ResultSetMenuModel { + let entries = labels.enumerated().map { index, label in + ResultSetMenuEntry( + id: UUID(), + label: label, + isPinned: false, + isActive: index == activeIndex, + ordinal: index + 1, + isComparable: true + ) + } + return ResultSetMenuModel(entries: entries, activeOrdinal: activeIndex + 1, total: labels.count) + } +} + +private struct HostedRow { + let view: NSView + let window: NSWindow +} + +@MainActor +private final class ChoiceRecorder { + var pages: [ResultsPage] = [] + var results: [UUID] = [] +} From 4c8f62ff569e623a4050655a725318a60073ffd0 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 15:35:09 +0700 Subject: [PATCH 112/123] chore(l10n): add the query run tab strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../TablePro/Resources/Localizable.xcstrings | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index b0c9bc5e89..37ed6152d1 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -11555,6 +11555,9 @@ } } } + }, + "%lld row(s) returned" : { + }, "%lld row%@ affected" : { "extractionState" : "stale", @@ -21434,6 +21437,9 @@ }, "After" : { + }, + "After a run, Message lists what each statement did and Summary puts the same in a table, beside a tab for each result." : { + }, "After keyword expansion, Tab moves through fields such as %1$@, and %2$@ marks where the cursor ends up." : { @@ -52237,6 +52243,9 @@ } } } + }, + "Copy Statement" : { + }, "Copy stopped" : { "localizations" : { @@ -69678,6 +69687,9 @@ }, "Each row takes a value that exists in the referenced table." : { + }, + "Each statement of the last run, with its status, rows and time" : { + }, "Each value is split at every match. Rows with fewer pieces get empty cells." : { "localizations" : { @@ -73935,6 +73947,9 @@ } } } + }, + "Error: %@" : { + }, "Error: Selected path is not a regular file" : { "localizations" : { @@ -110119,6 +110134,9 @@ } } } + }, + "Messages" : { + }, "Messages are nested too deeply." : { @@ -113840,6 +113858,9 @@ }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, takes the connection and database out of the toolbar, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter bar, opens that bar with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows and Message and Summary tabs above the results, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, takes the connection and database out of the toolbar, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter bar, opens that bar with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { @@ -120462,6 +120483,9 @@ } } } + }, + "No Run Yet" : { + }, "No saved changes to '%@' are being kept." : { "localizations" : { @@ -126176,6 +126200,9 @@ } } } + }, + "OK, %lld row(s) affected" : { + }, "Old image" : { "extractionState" : "manual", @@ -141438,6 +141465,9 @@ } } } + }, + "Query plan returned" : { + }, "Query preview" : { "comment" : "Accessibility label for the query preview text view.", @@ -155216,6 +155246,9 @@ } } } + }, + "Run a query to see what each statement did." : { + }, "Run a saved query on the Server Dashboard" : { @@ -166359,6 +166392,9 @@ }, "show masked values" : { + }, + "Show Message and Summary tabs above query results" : { + }, "SHOW needs TOPICS, BROKERS, GROUPS or CLUSTER." : { "extractionState" : "manual", @@ -214941,6 +214977,9 @@ } } } + }, + "What each statement of the last run did" : { + }, "What is switched on here is ignored when two structures are compared. These drift between environments by design." : { "localizations" : { From 576310cbad61755238dabe8525d3beed17b180cd Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 16:46:17 +0700 Subject: [PATCH 113/123] feat(sidebar): add a Compact row size and use it in the navigator layout Compact keeps the regular text and glyph in 22 point rows, shorter than AppKit's small rows, so a long tree of connections and tables fits on screen. Use Navigator Layout turns it on and Use Standard Layout puts Match System back. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../WorkspaceRailViewController.swift | 10 ++++--- .../Settings/NavigatorLayoutPreset.swift | 6 +++-- .../Models/UI/SidebarRowSizePreference.swift | 15 ++++++++++- .../Views/Settings/GeneralSettingsView.swift | 7 ++--- .../SourceList/SidebarOutlineScaffold.swift | 22 +++++++++++---- .../Models/NavigatorLayoutPresetTests.swift | 3 +++ .../UI/SidebarRowSizePreferenceTests.swift | 27 +++++++++++++++---- .../Sidebar/SidebarOutlineScaffoldTests.swift | 25 +++++++++++++++++ 8 files changed, 96 insertions(+), 19 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift index ac2d1f14aa..8d45ec63a8 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift @@ -404,11 +404,15 @@ 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. private var resolvedRowSizeStyle: NSTableView.RowSizeStyle { - let preference = AppSettingsManager.shared.general.sidebarRowSize - guard preference == .matchSystem else { + switch AppSettingsManager.shared.general.sidebarRowSize { + case .matchSystem: + return rowSizeProbe.effectiveRowSizeStyle + case .compact: + /// Compact has no AppKit style of its own, and its tree is denser than Small's. + return .small + case let preference: return SidebarRowSizeResolver.rowSizeStyle(for: preference) } - return rowSizeProbe.effectiveRowSizeStyle } internal func refreshLayoutIfNeeded() { diff --git a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift index a33a9f83f6..05bbfd976b 100644 --- a/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift +++ b/apple/TablePro/Models/Settings/NavigatorLayoutPreset.swift @@ -7,8 +7,8 @@ import Foundation /// The Layout buttons in Settings > General: table details, favorite tables at the top of the tree, /// the Objects tab on selection, the Objects toolbar buttons, labels under the toolbar's icons, the -/// toolbar without its connection and database capsules, the saved connections in the tree and Tree -/// as the default sidebar layout, on or off in one step. The +/// toolbar without its connection and database capsules, the saved connections in the tree, Tree +/// as the default sidebar layout and compact sidebar rows, on or off in one step. The /// same buttons switch the table tab's data view and the query bar (`applyDataView`). /// /// The tree lists the saved connections itself, so the layout keeps the separate connections column @@ -27,6 +27,7 @@ internal enum NavigatorLayoutPreset { settings.showsToolbarLocationItems = false settings.showsConnectionsInTree = true settings.showsConnectionNavigator = false + settings.sidebarRowSize = .compact defaultLayout = .tree } @@ -40,6 +41,7 @@ internal enum NavigatorLayoutPreset { settings.showsToolbarLocationItems = standard.showsToolbarLocationItems settings.showsConnectionsInTree = standard.showsConnectionsInTree settings.showsConnectionNavigator = standard.showsConnectionNavigator + settings.sidebarRowSize = standard.sidebarRowSize defaultLayout = .flat } diff --git a/apple/TablePro/Models/UI/SidebarRowSizePreference.swift b/apple/TablePro/Models/UI/SidebarRowSizePreference.swift index 5a4d79fc58..e3d8d5c082 100644 --- a/apple/TablePro/Models/UI/SidebarRowSizePreference.swift +++ b/apple/TablePro/Models/UI/SidebarRowSizePreference.swift @@ -11,9 +11,11 @@ import SwiftUI /// macOS already has this setting, in System Settings > Appearance > Sidebar icon size, and it /// applies to every app. Following it is the default, so TablePro's sidebar matches Finder, Mail and /// Notes out of the box. The explicit sizes are an override for a database with hundreds of objects, -/// where density is worth more than matching the rest of the system. +/// where density is worth more than matching the rest of the system. Compact is the densest: the +/// regular text size with the space around it trimmed, so a long tree fits without smaller text. internal enum SidebarRowSizePreference: String, CaseIterable, Codable, Sendable { case matchSystem + case compact case small case medium case large @@ -21,6 +23,7 @@ internal enum SidebarRowSizePreference: String, CaseIterable, Codable, Sendable internal var title: String { switch self { case .matchSystem: return String(localized: "Match System") + case .compact: return String(localized: "Compact") case .small: return String(localized: "Small") case .medium: return String(localized: "Medium") case .large: return String(localized: "Large") @@ -41,6 +44,7 @@ internal enum SidebarRowSizeResolver { ) -> SidebarRowSize { switch preference { case .matchSystem: return system + case .compact: return .medium case .small: return .small case .medium: return .medium case .large: return .large @@ -52,11 +56,20 @@ internal enum SidebarRowSizeResolver { internal static func rowSizeStyle(for preference: SidebarRowSizePreference) -> NSTableView.RowSizeStyle { switch preference { case .matchSystem: return .default + case .compact: return .custom case .small: return .small case .medium: return .medium case .large: return .large } } + + /// The height a `.custom` row takes. AppKit's own sizes start at 24 points, so Compact names + /// its height outright: 22 points holds the regular text and a 15 point glyph without clipping. + internal static func rowHeight(for preference: SidebarRowSizePreference) -> CGFloat? { + preference == .compact ? compactRowHeight : nil + } + + internal static let compactRowHeight: CGFloat = 22 } internal extension SidebarRowSize { diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 585e515aba..fa447f2f85 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -81,8 +81,8 @@ struct GeneralSettingsView: View { Text(String(localized: """ Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects \ tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the \ - tree, takes the connection and database out of the toolbar, and makes Tree the default \ - sidebar layout. In table tabs it shows column types in \ + tree, takes the connection and database out of the toolbar, makes Tree the default \ + sidebar layout and uses compact sidebar rows. In table tabs it shows column types in \ the header, the sort and a Text mode in the filter bar, opens that bar with each table, \ puts the result bar above the grid and names the database and connection in tab titles. \ In query tabs it shows the query bar on two rows and Message and Summary tabs above the \ @@ -149,7 +149,8 @@ struct GeneralSettingsView: View { } .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. + Choose a size to fit more objects on screen than the rest of the system shows. \ + Compact keeps the regular text size with less space between rows. """)) Picker("Default layout for new connections:", selection: $defaultSidebarLayout) { diff --git a/apple/TablePro/Views/Sidebar/SourceList/SidebarOutlineScaffold.swift b/apple/TablePro/Views/Sidebar/SourceList/SidebarOutlineScaffold.swift index 54cdaee3ed..ff4178e698 100644 --- a/apple/TablePro/Views/Sidebar/SourceList/SidebarOutlineScaffold.swift +++ b/apple/TablePro/Views/Sidebar/SourceList/SidebarOutlineScaffold.swift @@ -43,9 +43,11 @@ internal enum SidebarOutlineScaffold { outlineView.style = configuration.style /// `.sourceList` already supplies the row height and the indent per level, and `.default` /// is how a table says "the size the user picked in Appearance". - outlineView.rowSizeStyle = configuration.style == .sourceList - ? SidebarRowSizeResolver.rowSizeStyle(for: configuration.rowSizePreference) - : .custom + if configuration.style == .sourceList { + applyRowSize(configuration.rowSizePreference, to: outlineView) + } else { + outlineView.rowSizeStyle = .custom + } outlineView.allowsMultipleSelection = configuration.allowsMultipleSelection outlineView.allowsEmptySelection = true outlineView.floatsGroupRows = false @@ -68,8 +70,18 @@ internal enum SidebarOutlineScaffold { ) { guard let outlineView = scrollView.documentView as? NSOutlineView, outlineView.style == .sourceList else { return } + applyRowSize(preference, to: outlineView) + } + + /// A style change makes AppKit reset `rowHeight` to that style's height, so a custom height is + /// set after the style, every time. + private static func applyRowSize(_ preference: SidebarRowSizePreference, to outlineView: NSOutlineView) { let style = SidebarRowSizeResolver.rowSizeStyle(for: preference) - guard outlineView.rowSizeStyle != style else { return } - outlineView.rowSizeStyle = style + if outlineView.rowSizeStyle != style { + outlineView.rowSizeStyle = style + } + if let height = SidebarRowSizeResolver.rowHeight(for: preference), outlineView.rowHeight != height { + outlineView.rowHeight = height + } } } diff --git a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift index 159fdcd549..4b8a563e31 100644 --- a/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift +++ b/apple/TableProTests/Models/NavigatorLayoutPresetTests.swift @@ -21,6 +21,7 @@ struct NavigatorLayoutPresetTests { expected.showsToolbarLocationItems = false expected.showsConnectionsInTree = true expected.showsConnectionNavigator = false + expected.sidebarRowSize = .compact return expected } @@ -38,6 +39,7 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsToolbarLabels) #expect(!settings.showsToolbarLocationItems, "The tree, the query bar and the tab titles name both") #expect(settings.showsConnectionsInTree) + #expect(settings.sidebarRowSize == .compact, "A long tree of tables fits without smaller text") #expect(layout == .tree) } @@ -71,6 +73,7 @@ struct NavigatorLayoutPresetTests { #expect(settings.showsToolbarLocationItems, "Standard Layout puts the connection and database back") #expect(settings.showsConnectionsInTree == GeneralSettings.default.showsConnectionsInTree) #expect(settings.showsConnectionNavigator == GeneralSettings.default.showsConnectionNavigator) + #expect(settings.sidebarRowSize == .matchSystem) #expect(settings == GeneralSettings.default) #expect(layout == .flat) } diff --git a/apple/TableProTests/Models/UI/SidebarRowSizePreferenceTests.swift b/apple/TableProTests/Models/UI/SidebarRowSizePreferenceTests.swift index b529f71bfc..68e38b83dd 100644 --- a/apple/TableProTests/Models/UI/SidebarRowSizePreferenceTests.swift +++ b/apple/TableProTests/Models/UI/SidebarRowSizePreferenceTests.swift @@ -36,6 +36,21 @@ struct SidebarRowSizePreferenceTests { #expect(SidebarRowSizeResolver.rowSizeStyle(for: .large) == .large) } + @Test("Compact keeps the regular text and glyph and asks for its own row height") + func compactKeepsRegularTextInShorterRows() { + #expect(SidebarRowSizeResolver.resolve(preference: .compact, system: .small) == .medium) + #expect(SidebarRowSizeResolver.resolve(preference: .compact, system: .large) == .medium) + #expect(SidebarRowSizeResolver.rowSizeStyle(for: .compact) == .custom) + #expect(SidebarRowSizeResolver.rowHeight(for: .compact) == SidebarRowSizeResolver.compactRowHeight) + } + + @Test("Only Compact names a row height; the other sizes leave it to AppKit") + func otherSizesHaveNoCustomHeight() { + for preference in SidebarRowSizePreference.allCases where preference != .compact { + #expect(SidebarRowSizeResolver.rowHeight(for: preference) == nil) + } + } + @Test("A taller row draws larger text and a larger glyph") func contentScalesWithTheRow() { #expect(SidebarRowSize.small.iconPointSize < SidebarRowSize.medium.iconPointSize) @@ -44,12 +59,14 @@ struct SidebarRowSizePreferenceTests { @Test("The preference round-trips through settings so it survives a relaunch") func preferenceIsCodable() throws { - let settings = GeneralSettings(sidebarRowSize: .large) - let decoded = try JSONDecoder().decode( - GeneralSettings.self, from: try JSONEncoder().encode(settings) - ) + for size in [SidebarRowSizePreference.large, .compact] { + let settings = GeneralSettings(sidebarRowSize: size) + let decoded = try JSONDecoder().decode( + GeneralSettings.self, from: try JSONEncoder().encode(settings) + ) - #expect(decoded.sidebarRowSize == .large) + #expect(decoded.sidebarRowSize == size) + } } @Test("Settings saved before the preference existed default to following the system") diff --git a/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift b/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift index f04ea32520..09dc935d0c 100644 --- a/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift +++ b/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift @@ -95,6 +95,31 @@ struct SidebarOutlineScaffoldTests { #expect(try outline(scrollView).rowSizeStyle == .large) } + + @Test("Compact rows are 22 points tall, shorter than AppKit's small rows") + func compactRowsAreShorterThanSmall() throws { + let compact = try outline(makeScrollView(rowSize: .compact)) + let small = try outline(makeScrollView(rowSize: .small)) + + #expect(compact.rowSizeStyle == .custom) + #expect(compact.rowHeight == SidebarRowSizeResolver.compactRowHeight) + #expect(compact.rowHeight < small.rowHeight) + } + + /// AppKit resets `rowHeight` whenever the style changes, so leaving Compact and coming back + /// has to set the height again rather than keep the other size's height. + @Test("Switching to Compact and back on screen keeps each size's own height") + func compactSurvivesSwitchingSizes() throws { + let scrollView = makeScrollView(rowSize: .compact) + let large = try outline(makeScrollView(rowSize: .large)).rowHeight + + SidebarOutlineScaffold.applyRowSize(.large, to: scrollView) + #expect(try outline(scrollView).rowHeight == large) + + SidebarOutlineScaffold.applyRowSize(.compact, to: scrollView) + #expect(try outline(scrollView).rowSizeStyle == .custom) + #expect(try outline(scrollView).rowHeight == SidebarRowSizeResolver.compactRowHeight) + } } @MainActor From fa6ea6dddf5a9a12e276cec624fb0b7ca59917ea Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 16:46:17 +0700 Subject: [PATCH 114/123] chore(l10n): add the Compact row size strings Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- apple/TablePro/Resources/Localizable.xcstrings | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 37ed6152d1..29d141f199 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -108104,6 +108104,9 @@ } } } + }, + "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. Compact keeps the regular text size with less space between rows." : { + }, "Match what I type" : { @@ -113867,6 +113870,9 @@ }, "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, takes the connection and database out of the toolbar, and makes Tree the default sidebar layout. In table tabs it shows column types in the header, the sort and a Text mode in the filter panel, opens that panel with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { + }, + "Navigator Layout turns on table details, favorite tables at the top of the tree, the Objects tab on selection, the Objects toolbar buttons, toolbar labels and saved connections in the tree, takes the connection and database out of the toolbar, makes Tree the default sidebar layout and uses compact sidebar rows. In table tabs it shows column types in the header, the sort and a Text mode in the filter bar, opens that bar with each table, puts the result bar above the grid and names the database and connection in tab titles. In query tabs it shows the query bar on two rows and Message and Summary tabs above the results, and object icons turn colorful. Standard Layout turns them off again. Open connections switch layout too." : { + }, "Navigator Layout turns on table details, the Objects tab on selection, the Objects toolbar buttons and the connections list, and makes Tree the default sidebar layout. Standard Layout turns them off again. Open connections switch layout too." : { From 890dcaf0948a8352af3d3e74d70ca576fab4edc1 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 19:39:37 +0700 Subject: [PATCH 115/123] fix(settings): move the object icon style picker to General so Appearance fits its window The Appearance pane's form cannot scroll, so the Object Icons section made it 566 points tall in a 500 point pane and pushed the Appearance picker and the theme buttons out of reach. The picker now sits under Show object icons in General > Sidebar, and the Appearance pane is upstream's again. A test pins that the pane fits the smallest window. --- .../Views/Settings/AppearanceSettingsView.swift | 11 ----------- .../Views/Settings/GeneralSettingsView.swift | 12 ++++++++++++ .../Views/Settings/AppearancePaneListTests.swift | 12 ++++++++++++ 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift index 62221bc190..9170061c6a 100644 --- a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift +++ b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift @@ -37,17 +37,6 @@ 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 { - Picker(String(localized: "Object Icons"), selection: $settings.objectIconStyle) { - ForEach(ObjectIconStyle.allCases) { style in - Text(style.displayName).tag(style) - } - } - .accessibilityIdentifier("appearance-object-icon-style") - } footer: { - Text("Colorful gives each kind of object its own filled, colored icon in the sidebar, the tabs and the object lists.") - } } .formStyle(.grouped) .scrollDisabled(true) diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index fa447f2f85..652aa9f2ce 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -125,6 +125,18 @@ struct GeneralSettingsView: View { 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.") + // Here rather than in Appearance: that pane cannot scroll, and one more row pushed its controls off it. + Picker("Object icon style:", selection: $appearanceSettings.objectIconStyle) { + ForEach(ObjectIconStyle.allCases) { style in + Text(style.displayName).tag(style) + } + } + .accessibilityIdentifier("general-object-icon-style") + .help(String(localized: """ + Colorful gives each kind of object its own filled, colored icon in the sidebar, the tabs, the \ + toolbar and the object lists. + """)) + Toggle("Show object comments", isOn: $settings.showObjectComments) .help("Shows database object comments next to tables in the sidebar and in grid column headers.") diff --git a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift index 45f6b02e22..9c0ddb85a0 100644 --- a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift +++ b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift @@ -106,6 +106,18 @@ struct AppearancePaneListTests { #expect(scrollView.verticalScrollElasticity != .none) } + /// The Form above the list cannot scroll, so content taller than the pane pushes its first and last controls + /// past the window's edges, where nothing can reach them. + @Test("The pane's content fits the smallest Settings window") + func contentFitsTheSmallestPane() { + let paneSize = SettingsPaneTabViewController.paneSize + let hosting = NSHostingController(rootView: AppearanceSettingsView(settings: .constant(.default))) + + let needed = hosting.sizeThatFits(in: paneSize) + + #expect(needed.height <= paneSize.height, "The pane needs \(needed.height) points of \(paneSize.height)") + } + @Test("Reading the Themes list for accessibility leaves its rows where they are") func themesListHoldsStillWhileAccessibilityReadsIt() throws { let pane = try Self.hostPane() From 8aef701f644cc1e6d09664639435ecce684eb7c3 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 19:39:37 +0700 Subject: [PATCH 116/123] chore(l10n): add the object icon style picker strings --- apple/TablePro/Resources/Localizable.xcstrings | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index be89e0d250..55c8805385 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -44080,6 +44080,9 @@ }, "Colorful gives each kind of object its own filled, colored icon in the sidebar, the tabs and the object lists." : { + }, + "Colorful gives each kind of object its own filled, colored icon in the sidebar, the tabs, the toolbar and the object lists." : { + }, "Colors" : { "extractionState" : "stale", @@ -126150,6 +126153,9 @@ } } } + }, + "Object icon style:" : { + }, "Object Icons" : { From 2f51c88893547a412ec14f10b978c8f9cd4ea204 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 19:47:11 +0700 Subject: [PATCH 117/123] fix(editor): make an accessibility value set an edit the tab hears Setting AXValue swapped the text storage without the change notification, so text Voice Control or another assistive app put in the SQL editor showed on screen but never reached the tab: Run and Format stayed dim and the text was not saved. The value now goes through the edit path, which notifies, records undo and respects a read-only editor. --- .../TextView/TextView+Accessibility.swift | 5 +++- .../AccessibilityTests.swift | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift index 9158f00fbe..6e445a4d2a 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift @@ -49,12 +49,15 @@ extension TextView { string } + // Assistive technology edits on the user's behalf, so the edit takes the user's path: the delegate and the + // change notification hear it, undo records it, and a read-only editor refuses it. Setting `string` swapped the + // storage silently, so the editor showed text its document never received. override open func setAccessibilityValue(_ accessibilityValue: Any?) { guard let string = accessibilityValue as? String else { return } - self.string = string + replaceCharacters(in: documentRange, with: string) } override open func accessibilityString(for range: NSRange) -> String? { diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift index dc2643ba23..794f084002 100644 --- a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift @@ -55,6 +55,31 @@ struct AccessibilityTests { #expect(textView.string == newValue) } + @Test("A value set through accessibility is an edit the editor's owner hears about") + func setAccessibilityValueNotifiesTheChange() { + var notified = 0 + let observer = NotificationCenter.default.addObserver( + forName: TextView.textDidChangeNotification, + object: textView, + queue: nil + ) { _ in notified += 1 } + defer { NotificationCenter.default.removeObserver(observer) } + + textView.setAccessibilityValue("SELECT 1") + + #expect(textView.string == "SELECT 1") + #expect(notified == 1) + } + + @Test("A read-only editor refuses a value set through accessibility") + func setAccessibilityValueRespectsReadOnly() { + textView.isEditable = false + + textView.setAccessibilityValue("SELECT 1") + + #expect(textView.string == sampleText) + } + @Test func setAccessibilityValueInvalidType() { let originalString = textView.string From afaebf7410531511ed622c7072bf1427da7512ee Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 19:59:10 +0700 Subject: [PATCH 118/123] feat(sidebar): give Compact rows 24 points At 22 points the tree of connections and tables read as crowded. 24 keeps the regular text and glyph with room around them, as short as Small's rows without Small's smaller text. --- .../TablePro/Models/UI/SidebarRowSizePreference.swift | 7 ++++--- .../Views/Sidebar/SidebarOutlineScaffoldTests.swift | 10 ++++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/apple/TablePro/Models/UI/SidebarRowSizePreference.swift b/apple/TablePro/Models/UI/SidebarRowSizePreference.swift index e3d8d5c082..3265c8d744 100644 --- a/apple/TablePro/Models/UI/SidebarRowSizePreference.swift +++ b/apple/TablePro/Models/UI/SidebarRowSizePreference.swift @@ -63,13 +63,14 @@ internal enum SidebarRowSizeResolver { } } - /// The height a `.custom` row takes. AppKit's own sizes start at 24 points, so Compact names - /// its height outright: 22 points holds the regular text and a 15 point glyph without clipping. + /// The height a `.custom` row takes. Small's rows are as short but shrink the text to fit them, so + /// Compact names its height outright: 24 points holds the regular text and a 15 point glyph with + /// room around them. At 22 the rows read as crowded. internal static func rowHeight(for preference: SidebarRowSizePreference) -> CGFloat? { preference == .compact ? compactRowHeight : nil } - internal static let compactRowHeight: CGFloat = 22 + internal static let compactRowHeight: CGFloat = 24 } internal extension SidebarRowSize { diff --git a/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift b/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift index 09dc935d0c..39ca0de07d 100644 --- a/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift +++ b/apple/TableProTests/Views/Sidebar/SidebarOutlineScaffoldTests.swift @@ -96,14 +96,16 @@ struct SidebarOutlineScaffoldTests { #expect(try outline(scrollView).rowSizeStyle == .large) } - @Test("Compact rows are 22 points tall, shorter than AppKit's small rows") - func compactRowsAreShorterThanSmall() throws { + @Test("Compact rows are 24 points tall: no taller than Small's and shorter than Medium's") + func compactRowsAreAsShortAsSmall() throws { let compact = try outline(makeScrollView(rowSize: .compact)) let small = try outline(makeScrollView(rowSize: .small)) + let medium = try outline(makeScrollView(rowSize: .medium)) #expect(compact.rowSizeStyle == .custom) - #expect(compact.rowHeight == SidebarRowSizeResolver.compactRowHeight) - #expect(compact.rowHeight < small.rowHeight) + #expect(compact.rowHeight == 24) + #expect(compact.rowHeight <= small.rowHeight) + #expect(compact.rowHeight < medium.rowHeight) } /// AppKit resets `rowHeight` whenever the style changes, so leaving Compact and coming back From a3efbd4406ade330a24fd68a955186e4df4b86f7 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 21:23:06 +0700 Subject: [PATCH 119/123] fix(window): run the titlebar double-click action over content under a transparent titlebar From macOS 26 the connection window's titlebar is transparent, and the content under it takes the press. The window still dragged, but a double-click never reached AppKit's titlebar action, so it neither zoomed nor minimized. The window now runs the action set in Desktop & Dock when the double-click lands on content there; the titlebar's own views still answer as before. --- apple/.swiftlint.yml | 4 +- .../Infrastructure/ContentWindow.swift | 38 +++++++ .../TitlebarDoubleClickAction.swift | 33 ++++++ .../Services/TitlebarDoubleClickTests.swift | 107 ++++++++++++++++++ 4 files changed, 180 insertions(+), 2 deletions(-) create mode 100644 apple/TablePro/Core/Services/Infrastructure/TitlebarDoubleClickAction.swift create mode 100644 apple/TableProTests/Services/TitlebarDoubleClickTests.swift diff --git a/apple/.swiftlint.yml b/apple/.swiftlint.yml index 6647ff85a7..bdccbc9bb4 100644 --- a/apple/.swiftlint.yml +++ b/apple/.swiftlint.yml @@ -186,7 +186,7 @@ custom_rules: storage_environment_defaults: name: "Storage Environment Defaults" regex: 'UserDefaults\.standard' - excluded: ".*/(AppStorageEnvironment|GeneralSettings|SoftwareUpdater|WorkspaceRailViewController|SplitViewAutosaveSweep)\\.swift" + excluded: ".*/(AppStorageEnvironment|GeneralSettings|SoftwareUpdater|WorkspaceRailViewController|SplitViewAutosaveSweep|TitlebarDoubleClickAction)\\.swift" message: "Resolve preferences through AppStorageEnvironment.shared.defaults. Only a macOS-owned system preference reads the standard domain." severity: error # Package code cannot reach AppStorageEnvironment and the iOS app has no sandbox, so `.standard` is @@ -213,7 +213,7 @@ custom_rules: # Storage and preferences preference_key_namespace: name: "Preference Key Namespace" - regex: '\bforKey:(? Bool { + guard point.y >= contentLayoutRect.maxY, + let contentView, + let frameView = contentView.superview, + let hit = frameView.hitTest(point), + hit.isDescendant(of: contentView), + !(hit is NSControl) + else { return false } + var view: NSView? = hit + while let current = view, current !== frameView { + guard current.mouseDownCanMoveWindow else { return false } + view = current.superview + } + return true + } + + // Read when it is needed, so a change in System Settings applies at once. + internal static var titlebarDoubleClickAction: () -> TitlebarDoubleClickAction = { .current } + + private func performTitlebarDoubleClickAction() { + switch Self.titlebarDoubleClickAction() { + case .zoom: performZoom(nil) + case .minimize: performMiniaturize(nil) + case .none: break + } + } + // Hiding the toolbar drops the content's top safe area, so the titlebar is decided again. override internal func toggleToolbarShown(_ sender: Any?) { super.toggleToolbarShown(sender) diff --git a/apple/TablePro/Core/Services/Infrastructure/TitlebarDoubleClickAction.swift b/apple/TablePro/Core/Services/Infrastructure/TitlebarDoubleClickAction.swift new file mode 100644 index 0000000000..43b10d4b54 --- /dev/null +++ b/apple/TablePro/Core/Services/Infrastructure/TitlebarDoubleClickAction.swift @@ -0,0 +1,33 @@ +// +// TitlebarDoubleClickAction.swift +// TablePro +// + +import Foundation + +/// What a double-click on a window's titlebar does, as System Settings > Desktop & Dock sets it. +internal enum TitlebarDoubleClickAction: Equatable { + case zoom + case minimize + case none + + /// `setting` is the current preference; `minimizesLegacy` is the checkbox older macOS versions wrote, which still + /// decides when the current preference was never set. + internal init(setting: String?, minimizesLegacy: Bool) { + switch setting { + case "Minimize": self = .minimize + case "None": self = .none + case nil: self = minimizesLegacy ? .minimize : .zoom + default: self = .zoom + } + } + + /// macOS owns these keys in the global domain, which only the standard defaults read. + internal static var current: TitlebarDoubleClickAction { + let defaults = UserDefaults.standard + return TitlebarDoubleClickAction( + setting: defaults.string(forKey: "AppleActionOnDoubleClick"), + minimizesLegacy: defaults.bool(forKey: "AppleMiniaturizeOnDoubleClick") + ) + } +} diff --git a/apple/TableProTests/Services/TitlebarDoubleClickTests.swift b/apple/TableProTests/Services/TitlebarDoubleClickTests.swift new file mode 100644 index 0000000000..76bb6b777a --- /dev/null +++ b/apple/TableProTests/Services/TitlebarDoubleClickTests.swift @@ -0,0 +1,107 @@ +// +// TitlebarDoubleClickTests.swift +// TableProTests +// + +import AppKit +import Testing + +@testable import TablePro + +/// The connection window as the app builds it: its content reaches under a transparent titlebar, where a +/// double-click used to land on the content and never reach AppKit's titlebar action. +@MainActor +struct TitlebarDoubleClickTests { + @MainActor + private struct Hosted { + let window: ContentWindow + let workspace: ConnectionWorkspace + + func close() { + window.orderOut(nil) + window.contentViewController = nil + workspace.teardown() + } + + /// Points along the titlebar band, sorted by whether the content or the titlebar's own views are under them. + func bandPoints() -> (overContent: [NSPoint], overTitlebar: [NSPoint]) { + var overContent: [NSPoint] = [] + var overTitlebar: [NSPoint] = [] + guard let contentView = window.contentView, let frameView = contentView.superview else { return ([], []) } + let y = (window.contentLayoutRect.maxY + window.frame.height) / 2 + for x in stride(from: 10.0, to: window.frame.width - 10, by: 20) { + let point = NSPoint(x: x, y: y) + guard let hit = frameView.hitTest(point) else { continue } + if hit.isDescendant(of: contentView) { + overContent.append(point) + } else { + overTitlebar.append(point) + } + } + return (overContent, overTitlebar) + } + } + + private func host() throws -> Hosted { + let connection = TestFixtures.makeConnection(name: "Titlebar") + let workspace = ConnectionWorkspace( + connectionId: connection.id, payload: nil, autoConnect: false, payloadConnection: connection, + session: nil, sessionState: nil, trailingPaneState: nil, phase: .connecting + ) + let window = try #require(TabWindowController.makeEditorWindow() as? ContentWindow) + window.isReleasedWhenClosed = false + let split = MainSplitViewController(payload: nil, sessionState: nil, adopting: workspace) + window.contentViewController = split + split.installTabStripAccessory(on: window) + window.setContentSize(NSSize(width: 1_200, height: 800)) + window.orderFront(nil) + window.layoutIfNeeded() + return Hosted(window: window, workspace: workspace) + } + + private func doubleClick(at point: NSPoint, in window: NSWindow) throws -> NSEvent { + try #require(NSEvent.mouseEvent( + with: .leftMouseDown, location: point, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 2, pressure: 1 + )) + } + + @Test("The titlebar double-click follows the Desktop & Dock setting") + func actionFollowsTheSetting() { + #expect(TitlebarDoubleClickAction(setting: nil, minimizesLegacy: false) == .zoom) + #expect(TitlebarDoubleClickAction(setting: nil, minimizesLegacy: true) == .minimize) + #expect(TitlebarDoubleClickAction(setting: "Maximize", minimizesLegacy: true) == .zoom) + #expect(TitlebarDoubleClickAction(setting: "Fill", minimizesLegacy: false) == .zoom) + #expect(TitlebarDoubleClickAction(setting: "Minimize", minimizesLegacy: false) == .minimize) + #expect(TitlebarDoubleClickAction(setting: "None", minimizesLegacy: true) == .none) + } + + @Test("Content under the titlebar takes the double-click, and the titlebar's own views are left to AppKit") + func contentUnderTheTitlebarTakesIt() throws { + let hosted = try host() + defer { hosted.close() } + let points = hosted.bandPoints() + + try #require(!points.overContent.isEmpty, "The fixture needs content under the transparent titlebar") + #expect(points.overContent.allSatisfy { hosted.window.takesTitlebarDoubleClick(at: $0) }) + #expect(points.overTitlebar.allSatisfy { !hosted.window.takesTitlebarDoubleClick(at: $0) }) + + let belowTitlebar = NSPoint(x: hosted.window.frame.width / 2, y: hosted.window.contentLayoutRect.maxY - 100) + #expect(!hosted.window.takesTitlebarDoubleClick(at: belowTitlebar), "Content below the titlebar keeps its clicks") + } + + @Test("A double-click on the content under the titlebar zooms the window") + func doubleClickZooms() throws { + let hosted = try host() + defer { hosted.close() } + let previous = ContentWindow.titlebarDoubleClickAction + ContentWindow.titlebarDoubleClickAction = { .zoom } + defer { ContentWindow.titlebarDoubleClickAction = previous } + let point = try #require(hosted.bandPoints().overContent.first) + let before = hosted.window.frame + + hosted.window.sendEvent(try doubleClick(at: point, in: hosted.window)) + + #expect(hosted.window.frame != before, "The window should take its zoomed frame") + } +} From 59e675a87bec25f030afa5c024de0606b5806b84 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 21:23:06 +0700 Subject: [PATCH 120/123] feat(results): name run result tabs by statement number A result tab named after its statement grew as long as the SQL. In the Message and Summary strip each result tab now reads Result N, or Error N for a failed statement, matching the numbering on the Message and Summary pages; the statement stays in the tab's tooltip. --- .../Models/Query/QueryRunTabStrip.swift | 33 +++++++++++++++++-- .../Main/Child/MainEditorContentView.swift | 1 + .../Views/Results/QueryRunTabBar.swift | 10 ++++-- .../Models/Query/QueryRunTabStripTests.swift | 24 +++++++++++++- 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/apple/TablePro/Models/Query/QueryRunTabStrip.swift b/apple/TablePro/Models/Query/QueryRunTabStrip.swift index fbf1fd0eeb..79c5c5f5d7 100644 --- a/apple/TablePro/Models/Query/QueryRunTabStrip.swift +++ b/apple/TablePro/Models/Query/QueryRunTabStrip.swift @@ -17,10 +17,19 @@ struct QueryRunTabStrip: Equatable { let segments: [Segment] /// -1 when no tab stands for the page in front, such as a result page with no results left. let selectedIndex: Int + /// A result's tab named by the statement that made it, "Result 2" or "Error 3", so the tab matches the Message + /// and Summary numbering and stays short. The statement itself is the tab's tooltip. + let statementTitles: [UUID: String] /// `listsEachResult` false folds the results into one tab for the active result, and the pull-down at the end of /// the row chooses which. The row folds when it is too narrow or the run made more results than tabs. - init(page: ResultsPage, results: ResultSetMenuModel, listsEachResult: Bool) { + init( + page: ResultsPage, + results: ResultSetMenuModel, + listsEachResult: Bool, + statementTitles: [UUID: String] = [:] + ) { + self.statementTitles = statementTitles let shown: [ResultSetMenuEntry] if listsEachResult { shown = results.entries @@ -47,17 +56,35 @@ struct QueryRunTabStrip: Equatable { results.total <= ResultSetMenuModel.maximumTabCount } - static func title(of segment: Segment, in results: ResultSetMenuModel) -> String { + /// A result no statement of the last run made, such as one pinned from an earlier run, keeps its own name. + func title(of segment: Segment, in results: ResultSetMenuModel) -> String { switch segment { case .message: return String(localized: "Message") case .summary: return String(localized: "Summary") case .result(let entry): - return results.tabTitle(of: entry) + return statementTitles[entry.id] ?? results.tabTitle(of: entry) } } + /// Each result of the run, keyed by its id, named after the statement's number in the run. + static func statementTitles(in log: QueryRunLog?) -> [UUID: String] { + guard let log else { return [:] } + var titles: [UUID: String] = [:] + for entry in log.entries { + guard let id = entry.resultSetId, titles[id] == nil else { continue } + let format: String + if case .failed = entry.outcome { + format = String(localized: "Error %d") + } else { + format = String(localized: "Result %d") + } + titles[id] = String(format: format, entry.ordinal) + } + return titles + } + static func toolTip(of segment: Segment, in results: ResultSetMenuModel) -> String { switch segment { case .message: diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index db09ab9860..68f32fcad3 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -684,6 +684,7 @@ struct MainEditorContentView: View { QueryRunTabBar( page: presentation.page, results: resultSetEntriesModel(for: tab), + statementTitles: QueryRunTabStrip.statementTitles(in: tab.display.runLog), showsMenu: presentation.resultSetChooser == .tabRow, actions: coordinator.runTabActions(forTab: tab.id) ) diff --git a/apple/TablePro/Views/Results/QueryRunTabBar.swift b/apple/TablePro/Views/Results/QueryRunTabBar.swift index bc38ee21b4..5f736da3e3 100644 --- a/apple/TablePro/Views/Results/QueryRunTabBar.swift +++ b/apple/TablePro/Views/Results/QueryRunTabBar.swift @@ -21,6 +21,7 @@ struct QueryRunTabActions { struct QueryRunTabBar: View { let page: ResultsPage let results: ResultSetMenuModel + var statementTitles: [UUID: String] = [:] /// False in Structure mode, which chooses no result, as the result set tab row offers no pull-down there. var showsMenu = true let actions: QueryRunTabActions @@ -47,7 +48,12 @@ struct QueryRunTabBar: View { HStack(spacing: StatusBarChrome.clusterSpacing) { // SwiftUI sets a hosted control's size from its environment, so it is set here and not in the control. QueryRunTabs( - strip: QueryRunTabStrip(page: page, results: results, listsEachResult: listsEachResult), + strip: QueryRunTabStrip( + page: page, + results: results, + listsEachResult: listsEachResult, + statementTitles: statementTitles + ), results: results, onChoose: choose ) @@ -123,7 +129,7 @@ final class QueryRunTabsControl: NSSegmentedControl { segmentCount = strip.segments.count } for (index, segment) in strip.segments.enumerated() { - let title = QueryRunTabStrip.title(of: segment, in: results) + let title = strip.title(of: segment, in: results) if label(forSegment: index) != title { setLabel(title, forSegment: index) } diff --git a/apple/TableProTests/Models/Query/QueryRunTabStripTests.swift b/apple/TableProTests/Models/Query/QueryRunTabStripTests.swift index 5f5f18389d..1a45982474 100644 --- a/apple/TableProTests/Models/Query/QueryRunTabStripTests.swift +++ b/apple/TableProTests/Models/Query/QueryRunTabStripTests.swift @@ -23,7 +23,29 @@ struct QueryRunTabStripTests { } private static func titles(_ strip: QueryRunTabStrip, _ results: ResultSetMenuModel) -> [String] { - strip.segments.map { QueryRunTabStrip.title(of: $0, in: results) } + strip.segments.map { strip.title(of: $0, in: results) } + } + + @Test("A result tab is named by its statement's number, a failed statement's by Error, and others keep their name") + func resultTabsCarryTheStatementNumber() { + let results = Self.results(["SELECT id, customer_id, status FROM orders", "SELECT status, COUNT(*)", "Error 3", "pinned"]) + let ids = results.entries.map(\.id) + let log = QueryRunLog(startedAt: .now, entries: [ + QueryRunLogEntry(statement: "SELECT id, customer_id, status FROM orders", outcome: .returnedRows(6), resultSetId: ids[0]), + QueryRunLogEntry(statement: "UPDATE orders SET total = 0", outcome: .affectedRows(2)), + QueryRunLogEntry(statement: "SELECT status, COUNT(*)", outcome: .returnedRows(4), resultSetId: ids[1]), + .failed("SELECT * FROM missing", message: "no such table", resultSetId: ids[2]) + ]) + let strip = QueryRunTabStrip( + page: .result, + results: results, + listsEachResult: true, + statementTitles: QueryRunTabStrip.statementTitles(in: log) + ) + + #expect(Self.titles(strip, results) == ["Message", "Summary", "Result 1", "Result 3", "Error 4", "pinned"]) + #expect(QueryRunTabStrip.toolTip(of: strip.segments[2], in: results) == "SELECT id, customer_id, status FROM orders") + #expect(QueryRunTabStrip.statementTitles(in: nil).isEmpty) } @Test("Message and Summary lead the row, then a tab per result, even for one result") From 84e4979d6d3f99b243e33201a5cbfc0790b6f8d9 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Wed, 11 Nov 2026 22:03:28 +0700 Subject: [PATCH 121/123] chore(changelog): add the entries for the Navigator Layout --- apple/changelog.d/4199.added.1.md | 1 + apple/changelog.d/4199.added.10.md | 1 + apple/changelog.d/4199.added.11.md | 1 + apple/changelog.d/4199.added.12.md | 1 + apple/changelog.d/4199.added.13.md | 1 + apple/changelog.d/4199.added.14.md | 1 + apple/changelog.d/4199.added.15.md | 1 + apple/changelog.d/4199.added.16.md | 1 + apple/changelog.d/4199.added.17.md | 1 + apple/changelog.d/4199.added.18.md | 1 + apple/changelog.d/4199.added.2.md | 1 + apple/changelog.d/4199.added.3.md | 1 + apple/changelog.d/4199.added.4.md | 1 + apple/changelog.d/4199.added.5.md | 1 + apple/changelog.d/4199.added.6.md | 1 + apple/changelog.d/4199.added.7.md | 1 + apple/changelog.d/4199.added.8.md | 1 + apple/changelog.d/4199.added.9.md | 1 + apple/changelog.d/4199.added.md | 1 + apple/changelog.d/4199.changed.1.md | 1 + apple/changelog.d/4199.changed.md | 1 + apple/changelog.d/4199.fixed.1.md | 1 + apple/changelog.d/4199.fixed.2.md | 1 + apple/changelog.d/4199.fixed.md | 1 + 24 files changed, 24 insertions(+) create mode 100644 apple/changelog.d/4199.added.1.md create mode 100644 apple/changelog.d/4199.added.10.md create mode 100644 apple/changelog.d/4199.added.11.md create mode 100644 apple/changelog.d/4199.added.12.md create mode 100644 apple/changelog.d/4199.added.13.md create mode 100644 apple/changelog.d/4199.added.14.md create mode 100644 apple/changelog.d/4199.added.15.md create mode 100644 apple/changelog.d/4199.added.16.md create mode 100644 apple/changelog.d/4199.added.17.md create mode 100644 apple/changelog.d/4199.added.18.md create mode 100644 apple/changelog.d/4199.added.2.md create mode 100644 apple/changelog.d/4199.added.3.md create mode 100644 apple/changelog.d/4199.added.4.md create mode 100644 apple/changelog.d/4199.added.5.md create mode 100644 apple/changelog.d/4199.added.6.md create mode 100644 apple/changelog.d/4199.added.7.md create mode 100644 apple/changelog.d/4199.added.8.md create mode 100644 apple/changelog.d/4199.added.9.md create mode 100644 apple/changelog.d/4199.added.md create mode 100644 apple/changelog.d/4199.changed.1.md create mode 100644 apple/changelog.d/4199.changed.md create mode 100644 apple/changelog.d/4199.fixed.1.md create mode 100644 apple/changelog.d/4199.fixed.2.md create mode 100644 apple/changelog.d/4199.fixed.md diff --git a/apple/changelog.d/4199.added.1.md b/apple/changelog.d/4199.added.1.md new file mode 100644 index 0000000000..11e7c7a88f --- /dev/null +++ b/apple/changelog.d/4199.added.1.md @@ -0,0 +1 @@ +Tables in the sidebar can expand to list their columns, indexes, foreign keys, checks and triggers. diff --git a/apple/changelog.d/4199.added.10.md b/apple/changelog.d/4199.added.10.md new file mode 100644 index 0000000000..5532616ac8 --- /dev/null +++ b/apple/changelog.d/4199.added.10.md @@ -0,0 +1 @@ +The filter bar can open with each table you open. diff --git a/apple/changelog.d/4199.added.11.md b/apple/changelog.d/4199.added.11.md new file mode 100644 index 0000000000..9ebddf094a --- /dev/null +++ b/apple/changelog.d/4199.added.11.md @@ -0,0 +1 @@ +Table and view tab titles can name the database and connection, such as orders@shop (Shop Demo). diff --git a/apple/changelog.d/4199.added.12.md b/apple/changelog.d/4199.added.12.md new file mode 100644 index 0000000000..cbe8464c18 --- /dev/null +++ b/apple/changelog.d/4199.added.12.md @@ -0,0 +1 @@ +The bar with the row count, view switcher and pages can sit above the grid instead of below it. diff --git a/apple/changelog.d/4199.added.13.md b/apple/changelog.d/4199.added.13.md new file mode 100644 index 0000000000..4009f3f8be --- /dev/null +++ b/apple/changelog.d/4199.added.13.md @@ -0,0 +1 @@ +The query bar can use two rows, adding Save, Query Builder, Snippets and a connection picker. diff --git a/apple/changelog.d/4199.added.14.md b/apple/changelog.d/4199.added.14.md new file mode 100644 index 0000000000..c975c06f9a --- /dev/null +++ b/apple/changelog.d/4199.added.14.md @@ -0,0 +1 @@ +Moving a query tab to another connection from the two-row query bar asks first, and warns for production. diff --git a/apple/changelog.d/4199.added.15.md b/apple/changelog.d/4199.added.15.md new file mode 100644 index 0000000000..88eba340db --- /dev/null +++ b/apple/changelog.d/4199.added.15.md @@ -0,0 +1 @@ +Object icons can be colorful, with a filled icon in its own color for each kind of object. diff --git a/apple/changelog.d/4199.added.16.md b/apple/changelog.d/4199.added.16.md new file mode 100644 index 0000000000..a2cba66129 --- /dev/null +++ b/apple/changelog.d/4199.added.16.md @@ -0,0 +1 @@ +The Objects tab shows each MySQL and MariaDB table's engine, create time and update time. diff --git a/apple/changelog.d/4199.added.17.md b/apple/changelog.d/4199.added.17.md new file mode 100644 index 0000000000..7b7283c78c --- /dev/null +++ b/apple/changelog.d/4199.added.17.md @@ -0,0 +1 @@ +Query tabs can show Message and Summary tabs above the results, with what each statement of the last run did. diff --git a/apple/changelog.d/4199.added.18.md b/apple/changelog.d/4199.added.18.md new file mode 100644 index 0000000000..9521833878 --- /dev/null +++ b/apple/changelog.d/4199.added.18.md @@ -0,0 +1 @@ +A Compact sidebar row size keeps the regular text with less space between rows. diff --git a/apple/changelog.d/4199.added.2.md b/apple/changelog.d/4199.added.2.md new file mode 100644 index 0000000000..e90e83d7f8 --- /dev/null +++ b/apple/changelog.d/4199.added.2.md @@ -0,0 +1 @@ +The sidebar can list the tables you starred in a Favorites section at the top of the tree. diff --git a/apple/changelog.d/4199.added.3.md b/apple/changelog.d/4199.added.3.md new file mode 100644 index 0000000000..d8fdcd2aca --- /dev/null +++ b/apple/changelog.d/4199.added.3.md @@ -0,0 +1 @@ +The Tree sidebar can list every saved connection in its groups, with the open connection expanded to its databases. diff --git a/apple/changelog.d/4199.added.4.md b/apple/changelog.d/4199.added.4.md new file mode 100644 index 0000000000..133cd345e2 --- /dev/null +++ b/apple/changelog.d/4199.added.4.md @@ -0,0 +1 @@ +The connections column can list every saved connection in its groups, beside the database tree. diff --git a/apple/changelog.d/4199.added.5.md b/apple/changelog.d/4199.added.5.md new file mode 100644 index 0000000000..3f6c95b394 --- /dev/null +++ b/apple/changelog.d/4199.added.5.md @@ -0,0 +1 @@ +Selecting a database, schema or object group in the sidebar can list its objects in the Objects tab. diff --git a/apple/changelog.d/4199.added.6.md b/apple/changelog.d/4199.added.6.md new file mode 100644 index 0000000000..99d14589b7 --- /dev/null +++ b/apple/changelog.d/4199.added.6.md @@ -0,0 +1 @@ +Optional toolbar buttons open tables, views, functions, users, a new query or a backup in one click. diff --git a/apple/changelog.d/4199.added.7.md b/apple/changelog.d/4199.added.7.md new file mode 100644 index 0000000000..750250d600 --- /dev/null +++ b/apple/changelog.d/4199.added.7.md @@ -0,0 +1 @@ +The toolbar's connection and database controls can be turned off in Settings > General. diff --git a/apple/changelog.d/4199.added.8.md b/apple/changelog.d/4199.added.8.md new file mode 100644 index 0000000000..ed66a07a05 --- /dev/null +++ b/apple/changelog.d/4199.added.8.md @@ -0,0 +1 @@ +The data grid header can show each column's type under its name. diff --git a/apple/changelog.d/4199.added.9.md b/apple/changelog.d/4199.added.9.md new file mode 100644 index 0000000000..199bb19066 --- /dev/null +++ b/apple/changelog.d/4199.added.9.md @@ -0,0 +1 @@ +The filter bar can edit the sort, take the filter as one WHERE condition, and run both with Apply Filter & Sort. diff --git a/apple/changelog.d/4199.added.md b/apple/changelog.d/4199.added.md new file mode 100644 index 0000000000..916f33acde --- /dev/null +++ b/apple/changelog.d/4199.added.md @@ -0,0 +1 @@ +Use Navigator Layout in Settings > General turns the layout options on together, and Use Standard Layout turns them off. diff --git a/apple/changelog.d/4199.changed.1.md b/apple/changelog.d/4199.changed.1.md new file mode 100644 index 0000000000..490f3d62ab --- /dev/null +++ b/apple/changelog.d/4199.changed.1.md @@ -0,0 +1 @@ +The Objects tab is a sortable list with a kind picker, a name filter, and Open, Delete, Import and Export buttons. diff --git a/apple/changelog.d/4199.changed.md b/apple/changelog.d/4199.changed.md new file mode 100644 index 0000000000..95c3f82f4f --- /dev/null +++ b/apple/changelog.d/4199.changed.md @@ -0,0 +1 @@ +Show All Tables is now Show Objects, on any database, schema or object group, for tables, views, routines and more. diff --git a/apple/changelog.d/4199.fixed.1.md b/apple/changelog.d/4199.fixed.1.md new file mode 100644 index 0000000000..eeb9fd1427 --- /dev/null +++ b/apple/changelog.d/4199.fixed.1.md @@ -0,0 +1 @@ +Text Voice Control or another assistive app put in the SQL editor never reached the tab, so Run stayed dim. diff --git a/apple/changelog.d/4199.fixed.2.md b/apple/changelog.d/4199.fixed.2.md new file mode 100644 index 0000000000..5a7e8cfded --- /dev/null +++ b/apple/changelog.d/4199.fixed.2.md @@ -0,0 +1 @@ +Double-clicking an empty part of a connection window's titlebar did nothing on macOS 26 and later. diff --git a/apple/changelog.d/4199.fixed.md b/apple/changelog.d/4199.fixed.md new file mode 100644 index 0000000000..290721a12f --- /dev/null +++ b/apple/changelog.d/4199.fixed.md @@ -0,0 +1 @@ +The completion list stayed open over the results after a query started running. From 9ec4889e2e8acb1cd316c3ff5167509f6c8652e3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 12 Nov 2026 10:56:38 +0700 Subject: [PATCH 122/123] style(macos): keep executeQueryInternal under the SwiftLint body limit after merging main --- apple/TablePro/Views/Main/MainContentCoordinator.swift | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index b32cba7f6d..c0483f37f0 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -1396,9 +1396,7 @@ final class MainContentCoordinator: ObservableObject { prepared: prepared ) // A re-read (a sort, a reload after a write) is not a run, so the log keeps describing the last one. - if recordsRun { - queryExecutionCoordinator.recordStatementRun(sql, tabId: tabId, startedAt: claim.startedAt) - } + if recordsRun { queryExecutionCoordinator.recordStatementRun(sql, tabId: tabId, startedAt: claim.startedAt) } scheduleTraceCompletion(traceToken, outcome: .completed) reportFetchedQuery(claim: claim, trigger: trigger, result: fetchResult) From d70d687cd5e20804f53a1f47e924c4143563c272 Mon Sep 17 00:00:00 2001 From: Thang Nguyen Date: Thu, 12 Nov 2026 20:01:35 +0700 Subject: [PATCH 123/123] fix(toolbar): save no toolbar arrangement from the test host or the storage sandbox AppKit files a toolbar's arrangement and display mode under its identifier in the real standard domain. The unit host and a sandboxed run therefore wrote over the arrangement the installed app reads, and the tests left one record per throwaway toolbar identifier behind. The toolbar now autosaves only outside both, the rule SplitViewAutosaveName.current(_:) already follows for split views. With nothing saved, each launch starts from the default items, while the records of what the arrangement carries stayed in the sandbox's defaults. A sandboxed run then kept the Objects buttons and labels out, so those records are cleared once per launch there. toolbarConfigurationEnablesAutosave and displayModeDefaultsToIconOnly pinned autosave on in the test host and now expect it off. Claude-Session: https://claude.ai/code/session_01YGAGXFgnFBqpj3tHLobCvs --- .../Infrastructure/MainWindowToolbar.swift | 34 ++++++++++++++++++- ...MainWindowToolbarNativeContractTests.swift | 29 +++++++++++++++- .../MainWindowToolbarValidationTests.swift | 8 +++-- 3 files changed, 66 insertions(+), 5 deletions(-) diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index 070fab0886..cc9993e97d 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -145,7 +145,16 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { /// reader who turns labels on keeps them. self.managedToolbar.displayMode = .iconOnly self.managedToolbar.allowsUserCustomization = true - self.managedToolbar.autosavesConfiguration = true + let environment = AppStorageEnvironment.shared + let autosaves = Self.autosavesArrangement( + isUnitTestHost: environment.isUnitTestHost, + isIsolated: environment.isIsolated + ) + self.managedToolbar.autosavesConfiguration = autosaves + if !autosaves, !Self.hasStartedArrangementRecordsOver { + Self.hasStartedArrangementRecordsOver = true + Self.startArrangementRecordsOver(in: environment.defaults) + } self.managedToolbar.centeredItemIdentifiers = [Self.connection, Self.database] /// The hop off `AppSettingsManager.keyboard`'s own `didSet` matters: without it the toolbar /// items are mutated re-entrantly, part way through the settings write that triggered them. @@ -624,6 +633,29 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { return inStep } + /// AppKit files the arrangement and the display mode under the toolbar's identifier in the real standard domain, which + /// the unit test host and the storage sandbox must leave alone, the reason `SplitViewAutosaveName.current(_:)` names no + /// split view there. A sandboxed run wrote its arrangement over the one the installed app reads. + nonisolated internal static func autosavesArrangement(isUnitTestHost: Bool, isIsolated: Bool) -> Bool { + !(isUnitTestHost || isIsolated) + } + + private static var hasStartedArrangementRecordsOver = false + + /// The records say what the saved arrangement already carries. With nothing saved, every launch starts from the + /// default items and the icon-only mode, while the records stay in the sandbox's defaults from the last run, so they + /// are cleared once per launch and the first reconcile adds the Objects buttons and labels again. + internal static func startArrangementRecordsOver(in defaults: UserDefaults) { + for key in [ + ToolbarDebugItemsRecord.key, + ToolbarObjectKindsRecord.key, + ToolbarLocationItemsRecord.key, + ToolbarLabelsRecord.key, + ] { + defaults.removeObject(forKey: key) + } + } + // Pushed by the one writer of a module's state, so no toolbar listens for module changes while the module is off. internal static func applyModuleChange() { for window in NSApp.windows { diff --git a/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift b/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift index ddfefcf26d..82469b1c4b 100644 --- a/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift +++ b/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift @@ -403,10 +403,37 @@ struct MainWindowToolbarNativeContractTests { func displayModeDefaultsToIconOnly() { let owner = MainWindowToolbar() #expect(owner.managedToolbar.displayMode == .iconOnly) - #expect(owner.managedToolbar.autosavesConfiguration) #expect(owner.managedToolbar.allowsUserCustomization) } + /// AppKit files the arrangement in the real standard domain, so a sandboxed run or a test wrote over the arrangement + /// the installed app reads. + @Test("Only the installed app saves the toolbar arrangement; the test host and the sandbox never write it") + func arrangementIsSavedOnlyOutsideTheTestHostAndTheSandbox() { + #expect(MainWindowToolbar.autosavesArrangement(isUnitTestHost: false, isIsolated: false)) + #expect(!MainWindowToolbar.autosavesArrangement(isUnitTestHost: true, isIsolated: false)) + #expect(!MainWindowToolbar.autosavesArrangement(isUnitTestHost: false, isIsolated: true)) + #expect(!MainWindowToolbar().managedToolbar.autosavesConfiguration) + } + + /// With nothing saved each launch starts from the default items, so records left by the last sandboxed run would + /// claim the Objects buttons and labels were already there and keep them out. + @Test("Starting the records over forgets what an unsaved arrangement carried") + func startingRecordsOverClearsThem() throws { + let storage = try EphemeralDefaults() + ToolbarDebugItemsRecord(defaults: storage.defaults).record(true) + ToolbarObjectKindsRecord(defaults: storage.defaults).record(true) + ToolbarLocationItemsRecord(defaults: storage.defaults).record(true) + ToolbarLabelsRecord(defaults: storage.defaults).record(true) + + MainWindowToolbar.startArrangementRecordsOver(in: storage.defaults) + + #expect(!ToolbarDebugItemsRecord(defaults: storage.defaults).isApplied) + #expect(!ToolbarObjectKindsRecord(defaults: storage.defaults).isApplied) + #expect(!ToolbarLocationItemsRecord(defaults: storage.defaults).isApplied) + #expect(!ToolbarLabelsRecord(defaults: storage.defaults).isApplied) + } + /// The HIG's macOS rule: "Make every toolbar item available as a command in the menu bar." The /// rewrite moved the sidebar's two lists out of the toolbar's segmented control and into the /// sidebar's own scope control, which a collapsed sidebar takes away with it, so the menu bar is diff --git a/apple/TableProTests/Services/MainWindowToolbarValidationTests.swift b/apple/TableProTests/Services/MainWindowToolbarValidationTests.swift index 7f9f2a0a8f..91e15cd44f 100644 --- a/apple/TableProTests/Services/MainWindowToolbarValidationTests.swift +++ b/apple/TableProTests/Services/MainWindowToolbarValidationTests.swift @@ -452,15 +452,17 @@ struct MainWindowToolbarValidationTests { #expect(toolbar.validationCount == invalidationBaseline) } - @Test("Toolbar is configured for user customization and autosave") - func toolbarConfigurationEnablesAutosave() { + /// The installed app saves the arrangement; this host must not, since AppKit writes it into the real standard domain. + /// `MainWindowToolbarNativeContractTests` checks both sides of that rule. + @Test("Toolbar is configured for user customization, and the test host saves no arrangement") + func toolbarConfigurationAllowsCustomization() { let coordinatorFixture = makeFixture() let coordinator = coordinatorFixture.coordinator let owner = MainWindowToolbar() owner.repoint(to: coordinator) #expect(owner.managedToolbar.identifier == MainWindowToolbar.toolbarIdentifier) #expect(owner.managedToolbar.allowsUserCustomization == true) - #expect(owner.managedToolbar.autosavesConfiguration == true) + #expect(owner.managedToolbar.autosavesConfiguration == false) } @Test("Allowed item identifiers are a superset of defaults so restored items survive autosave")