From 8d45f62e8495656aa0cdd0df2f16b24989fd3971 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 25 Nov 2026 11:00:53 +0700 Subject: [PATCH 1/2] feat(filter): list the filter column picker alphabetically on request Data-file filters, hidden columns and Display As now follow a column by id when an edit renames its neighbours, and Reset All Settings resets the Filters page. --- .../Core/Coordinators/FilterCoordinator.swift | 6 +- .../Core/DataFiles/DataFileColumnNames.swift | 6 ++ .../DataFileController+Editing.swift | 25 +---- .../DataFiles/DataFileController+Query.swift | 4 +- .../DataFiles/DataFileController+Undo.swift | 45 ++++++++- .../Core/DataFiles/DataFileController.swift | 35 +++++++ .../Services/Query/FilterColumnMenu.swift | 59 +++++++++--- .../Core/Storage/AppSettingsManager.swift | 1 + .../Core/Storage/FilterSettingsStorage.swift | 81 +++++++++++----- .../Database/TabFilterState+Editing.swift | 32 ++++--- .../TablePro/Models/Query/QueryTabState.swift | 47 ++++++++++ .../TablePro/Resources/Localizable.xcstrings | 12 +++ .../Views/DataFiles/DataFileFilterPanel.swift | 2 +- .../Views/Filter/FilterPanelView.swift | 27 +++++- .../TablePro/Views/Filter/FilterRowView.swift | 9 +- .../Views/Filter/NestedFieldPathPicker.swift | 19 +--- .../Sections/FilterSettingsPage.swift | 30 ++++-- .../Views/Settings/SettingsNavigation.swift | 1 + .../DataFiles/DataFileControllerTests.swift | 88 +++++++++++++++++- .../Core/Services/FilterColumnMenuTests.swift | 67 +++++++++++-- .../Storage/FilterSettingsStorageTests.swift | 93 ++++++++++++++++++- .../Models/TabFilterStateEditingTests.swift | 17 ++++ .../Views/Filter/FilterRowLayoutTests.swift | 5 +- .../Views/Filter/FilterRowViewTests.swift | 2 +- 24 files changed, 580 insertions(+), 133 deletions(-) diff --git a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift index 8c68577b14..3482c163ab 100644 --- a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift @@ -407,7 +407,7 @@ final class FilterCoordinator: ObservableObject { } func addFilterForColumn(_ columnName: String) { - let settings = FilterSettingsStorage.shared.loadSettings() + let settings = FilterSettingsStorage.shared.settings mutateSelectedTabFilterState { state in state.addFilter(forColumn: columnName, settings: settings) } @@ -466,7 +466,7 @@ final class FilterCoordinator: ObservableObject { guard !tab.tableContext.isTemporary, let tableName = tab.tableContext.tableName else { return } /// Turning saving off stops writing, and leaves what is already on disk alone. Falling /// through to an empty write would delete it, so the setting could never be turned back on. - guard FilterSettingsStorage.shared.loadSettings().restoreBehavior.savesToDisk else { return } + guard FilterSettingsStorage.shared.settings.restoreBehavior.savesToDisk else { return } let persisted = tab.filterState.persistedState FilterSettingsStorage.shared.saveLastFilters( persisted, @@ -478,7 +478,7 @@ final class FilterCoordinator: ObservableObject { } private func restoreLastFilters(for tableName: String, at index: Int) { - let settings = FilterSettingsStorage.shared.loadSettings() + let settings = FilterSettingsStorage.shared.settings guard index < parent.tabManager.tabs.count else { return } let tab = parent.tabManager.tabs[index] diff --git a/apple/TablePro/Core/DataFiles/DataFileColumnNames.swift b/apple/TablePro/Core/DataFiles/DataFileColumnNames.swift index 0d4b3209a2..1f3aeab8bb 100644 --- a/apple/TablePro/Core/DataFiles/DataFileColumnNames.swift +++ b/apple/TablePro/Core/DataFiles/DataFileColumnNames.swift @@ -47,6 +47,12 @@ struct DataFileColumnNames: Equatable { indexByID[id] } + // The name the same column has in `updated`, nil once it is gone. A name no column holds stays as it is. + func carrying(_ name: String, to updated: DataFileColumnNames) -> String? { + guard let id = id(forName: name) else { return name } + return updated.name(for: id) + } + private static func baseName(_ raw: String, position: Int) -> String { let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { diff --git a/apple/TablePro/Core/DataFiles/DataFileController+Editing.swift b/apple/TablePro/Core/DataFiles/DataFileController+Editing.swift index 93d533ce3b..4d6c63d7c0 100644 --- a/apple/TablePro/Core/DataFiles/DataFileController+Editing.swift +++ b/apple/TablePro/Core/DataFiles/DataFileController+Editing.swift @@ -180,37 +180,20 @@ extension DataFileController { func deleteColumns(_ ids: Set) { guard isEditable, !ids.isEmpty, var updated = table else { return } - let removedNames = ids.compactMap { columnNames.name(for: $0) } updated.deleteColumns(ids) - let referencedFilters = filterState.filtersOnAnyColumn(in: Set(removedNames)) - let referencedSort = sortReferences.contains { ids.contains($0.column) } commit( updated, - actionName: ids.count == 1 ? String(localized: "Delete Column") : String(localized: "Delete Columns"), - includesFilters: referencedFilters - ) { controller in - controller.columnLayout.hiddenColumns.subtract(removedNames) - controller.filterState.removeFilters(onColumns: Set(removedNames)) - } - if referencedFilters || referencedSort { - runQuery() - } + actionName: ids.count == 1 ? String(localized: "Delete Column") : String(localized: "Delete Columns") + ) } func renameColumn(_ id: TabularColumnID, to name: String) { - guard isEditable, var updated = table, let oldName = columnNames.name(for: id) else { return } + guard isEditable, var updated = table, columnNames.index(of: id) != nil else { return } if updated.headerRowKey == nil, updated.source.intrinsicColumnNames == nil { adoptDisplayNamesAsHeader(in: &updated) } updated.renameColumn(id, to: name) - let referencedFilters = filterState.filtersOnAnyColumn(in: [oldName]) - commit(updated, actionName: String(localized: "Rename Column"), includesFilters: referencedFilters) { controller in - guard let newName = controller.columnNames.name(for: id), newName != oldName else { return } - controller.filterState.renameFilterColumn(from: oldName, to: newName) - if controller.columnLayout.hiddenColumns.remove(oldName) != nil { - controller.columnLayout.hiddenColumns.insert(newName) - } - } + commit(updated, actionName: String(localized: "Rename Column")) } private func adoptDisplayNamesAsHeader(in table: inout TabularTable) { diff --git a/apple/TablePro/Core/DataFiles/DataFileController+Query.swift b/apple/TablePro/Core/DataFiles/DataFileController+Query.swift index c3be9ee203..741814d197 100644 --- a/apple/TablePro/Core/DataFiles/DataFileController+Query.swift +++ b/apple/TablePro/Core/DataFiles/DataFileController+Query.swift @@ -67,8 +67,8 @@ extension DataFileController { commitFilterState(filterState.removingAllFilters()) } - // Once a running row names a column the file no longer has, after a header row is toggled for - // instance, the filter stops rather than run without it under a panel that says it applies. + // Once a running row names a column the file no longer has, the filter stops rather than run + // without it under a panel that says it applies. private func dropFiltersTheFileCannotRun() { guard let applied = filterState.applied, !applied.filters.allSatisfy({ cellPredicate(for: $0) != nil }) else { return } diff --git a/apple/TablePro/Core/DataFiles/DataFileController+Undo.swift b/apple/TablePro/Core/DataFiles/DataFileController+Undo.swift index e517cce37e..f5fff65f16 100644 --- a/apple/TablePro/Core/DataFiles/DataFileController+Undo.swift +++ b/apple/TablePro/Core/DataFiles/DataFileController+Undo.swift @@ -17,6 +17,7 @@ struct DataFileEditState { let kindOverrides: [TabularColumnID: TabularInferredKind] let displayKeys: [Int]? let columnLayout: ColumnLayoutState + let displayFormats: [TabularColumnID: ValueDisplayFormat] let filterState: TabFilterState? let queryRevision: Int } @@ -30,6 +31,7 @@ extension DataFileController { kindOverrides: kindOverrides, displayKeys: displayKeys, columnLayout: columnLayout, + displayFormats: displayFormatsByColumn, filterState: includesFilters ? filterState : nil, queryRevision: queryRevision ) @@ -39,10 +41,13 @@ extension DataFileController { _ updated: TabularTable, actionName: String, displayKeys newDisplayKeys: [Int]?? = nil, - includesFilters: Bool = false, adjust: ((DataFileController) -> Void)? = nil ) { - guard let previous = captureEditState(queryRevision: currentQueryRevision, includesFilters: includesFilters) else { + // Removing a column takes the filter rows on it, so undo has to bring them back. + let dropsFilters = dropsFilterRows(updated) + let rerunsQuery = dropsFilterRows(updated, appliedOnly: true) + || sortReferences.contains { table?.columnIndex(of: $0.column) != nil && updated.columnIndex(of: $0.column) == nil } + guard let previous = captureEditState(queryRevision: currentQueryRevision, includesFilters: dropsFilters) else { return } replaceTable(updated) @@ -53,6 +58,9 @@ extension DataFileController { registerUndo(restoring: previous, actionName: actionName) onEdited?() refreshPage() + if rerunsQuery { + runQuery() + } } private func registerUndo(restoring state: DataFileEditState, actionName: String) { @@ -66,17 +74,24 @@ extension DataFileController { } private func restore(_ state: DataFileEditState, actionName: String) { - let includesFilters = state.filterState != nil + // Undoing an insert drops the filter rows on that column, so redo has to bring them back. + let includesFilters = state.filterState != nil || dropsFilterRows(state.table) guard let current = captureEditState(queryRevision: currentQueryRevision, includesFilters: includesFilters) else { return } let sortBefore = sortState + let returning = Set(state.table.columns.map(\.id)).subtracting(columnNames.ids) replaceTable(state.table) for (id, kind) in state.inferredKinds { setInferredKind(kind, for: id) } kindOverrides = state.kindOverrides - columnLayout = state.columnLayout + // Columns still here keep the layout and Display As set since; only the ones the undo brings back take theirs. + columnLayout = columnLayout.restoringColumns( + Set(returning.compactMap { columnNames.name(for: $0) }), + from: state.columnLayout + ) + restoreDisplayFormats(state.displayFormats, for: returning) if let filters = state.filterState { filterState = filters } @@ -89,4 +104,26 @@ extension DataFileController { runQuery() } } + + private var displayFormatsByColumn: [TabularColumnID: ValueDisplayFormat] { + let formats = gridModel.store.displayFormats + var byColumn: [TabularColumnID: ValueDisplayFormat] = [:] + for (index, id) in columnNames.ids.enumerated() where index < formats.count { + if let format = formats[index] { + byColumn[id] = format + } + } + return byColumn + } + + private func restoreDisplayFormats(_ saved: [TabularColumnID: ValueDisplayFormat], for ids: Set) { + var formats = gridModel.store.displayFormats + for id in ids { + guard let format = saved[id], let index = columnNames.index(of: id) else { continue } + formats = DisplayFormatArray.setting(format, at: index, in: formats, columnCount: columnNames.count) + } + if formats != gridModel.store.displayFormats { + gridModel.store.displayFormats = formats + } + } } diff --git a/apple/TablePro/Core/DataFiles/DataFileController.swift b/apple/TablePro/Core/DataFiles/DataFileController.swift index 6dadb8acdc..7c8d3eea67 100644 --- a/apple/TablePro/Core/DataFiles/DataFileController.swift +++ b/apple/TablePro/Core/DataFiles/DataFileController.swift @@ -501,14 +501,49 @@ final class DataFileController: ObservableObject { // Every edit, mutation and undo lands here, so find searches the file again. func replaceTable(_ newTable: TabularTable) { + let previousNames = columnNames table = newTable if sheets.indices.contains(selectedSheetIndex) { sheets[selectedSheetIndex].table = newTable } refreshColumnNames() + carryColumnState(from: previousNames) gridModel.findDatasetDidChange() } + // A display name depends on position (`Column 2`, `name (2)`), so inserting or deleting a column renames + // its neighbours. Filter rows, the layout and Display As follow the column by id instead. Not on a sheet + // switch: column ids repeat across sheets. + private func carryColumnState(from previous: DataFileColumnNames) { + let current = columnNames + guard previous != current else { return } + let newName = { (name: String) in previous.carrying(name, to: current) } + + var carried = filterState + carried.remapColumns(newName) + if carried != filterState { + filterState = carried + } + columnLayout = columnLayout.remappingColumns(newName) + + let formats = gridModel.store.displayFormats + if formats.contains(where: { $0 != nil }) { + gridModel.store.displayFormats = current.ids.map { id in + previous.index(of: id).flatMap { formats.indices.contains($0) ? formats[$0] : nil } + } + } + } + + // Whether `updated` lacks a column a filter row names, so committing it drops that row. + func dropsFilterRows(_ updated: TabularTable, appliedOnly: Bool = false) -> Bool { + let applied = filterState.applied?.filters ?? [] + let rows = appliedOnly ? applied : filterState.filters + applied + return rows.contains { row in + guard !row.isRawSQL, let id = columnNames.id(forName: row.columnName) else { return false } + return updated.columnIndex(of: id) == nil + } + } + func setInferredKind(_ kind: TabularInferredKind, for id: TabularColumnID) { inferredKinds[id] = kind } diff --git a/apple/TablePro/Core/Services/Query/FilterColumnMenu.swift b/apple/TablePro/Core/Services/Query/FilterColumnMenu.swift index 2a1ff9bbed..0da9088dc0 100644 --- a/apple/TablePro/Core/Services/Query/FilterColumnMenu.swift +++ b/apple/TablePro/Core/Services/Query/FilterColumnMenu.swift @@ -33,40 +33,55 @@ struct FilterColumnMenu: Equatable { static func build( columns: [String], fieldPaths: [PluginFieldPath], + order: FilterColumnOrder, depthLimit: Int = inlineDepthLimit, itemLimit: Int = inlineItemLimit ) -> FilterColumnMenu { let known = Set(columns) let nested = fieldPaths.filter { $0.depth > 1 && !known.contains($0.path) } - var order: [String] = [] - var byParent: [String: [PluginFieldPath]] = [:] - var inlineCount = 0 + // Picked in the driver's order before any sorting, so the order setting never changes which paths are inline. + var inline: [PluginFieldPath] = [] var skipped = false - for path in nested { - guard path.depth <= depthLimit, inlineCount < itemLimit else { + guard path.depth <= depthLimit, inline.count < itemLimit else { skipped = true continue } + inline.append(path) + } + + return FilterColumnMenu( + columns: order.ordered(columns), + groups: grouped(inline, order: order), + hasMorePaths: skipped || !nested.isEmpty + ) + } + + static func grouped(_ paths: [PluginFieldPath], order: FilterColumnOrder) -> [Group] { + var parents: [String] = [] + var byParent: [String: [PluginFieldPath]] = [:] + for path in paths { let parent = topLevelParent(of: path.path) if byParent[parent] == nil { - order.append(parent) + parents.append(parent) } byParent[parent, default: []].append(path) - inlineCount += 1 } - let groups = order.compactMap { parent -> Group? in + let groups = parents.compactMap { parent -> Group? in guard let paths = byParent[parent], !paths.isEmpty else { return nil } return Group(parent: parent, paths: paths) } - - return FilterColumnMenu( - columns: columns, - groups: groups, - hasMorePaths: skipped || !nested.isEmpty - ) + guard order == .alphabetical else { return groups } + return groups + .map { group in + Group( + parent: group.parent, + paths: group.paths.sorted { FilterColumnOrder.precedesAlphabetically($0.path, $1.path) } + ) + } + .sorted { FilterColumnOrder.precedesAlphabetically($0.parent, $1.parent) } } static func topLevelParent(of path: String) -> String { @@ -87,3 +102,19 @@ struct FilterColumnMenu: Equatable { columns.contains(column) || groups.contains { $0.paths.contains { $0.path == column } } } } + +// A filter bar redraws on every keystroke in a value field, and sorting a wide table's columns each time shows. +@MainActor +final class FilterColumnMenuCache { + private var inputs: (columns: [String], fieldPaths: [PluginFieldPath], order: FilterColumnOrder)? + private var menu = FilterColumnMenu.empty + + func menu(columns: [String], fieldPaths: [PluginFieldPath], order: FilterColumnOrder) -> FilterColumnMenu { + if let inputs, inputs.order == order, inputs.columns == columns, inputs.fieldPaths == fieldPaths { + return menu + } + menu = FilterColumnMenu.build(columns: columns, fieldPaths: fieldPaths, order: order) + inputs = (columns, fieldPaths, order) + return menu + } +} diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 099dd9e848..5d6a201306 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -144,6 +144,7 @@ final class AppSettingsManager { // The reset alert promises every section, so Sparkle's update preferences go too. SoftwareUpdater.shared.resetUpdatePreferences() AppModuleActivation.resetToDefaults() + FilterSettingsStorage.shared.resetSettings() } ) { self.storage = storage diff --git a/apple/TablePro/Core/Storage/FilterSettingsStorage.swift b/apple/TablePro/Core/Storage/FilterSettingsStorage.swift index 6854a332c8..7abde97920 100644 --- a/apple/TablePro/Core/Storage/FilterSettingsStorage.swift +++ b/apple/TablePro/Core/Storage/FilterSettingsStorage.swift @@ -3,6 +3,7 @@ // TablePro // +import Combine import Foundation import os @@ -53,6 +54,37 @@ enum FilterDefaultOperator: String, CaseIterable, Identifiable, Codable { } } +// Only the column picker follows it: a new row's default column and the value completions keep table order. +enum FilterColumnOrder: String, CaseIterable, Identifiable, Codable { + case table = "table" + case alphabetical = "alphabetical" + + var id: String { rawValue } + + var displayName: String { + switch self { + case .table: return String(localized: "Table Order") + case .alphabetical: return String(localized: "Alphabetical") + } + } + + func ordered(_ names: [String]) -> [String] { + switch self { + case .table: return names + case .alphabetical: return names.sorted(by: Self.precedesAlphabetically) + } + } + + // Finder order, so col2 lands before col10; the ordinal compare keeps names the locale ties in a fixed order. + static func precedesAlphabetically(_ lhs: String, _ rhs: String) -> Bool { + switch lhs.localizedStandardCompare(rhs) { + case .orderedAscending: return true + case .orderedDescending: return false + case .orderedSame: return lhs < rhs + } + } +} + /// What reopening a table does with the filter rows saved for it. enum FilterRestoreBehavior: String, CaseIterable, Identifiable, Codable { case restoreAndApply = "restoreAndApply" @@ -106,21 +138,24 @@ struct FilterSettings: Codable, Equatable { var defaultOperator: FilterDefaultOperator var restoreBehavior: FilterRestoreBehavior var alwaysShowPanel: Bool + var columnOrder: FilterColumnOrder init( defaultColumn: FilterDefaultColumn = .rawSQL, defaultOperator: FilterDefaultOperator = .equal, restoreBehavior: FilterRestoreBehavior = .restoreAndApply, - alwaysShowPanel: Bool = false + alwaysShowPanel: Bool = false, + columnOrder: FilterColumnOrder = .table ) { self.defaultColumn = defaultColumn self.defaultOperator = defaultOperator self.restoreBehavior = restoreBehavior self.alwaysShowPanel = alwaysShowPanel + self.columnOrder = columnOrder } private enum CodingKeys: String, CodingKey { - case defaultColumn, defaultOperator, restoreBehavior, alwaysShowPanel, panelState + case defaultColumn, defaultOperator, restoreBehavior, alwaysShowPanel, columnOrder, panelState } /// Reads the split fields, and falls back to the single `panelState` a file written before the @@ -140,6 +175,8 @@ struct FilterSettings: Codable, Equatable { self.alwaysShowPanel = try container.decodeIfPresent( Bool.self, forKey: .alwaysShowPanel ) ?? legacy?.alwaysShowPanel ?? false + // An order a later build added must not throw here, or every filter setting falls back to its default. + self.columnOrder = (try? container.decodeIfPresent(FilterColumnOrder.self, forKey: .columnOrder)) ?? .table } /// `panelState` goes back in as the nearest of the three old cases. A build from before the @@ -152,6 +189,7 @@ struct FilterSettings: Codable, Equatable { try container.encode(defaultOperator, forKey: .defaultOperator) try container.encode(restoreBehavior, forKey: .restoreBehavior) try container.encode(alwaysShowPanel, forKey: .alwaysShowPanel) + try container.encode(columnOrder, forKey: .columnOrder) try container.encode(legacyPanelState, forKey: .panelState) } @@ -162,7 +200,7 @@ struct FilterSettings: Codable, Equatable { } @MainActor -final class FilterSettingsStorage: TableScopedSettingsStore { +final class FilterSettingsStorage: ObservableObject, TableScopedSettingsStore { static let shared = FilterSettingsStorage() nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "FilterSettingsStorage") @@ -180,7 +218,8 @@ final class FilterSettingsStorage: TableScopedSettingsStore { private let decoder = JSONDecoder() private let ioQueue = DispatchQueue(label: "com.TablePro.FilterSettingsStorage.io", qos: .utility) - private var cachedSettings: FilterSettings? + // Published so an open filter bar and the Settings page follow a change made in the other. + @Published private(set) var settings: FilterSettings private var lastFiltersCache: [String: PersistedFilterState] = [:] private var browseSearchCache: [String: BrowseSearchState] = [:] @@ -191,6 +230,7 @@ final class FilterSettingsStorage: TableScopedSettingsStore { init(filterStateDirectory: URL, defaults: UserDefaults) { self.filterStateDirectory = filterStateDirectory self.defaults = defaults + self.settings = Self.decodedSettings(from: defaults) do { try FileManager.default.createDirectory( @@ -205,37 +245,32 @@ final class FilterSettingsStorage: TableScopedSettingsStore { Self.performCompositeKeyMigrationIfNeeded(filterStateDirectory: filterStateDirectory, defaults: defaults) } - func loadSettings() -> FilterSettings { - if let cached = cachedSettings { return cached } - - guard let data = defaults.data(forKey: Self.settingsKey) else { - let defaultSettings = FilterSettings() - cachedSettings = defaultSettings - return defaultSettings - } - + private static func decodedSettings(from defaults: UserDefaults) -> FilterSettings { + guard let data = defaults.data(forKey: settingsKey) else { return FilterSettings() } do { - let decoded = try decoder.decode(FilterSettings.self, from: data) - cachedSettings = decoded - return decoded + return try JSONDecoder().decode(FilterSettings.self, from: data) } catch { - Self.logger.error("Failed to decode filter settings: \(error)") - let defaultSettings = FilterSettings() - cachedSettings = defaultSettings - return defaultSettings + logger.error("Failed to decode filter settings: \(error)") + return FilterSettings() } } - func saveSettings(_ settings: FilterSettings) { - cachedSettings = settings + func saveSettings(_ newSettings: FilterSettings) { + guard newSettings != settings else { return } + settings = newSettings do { - let data = try encoder.encode(settings) + let data = try encoder.encode(newSettings) defaults.set(data, forKey: Self.settingsKey) } catch { Self.logger.error("Failed to encode filter settings: \(error)") } } + func resetSettings() { + defaults.removeObject(forKey: Self.settingsKey) + settings = FilterSettings() + } + func loadLastFilters( for tableName: String, connectionId: UUID, diff --git a/apple/TablePro/Models/Database/TabFilterState+Editing.swift b/apple/TablePro/Models/Database/TabFilterState+Editing.swift index 4ce78727e2..a7f1aa7f77 100644 --- a/apple/TablePro/Models/Database/TabFilterState+Editing.swift +++ b/apple/TablePro/Models/Database/TabFilterState+Editing.swift @@ -164,22 +164,28 @@ internal extension TabFilterState { // The draft and what runs both follow a renamed column, or a rerun would look for the old name. mutating func renameFilterColumn(from oldName: String, to newName: String) { - let rename = { (rows: [TableFilter]) -> [TableFilter] in - rows.map { row in - guard !row.isRawSQL, row.columnName == oldName else { return row } - var renamed = row - renamed.columnName = newName - return renamed - } - } - filters = rename(filters) - applied = applied?.mapFilters(rename) + remapColumns { $0 == oldName ? newName : $0 } } mutating func removeFilters(onColumns names: Set) { - let keeps = { (row: TableFilter) in row.isRawSQL || !names.contains(row.columnName) } - filters = filters.filter(keeps) - applied = applied?.mapFilters { $0.filter(keeps) } + remapColumns { names.contains($0) ? nil : $0 } + } + + // One pass, so two columns that trade names move together instead of landing on the same one. + // A nil name removes the row. + mutating func remapColumns(_ newName: (String) -> String?) { + filters = Self.remapping(filters, newName) + applied = applied?.mapFilters { Self.remapping($0, newName) } + } + + private static func remapping(_ rows: [TableFilter], _ newName: (String) -> String?) -> [TableFilter] { + rows.compactMap { row in + guard !row.isRawSQL else { return row } + guard let name = newName(row.columnName) else { return nil } + var moved = row + moved.columnName = name + return moved + } } mutating func setAllFiltersEnabled(_ isEnabled: Bool) { diff --git a/apple/TablePro/Models/Query/QueryTabState.swift b/apple/TablePro/Models/Query/QueryTabState.swift index 519ff961a2..b1d2b7bed6 100644 --- a/apple/TablePro/Models/Query/QueryTabState.swift +++ b/apple/TablePro/Models/Query/QueryTabState.swift @@ -770,3 +770,50 @@ struct TabDisplayState: Equatable { && lhs.highlightRulesPresentationRequest == rhs.highlightRulesPresentationRequest } } + +extension ColumnLayoutState { + // Every key at once, so two columns that trade names keep their own entries. A nil name drops the column's entries. + func remappingColumns(_ newName: (String) -> String?) -> ColumnLayoutState { + var layout = self + layout.columnWidths = Self.remapping(columnWidths, newName) + layout.columnContentWidths = columnContentWidths.map { Self.remapping($0, newName) } + layout.columnOrder = columnOrder?.compactMap { newName($0) } + layout.hiddenColumns = Set(hiddenColumns.compactMap { newName($0) }) + return layout + } + + // Columns an undo brings back take the entries they had then; every other column keeps what it has now. + func restoringColumns(_ names: Set, from saved: ColumnLayoutState) -> ColumnLayoutState { + guard !names.isEmpty else { return self } + var layout = self + for name in names { + if saved.hiddenColumns.contains(name) { + layout.hiddenColumns.insert(name) + } + if let width = saved.columnWidths[name] { + layout.columnWidths[name] = width + } + if let width = saved.columnContentWidths?[name] { + layout.columnContentWidths = (layout.columnContentWidths ?? [:]).merging([name: width]) { $1 } + } + } + // A name missing from the order lands after every ordered column, so put it back in its old slot. + if var order = layout.columnOrder, let savedOrder = saved.columnOrder { + for (index, name) in savedOrder.enumerated() where names.contains(name) && !order.contains(name) { + order.insert(name, at: min(index, order.count)) + } + layout.columnOrder = order + } + return layout + } + + private static func remapping(_ widths: [String: CGFloat], _ newName: (String) -> String?) -> [String: CGFloat] { + var remapped: [String: CGFloat] = [:] + for (name, width) in widths { + if let moved = newName(name) { + remapped[moved] = width + } + } + return remapped + } +} diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index ec7b5a4671..5250747456 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -27380,6 +27380,9 @@ } } } + }, + "Alphabetical" : { + }, "Already in the target." : { "localizations" : { @@ -51165,6 +51168,9 @@ } } } + }, + "Column Picker" : { + }, "Column Reorder Failed" : { "localizations" : { @@ -118145,6 +118151,9 @@ } } } + }, + "List Columns Alphabetically" : { + }, "List Connections" : { "localizations" : { @@ -204940,6 +204949,9 @@ } } } + }, + "Table Order" : { + }, "Table rebuild" : { "localizations" : { diff --git a/apple/TablePro/Views/DataFiles/DataFileFilterPanel.swift b/apple/TablePro/Views/DataFiles/DataFileFilterPanel.swift index 014a67bbf0..54b05bc433 100644 --- a/apple/TablePro/Views/DataFiles/DataFileFilterPanel.swift +++ b/apple/TablePro/Views/DataFiles/DataFileFilterPanel.swift @@ -39,6 +39,6 @@ extension DataFileController: FilterPanelActions { } func addBlankFilter(columnName: String) { - filterState.addFilter(forColumn: columnName, settings: FilterSettingsStorage.shared.loadSettings()) + filterState.addFilter(forColumn: columnName, settings: FilterSettingsStorage.shared.settings) } } diff --git a/apple/TablePro/Views/Filter/FilterPanelView.swift b/apple/TablePro/Views/Filter/FilterPanelView.swift index c9146b8cfe..3f8a7b4923 100644 --- a/apple/TablePro/Views/Filter/FilterPanelView.swift +++ b/apple/TablePro/Views/Filter/FilterPanelView.swift @@ -6,6 +6,8 @@ struct FilterPanelView: View { let configuration: FilterPanelConfiguration let actions: any FilterPanelActions + @ObservedObject private var filterSettings = FilterSettingsStorage.shared + @State private var columnMenuCache = FilterColumnMenuCache() @State private var showSQLSheet = false @State private var generatedSQL = "" @State private var showSavePresetAlert = false @@ -185,6 +187,8 @@ struct FilterPanelView: View { Divider() + Toggle(String(localized: "List Columns Alphabetically"), isOn: listsColumnsAlphabetically) + Button { actions.openFilterSettings() } label: { @@ -244,13 +248,13 @@ struct FilterPanelView: View { ForEach(state.filters) { filter in FilterRowView( filter: filterBinding(for: filter), - columns: configuration.columns, + columnMenu: columnMenu, completions: completionItems, caseMatching: configuration.caseMatching, enumValuesByColumn: configuration.enumValuesByColumn, rawSQLCompletionProvider: configuration.rawSQLCompletionProvider, - columnMenu: columnMenu, fieldPaths: configuration.fieldPaths, + columnOrder: filterSettings.settings.columnOrder, offersRawFilter: configuration.offersRawFilter, rawFilterLabel: configuration.rawFilterLabel, reservesElementScope: reservesElementScope, @@ -315,7 +319,22 @@ struct FilterPanelView: View { } private var columnMenu: FilterColumnMenu { - FilterColumnMenu.build(columns: configuration.columns, fieldPaths: configuration.fieldPaths) + columnMenuCache.menu( + columns: configuration.columns, + fieldPaths: configuration.fieldPaths, + order: filterSettings.settings.columnOrder + ) + } + + private var listsColumnsAlphabetically: Binding { + Binding( + get: { filterSettings.settings.columnOrder == .alphabetical }, + set: { isOn in + var settings = filterSettings.settings + settings.columnOrder = isOn ? .alphabetical : .table + filterSettings.saveSettings(settings) + } + ) } private func filterBinding(for filter: TableFilter) -> Binding { @@ -328,7 +347,7 @@ struct FilterPanelView: View { private func addDefaultFilter(columns: [String], after anchorID: UUID? = nil) -> UUID { state.addFilter( - settings: FilterSettingsStorage.shared.loadSettings(), + settings: filterSettings.settings, columns: columns, primaryKeyColumn: configuration.primaryKeyColumn, offersRawFilter: configuration.offersRawFilter, diff --git a/apple/TablePro/Views/Filter/FilterRowView.swift b/apple/TablePro/Views/Filter/FilterRowView.swift index e311f0738e..da37f913c1 100644 --- a/apple/TablePro/Views/Filter/FilterRowView.swift +++ b/apple/TablePro/Views/Filter/FilterRowView.swift @@ -8,13 +8,13 @@ import TableProPluginKit struct FilterRowView: View { @Binding var filter: TableFilter - let columns: [String] + let columnMenu: FilterColumnMenu let completions: [String] var caseMatching: FilterCaseMatching = .engine(.unsupported) var enumValuesByColumn: [String: [String]] = [:] var rawSQLCompletionProvider: RawSQLFilterCompletionProvider? - var columnMenu: FilterColumnMenu = .empty var fieldPaths: [PluginFieldPath] = [] + var columnOrder: FilterColumnOrder = .table var offersRawFilter = true var rawFilterLabel = String(localized: "Raw SQL") var reservesElementScope = false @@ -200,7 +200,7 @@ struct FilterRowView: View { // Sized from the items every row shares, so a row with a drifted or raw item lines up with the rest. private var columnCellWidth: CGFloat { let paths = columnMenu.groups.flatMap { $0.paths.map(\.path) } - let titles = (offersRawFilter ? [rawFilterLabel] : []) + columns + paths + let titles = (offersRawFilter ? [rawFilterLabel] : []) + columnMenu.columns + paths return min(FilterControlMetrics.popUpWidth(titles: titles), Self.columnPickerMaximumWidth) } @@ -210,7 +210,7 @@ struct FilterRowView: View { Text(rawFilterLabel).tag(String?.none) Divider() } - ForEach(columns, id: \.self) { column in + ForEach(columnMenu.columns, id: \.self) { column in Text(column).tag(String?.some(column)) } ForEach(columnMenu.groups) { group in @@ -254,6 +254,7 @@ struct FilterRowView: View { .popover(isPresented: $showNestedPathPicker, arrowEdge: .bottom) { NestedFieldPathPicker( fieldPaths: fieldPaths, + order: columnOrder, currentValue: filter.columnName, onCommit: { filter = filter.selectingColumn($0) }, onDismiss: { showNestedPathPicker = false } diff --git a/apple/TablePro/Views/Filter/NestedFieldPathPicker.swift b/apple/TablePro/Views/Filter/NestedFieldPathPicker.swift index d18a32fbba..b082337e92 100644 --- a/apple/TablePro/Views/Filter/NestedFieldPathPicker.swift +++ b/apple/TablePro/Views/Filter/NestedFieldPathPicker.swift @@ -11,6 +11,7 @@ import TableProPluginKit /// the search field doubles as free-text entry for a field the sample never saw. struct NestedFieldPathPicker: View { let fieldPaths: [PluginFieldPath] + let order: FilterColumnOrder let currentValue: String let onCommit: (String) -> Void let onDismiss: () -> Void @@ -22,22 +23,8 @@ struct NestedFieldPathPicker: View { private static let searchAreaHeight: CGFloat = 44 private static let maxTotalHeight: CGFloat = 360 - private var visibleGroups: [(parent: String, paths: [PluginFieldPath])] { - var order: [String] = [] - var byParent: [String: [PluginFieldPath]] = [:] - - for path in fieldPaths where path.depth > 1 && matches(path.path) { - let parent = FilterColumnMenu.topLevelParent(of: path.path) - if byParent[parent] == nil { - order.append(parent) - } - byParent[parent, default: []].append(path) - } - - return order.compactMap { parent in - guard let paths = byParent[parent] else { return nil } - return (parent: parent, paths: paths) - } + private var visibleGroups: [FilterColumnMenu.Group] { + FilterColumnMenu.grouped(fieldPaths.filter { $0.depth > 1 && matches($0.path) }, order: order) } private func matches(_ path: String) -> Bool { diff --git a/apple/TablePro/Views/Settings/Sections/FilterSettingsPage.swift b/apple/TablePro/Views/Settings/Sections/FilterSettingsPage.swift index 6251504c07..7a5b27d173 100644 --- a/apple/TablePro/Views/Settings/Sections/FilterSettingsPage.swift +++ b/apple/TablePro/Views/Settings/Sections/FilterSettingsPage.swift @@ -6,18 +6,23 @@ import SwiftUI struct FilterSettingsPage: View { - @State private var settings = FilterSettingsStorage.shared.loadSettings() + // The filter bar's ⋯ menu writes the column order too, so the page reads the store rather than a copy. + @ObservedObject private var storage = FilterSettingsStorage.shared + + private var settings: Binding { + Binding(get: { storage.settings }, set: { storage.saveSettings($0) }) + } var body: some View { Form { Section { - Picker("Default column", selection: $settings.defaultColumn) { + Picker("Default column", selection: settings.defaultColumn) { ForEach(FilterDefaultColumn.allCases) { option in Text(option.displayName).tag(option) } } - Picker("Default operator", selection: $settings.defaultOperator) { + Picker("Default operator", selection: settings.defaultOperator) { ForEach(FilterDefaultOperator.allCases) { option in Text(option.displayName).tag(option) } @@ -27,16 +32,26 @@ struct FilterSettingsPage: View { } Section { - Picker(selection: $settings.restoreBehavior) { + Picker("Column order", selection: settings.columnOrder) { + ForEach(FilterColumnOrder.allCases) { option in + Text(option.displayName).tag(option) + } + } + } header: { + Text("Column Picker") + } + + Section { + Picker(selection: settings.restoreBehavior) { ForEach(FilterRestoreBehavior.allCases) { option in Text(option.displayName).tag(option) } } label: { Text("Saved filters") - Text(settings.restoreBehavior.settingsFooter) + Text(storage.settings.restoreBehavior.settingsFooter) } - Toggle("Always show the filter bar", isOn: $settings.alwaysShowPanel) + Toggle("Always show the filter bar", isOn: settings.alwaysShowPanel) } header: { Text("Reopening a Table") } @@ -44,8 +59,5 @@ struct FilterSettingsPage: View { .formStyle(.grouped) .accessibilityElement(children: .contain) .accessibilityIdentifier(SettingsPage.filters.pageIdentifier) - .onChange(of: settings) { newValue in - FilterSettingsStorage.shared.saveSettings(newValue) - } } } diff --git a/apple/TablePro/Views/Settings/SettingsNavigation.swift b/apple/TablePro/Views/Settings/SettingsNavigation.swift index 37fa07a0e8..8916d3c4e6 100644 --- a/apple/TablePro/Views/Settings/SettingsNavigation.swift +++ b/apple/TablePro/Views/Settings/SettingsNavigation.swift @@ -455,6 +455,7 @@ extension SettingsPage { [ String(localized: "Default column"), String(localized: "Default operator"), + String(localized: "Column order"), String(localized: "Saved filters"), String(localized: "Always show the filter bar"), ] diff --git a/apple/TableProTests/Core/DataFiles/DataFileControllerTests.swift b/apple/TableProTests/Core/DataFiles/DataFileControllerTests.swift index 6ed38841c3..10af5756c6 100644 --- a/apple/TableProTests/Core/DataFiles/DataFileControllerTests.swift +++ b/apple/TableProTests/Core/DataFiles/DataFileControllerTests.swift @@ -796,8 +796,8 @@ struct DataFileControllerTests { #expect(column(controller, 0) == ["B"]) } - @Test("Filters on columns a header toggle renamed stop counting as applied") - func headerToggleDropsUnresolvableFilters() async throws { + @Test("Filters follow their column through a header toggle") + func headerToggleCarriesFilters() async throws { let (controller, _) = try await loaded("name,city\nA,Paris\nB,London\n") controller.filterState.filters = [TableFilter(columnName: "city", value: "London")] controller.applyCheckedFilters() @@ -806,8 +806,90 @@ struct DataFileControllerTests { controller.setUsesFirstRowAsHeader(false) await controller.waitForPendingWork() + #expect(controller.filterState.filters.map(\.columnName) == ["Column 2"]) + #expect(controller.filterState.applied?.filters.map(\.columnName) == ["Column 2"]) + #expect(column(controller, 0) == ["B"]) + } + + @Test("Deleting a column keeps filters, hidden columns and Display As on their own columns") + func deleteKeepsColumnStateOnItsColumn() async throws { + let (controller, _) = try await loaded("name,name,city\nA,x,Paris\nB,y,London\n") + #expect(controller.columnNames.displayNames == ["name", "name (2)", "city"]) + controller.filterState.filters = [TableFilter(columnName: "name (2)", value: "y")] + controller.applyCheckedFilters() + await controller.waitForPendingWork() + controller.columnLayout.hiddenColumns = ["name (2)"] + controller.gridModel.store.displayFormats = [nil, nil, .json] + + controller.deleteColumns([controller.columnNames.ids[0]]) + await controller.waitForPendingWork() + + #expect(controller.columnNames.displayNames == ["name", "city"]) + #expect(controller.filterState.filters.map(\.columnName) == ["name"]) + #expect(controller.filterState.applied?.filters.map(\.columnName) == ["name"]) + #expect(controller.columnLayout.hiddenColumns == ["name"]) + #expect(controller.gridModel.store.displayFormats == [nil, .json]) + #expect(column(controller, 1) == ["London"]) + + controller.undoManager?.undo() + await controller.waitForPendingWork() + + #expect(controller.filterState.applied?.filters.map(\.columnName) == ["name (2)"]) + #expect(controller.columnLayout.hiddenColumns == ["name (2)"]) + #expect(controller.gridModel.store.displayFormats == [nil, nil, .json]) + } + + @Test("Undoing a cell edit keeps the Display As and hidden columns chosen after it") + func undoKeepsLaterColumnChoices() async throws { + let (controller, _) = try await loaded("name,payload\nA,{}\nB,[]\n") + controller.setCell(pageRow: 0, column: 0, text: "Z") + controller.gridModel.store.displayFormats = [nil, .json] + controller.columnLayout.hiddenColumns = ["name"] + + controller.undoManager?.undo() + await controller.waitForPendingWork() + + #expect(column(controller, 0) == ["A", "B"]) + #expect(controller.gridModel.store.displayFormats == [nil, .json]) + #expect(controller.columnLayout.hiddenColumns == ["name"]) + } + + @Test("Inserting a column with a taken name leaves a filter on the column it was set on") + func insertKeepsFilterOnItsColumn() async throws { + let (controller, _) = try await loaded("name,name\nA,x\nB,y\n") + controller.filterState.filters = [TableFilter(columnName: "name", value: "A")] + controller.applyCheckedFilters() + await controller.waitForPendingWork() + + controller.insertColumn(named: "name", at: 0) + controller.applyCheckedFilters() + await controller.waitForPendingWork() + + #expect(controller.columnNames.displayNames == ["name", "name (2)", "name (3)"]) + #expect(controller.filterState.applied?.filters.map(\.columnName) == ["name (2)"]) + #expect(column(controller, 1) == ["A"]) + } + + @Test("Splitting a filtered column drops its filter, reruns, and undo brings the filter back") + func splitDropsFilterAndUndoRestoresIt() async throws { + let (controller, _) = try await loaded("name,city\nA,Paris Nord\nB,London\n") + controller.filterState.filters = [TableFilter(columnName: "city", filterOperator: .contains, value: "Paris")] + controller.applyCheckedFilters() + await controller.waitForPendingWork() + #expect(controller.visibleRowCount == 1) + + controller.splitColumn(controller.columnNames.ids[1], separator: .literal(" ")) + await controller.waitForPendingWork() + + #expect(controller.filterState.filters.isEmpty) #expect(controller.filterState.applied == nil) - #expect(controller.visibleRowCount == 3) + #expect(controller.visibleRowCount == 2) + + controller.undoManager?.undo() + await controller.waitForPendingWork() + + #expect(controller.filterState.applied?.filters.map(\.columnName) == ["city"]) + #expect(controller.visibleRowCount == 1) } @Test("Undoing a column delete brings back its filter and sort") diff --git a/apple/TableProTests/Core/Services/FilterColumnMenuTests.swift b/apple/TableProTests/Core/Services/FilterColumnMenuTests.swift index 840968fa24..075d82c35c 100644 --- a/apple/TableProTests/Core/Services/FilterColumnMenuTests.swift +++ b/apple/TableProTests/Core/Services/FilterColumnMenuTests.swift @@ -27,7 +27,7 @@ struct FilterColumnMenuTests { @Test("nested paths group under their top-level parent, in first-seen order") func groupsByParent() { - let menu = FilterColumnMenu.build(columns: ["_id", "customer", "items"], fieldPaths: orderPaths) + let menu = FilterColumnMenu.build(columns: ["_id", "customer", "items"], fieldPaths: orderPaths, order: .table) #expect(menu.groups.map(\.parent) == ["customer", "items"]) #expect(menu.groups[0].paths.map(\.path) == ["customer.name", "customer.country"]) #expect(menu.groups[1].paths.map(\.path) == ["items.sku", "items.price"]) @@ -37,21 +37,22 @@ struct FilterColumnMenuTests { func skipsExistingColumns() { let menu = FilterColumnMenu.build( columns: ["customer.name"], - fieldPaths: [path("customer.name", depth: 2)] + fieldPaths: [path("customer.name", depth: 2)], + order: .table ) #expect(menu.groups.isEmpty) } @Test("top-level paths stay out of the nested section") func skipsTopLevelPaths() { - let menu = FilterColumnMenu.build(columns: ["a"], fieldPaths: [path("a", depth: 1)]) + let menu = FilterColumnMenu.build(columns: ["a"], fieldPaths: [path("a", depth: 1)], order: .table) #expect(menu.groups.isEmpty) } @Test("paths deeper than the inline limit are left to the searchable picker") func depthLimitDefersToPicker() { let deep = [path("a.b", depth: 2), path("a.b.c", depth: 3)] - let menu = FilterColumnMenu.build(columns: ["a"], fieldPaths: deep, depthLimit: 2) + let menu = FilterColumnMenu.build(columns: ["a"], fieldPaths: deep, order: .table, depthLimit: 2) #expect(menu.groups.flatMap { $0.paths.map(\.path) } == ["a.b"]) #expect(menu.hasMorePaths) } @@ -59,26 +60,78 @@ struct FilterColumnMenuTests { @Test("the inline item cap stops the menu growing without bound") func itemLimitCapsMenu() { let many = (0 ..< 40).map { path("a.f\($0)", depth: 2) } - let menu = FilterColumnMenu.build(columns: ["a"], fieldPaths: many, itemLimit: 10) + let menu = FilterColumnMenu.build(columns: ["a"], fieldPaths: many, order: .table, itemLimit: 10) #expect(menu.groups.flatMap(\.paths).count == 10) #expect(menu.hasMorePaths) } @Test("no nested paths means no overflow affordance") func noPathsMeansNoOverflow() { - let menu = FilterColumnMenu.build(columns: ["a", "b"], fieldPaths: []) + let menu = FilterColumnMenu.build(columns: ["a", "b"], fieldPaths: [], order: .table) #expect(menu.groups.isEmpty) #expect(!menu.hasMorePaths) } @Test("membership covers both flat columns and inline nested paths") func containsCoversBoth() { - let menu = FilterColumnMenu.build(columns: ["_id", "items"], fieldPaths: orderPaths) + let menu = FilterColumnMenu.build(columns: ["_id", "items"], fieldPaths: orderPaths, order: .table) #expect(menu.contains("_id")) #expect(menu.contains("items.sku")) #expect(!menu.contains("items.missing")) } + // MARK: - Order + + @Test("table order keeps the columns as the table lists them") + func tableOrderKeepsColumns() { + let menu = FilterColumnMenu.build(columns: ["id", "zone", "Amount"], fieldPaths: [], order: .table) + #expect(menu.columns == ["id", "zone", "Amount"]) + } + + @Test("alphabetical order sorts columns the way Finder does") + func alphabeticalSortsColumns() { + let menu = FilterColumnMenu.build( + columns: ["id", "col10", "zone", "Amount", "col2", "émail"], + fieldPaths: [], + order: .alphabetical + ) + #expect(menu.columns == ["Amount", "col2", "col10", "émail", "id", "zone"]) + } + + @Test("names that differ only in case keep one order whatever order they arrive in") + func alphabeticalOrderIsStableForCaseVariants() { + let forward = FilterColumnMenu.build(columns: ["name", "Name", "NAME"], fieldPaths: [], order: .alphabetical) + let reversed = FilterColumnMenu.build(columns: ["NAME", "Name", "name"], fieldPaths: [], order: .alphabetical) + #expect(forward.columns == reversed.columns) + #expect(Set(forward.columns) == ["name", "Name", "NAME"]) + } + + @Test("alphabetical order sorts nested groups and the paths inside them") + func alphabeticalSortsGroups() { + let menu = FilterColumnMenu.build(columns: ["items", "customer"], fieldPaths: orderPaths, order: .alphabetical) + #expect(menu.groups.map(\.parent) == ["customer", "items"]) + #expect(menu.groups[0].paths.map(\.path) == ["customer.country", "customer.name"]) + #expect(menu.groups[1].paths.map(\.path) == ["items.price", "items.sku"]) + } + + @Test("the order never changes which paths fit in the menu") + func orderKeepsInlinePaths() { + let paths = (0..<12).reversed().map { path("a.f\($0)", depth: 2) } + let byTable = FilterColumnMenu.build(columns: ["a"], fieldPaths: paths, order: .table, itemLimit: 5) + let byName = FilterColumnMenu.build(columns: ["a"], fieldPaths: paths, order: .alphabetical, itemLimit: 5) + #expect(Set(byName.groups.flatMap { $0.paths.map(\.path) }) == Set(byTable.groups.flatMap { $0.paths.map(\.path) })) + #expect(byName.groups.flatMap { $0.paths.map(\.path) } == ["a.f7", "a.f8", "a.f9", "a.f10", "a.f11"]) + } + + @Test("the cache rebuilds only when the columns, paths or order change") + @MainActor + func cacheFollowsInputs() { + let cache = FilterColumnMenuCache() + #expect(cache.menu(columns: ["b", "a"], fieldPaths: [], order: .table).columns == ["b", "a"]) + #expect(cache.menu(columns: ["b", "a"], fieldPaths: [], order: .alphabetical).columns == ["a", "b"]) + #expect(cache.menu(columns: ["c", "b", "a"], fieldPaths: [], order: .alphabetical).columns == ["a", "b", "c"]) + } + // MARK: - Element Scope @Test("a path with one array ancestor offers that ancestor as its scope") diff --git a/apple/TableProTests/Core/Storage/FilterSettingsStorageTests.swift b/apple/TableProTests/Core/Storage/FilterSettingsStorageTests.swift index 8deeaad541..8e57cc4adb 100644 --- a/apple/TableProTests/Core/Storage/FilterSettingsStorageTests.swift +++ b/apple/TableProTests/Core/Storage/FilterSettingsStorageTests.swift @@ -3,6 +3,7 @@ // TableProTests // +import Combine import Foundation @testable import TablePro import Testing @@ -372,8 +373,8 @@ struct FilterSettingsStorageTests { func defaultSettingsRestoreAndApply() { let (storage, directory) = makeStorage() defer { try? FileManager.default.removeItem(at: directory) } - #expect(storage.loadSettings().restoreBehavior == .restoreAndApply) - #expect(!storage.loadSettings().alwaysShowPanel) + #expect(storage.settings.restoreBehavior == .restoreAndApply) + #expect(!storage.settings.alwaysShowPanel) } @Test( @@ -399,7 +400,7 @@ struct FilterSettingsStorageTests { """ defaults.set(Data(legacy.utf8), forKey: "com.TablePro.filter.settings") - let settings = FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).loadSettings() + let settings = FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).settings #expect(settings.restoreBehavior == behavior) #expect(settings.alwaysShowPanel == alwaysShowPanel) @@ -419,12 +420,94 @@ struct FilterSettingsStorageTests { """ defaults.set(Data(legacy.utf8), forKey: "com.TablePro.filter.settings") - _ = FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).loadSettings() - let second = FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).loadSettings() + _ = FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).settings + let second = FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).settings #expect(second.restoreBehavior == .dontSave) } + private func storage(reading json: String) throws -> (FilterSettingsStorage, URL) { + let defaults = try pool.make().defaults + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("FilterSettingsStorageTests-\(UUID().uuidString)", isDirectory: true) + defaults.set(Data(json.utf8), forKey: "com.TablePro.filter.settings") + return (FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults), directory) + } + + @Test("The column picker keeps table order on a new install and on a file written before the setting") + func columnOrderDefaultsToTableOrder() throws { + let (fresh, freshDirectory) = makeStorage() + defer { try? FileManager.default.removeItem(at: freshDirectory) } + #expect(fresh.settings.columnOrder == .table) + + let (older, olderDirectory) = try storage(reading: """ + {"defaultColumn":"primaryKey","defaultOperator":"contains","restoreBehavior":"dontSave","alwaysShowPanel":true} + """) + defer { try? FileManager.default.removeItem(at: olderDirectory) } + #expect(older.settings == FilterSettings( + defaultColumn: .primaryKey, defaultOperator: .contains, restoreBehavior: .dontSave, alwaysShowPanel: true + )) + } + + @Test("An order this build does not know keeps every other filter setting") + func unknownColumnOrderKeepsOtherSettings() throws { + let (storage, directory) = try storage(reading: """ + {"defaultColumn":"primaryKey","defaultOperator":"contains","columnOrder":"byType"} + """) + defer { try? FileManager.default.removeItem(at: directory) } + #expect(storage.settings.defaultColumn == .primaryKey) + #expect(storage.settings.defaultOperator == .contains) + #expect(storage.settings.columnOrder == .table) + } + + @Test("A saved column order survives a fresh storage instance and still writes the legacy panel state") + func columnOrderRoundTrips() throws { + let defaults = try pool.make().defaults + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("FilterSettingsStorageTests-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + + FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults) + .saveSettings(FilterSettings(columnOrder: .alphabetical)) + + #expect(FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).settings.columnOrder == .alphabetical) + let data = try #require(defaults.data(forKey: "com.TablePro.filter.settings")) + let stored = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + #expect(stored["panelState"] as? String == "restoreLast") + } + + @Test("Saving publishes the change once and skips a value that did not change") + func savePublishesChanges() { + let (storage, directory) = makeStorage() + defer { try? FileManager.default.removeItem(at: directory) } + var published = 0 + let subscription = storage.objectWillChange.sink { published += 1 } + defer { subscription.cancel() } + + storage.saveSettings(FilterSettings(columnOrder: .alphabetical)) + storage.saveSettings(FilterSettings(columnOrder: .alphabetical)) + + #expect(published == 1) + #expect(storage.settings.columnOrder == .alphabetical) + } + + @Test("Resetting the settings brings back every default, for this session and the next") + func resetSettingsRestoresDefaults() throws { + let defaults = try pool.make().defaults + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("FilterSettingsStorageTests-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + let storage = FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults) + storage.saveSettings(FilterSettings( + defaultColumn: .primaryKey, restoreBehavior: .dontSave, alwaysShowPanel: true, columnOrder: .alphabetical + )) + + storage.resetSettings() + + #expect(storage.settings == FilterSettings()) + #expect(FilterSettingsStorage(filterStateDirectory: directory, defaults: defaults).settings == FilterSettings()) + } + @Test("A draft saved with nothing applied round-trips as a draft") func draftRoundTripsUnapplied() { let (storage, directory) = makeStorage() diff --git a/apple/TableProTests/Models/TabFilterStateEditingTests.swift b/apple/TableProTests/Models/TabFilterStateEditingTests.swift index 4a09e174bd..f48b9f3b9c 100644 --- a/apple/TableProTests/Models/TabFilterStateEditingTests.swift +++ b/apple/TableProTests/Models/TabFilterStateEditingTests.swift @@ -422,6 +422,23 @@ struct TabFilterStateEditingTests { #expect(state.filters.map(\.columnName) == ["town"]) } + @Test("Columns that trade names move in one pass, and a column that is gone takes its rows") + func remapColumnsSwapsNamesTogether() { + let rows = [ + TableFilter(columnName: "Column 2", value: "a"), + TableFilter(columnName: "Column 3", value: "b"), + TableFilter(columnName: "Column 1", value: "c"), + TableFilter.rawCondition("1 = 1"), + ] + var state = state(rows).applyingCheckedRows() + let moves = ["Column 2": "Column 3", "Column 3": "Column 2"] + + state.remapColumns { moves[$0] ?? ($0 == "Column 1" ? nil : $0) } + + #expect(state.filters.map(\.columnName) == ["Column 3", "Column 2", TableFilter.rawSQLColumn]) + #expect(state.applied?.filters.map(\.columnName) == ["Column 3", "Column 2", TableFilter.rawSQLColumn]) + } + @Test("A cross-column search ignores case, like the find that offers it") func crossColumnSearchIgnoresCase() { let filters = TabFilterState.crossColumnSearchFilters(term: "ana", columns: ["name", "email"]) diff --git a/apple/TableProTests/Views/Filter/FilterRowLayoutTests.swift b/apple/TableProTests/Views/Filter/FilterRowLayoutTests.swift index 9818fc25b6..c058fa3f5e 100644 --- a/apple/TableProTests/Views/Filter/FilterRowLayoutTests.swift +++ b/apple/TableProTests/Views/Filter/FilterRowLayoutTests.swift @@ -20,7 +20,7 @@ struct FilterRowLayoutTests { private func row(_ filter: TableFilter, focusedId: Binding = .constant(nil)) -> FilterRowView { FilterRowView( filter: .constant(filter), - columns: Self.columns, + columnMenu: FilterColumnMenu.build(columns: Self.columns, fieldPaths: [], order: .table), completions: [], caseMatching: .inMemory, enumValuesByColumn: Self.enumValues, @@ -197,10 +197,9 @@ struct FilterRowLayoutTests { let starts = try [scoped, badged, Self.textEquals].map { filter in let view = FilterRowView( filter: .constant(filter), - columns: Self.columns, + columnMenu: FilterColumnMenu.build(columns: Self.columns, fieldPaths: paths, order: .table), completions: [], caseMatching: .inMemory, - columnMenu: FilterColumnMenu.build(columns: Self.columns, fieldPaths: paths), fieldPaths: paths, reservesElementScope: true, onAdd: {}, diff --git a/apple/TableProTests/Views/Filter/FilterRowViewTests.swift b/apple/TableProTests/Views/Filter/FilterRowViewTests.swift index dc44921eaa..dffd447a90 100644 --- a/apple/TableProTests/Views/Filter/FilterRowViewTests.swift +++ b/apple/TableProTests/Views/Filter/FilterRowViewTests.swift @@ -38,7 +38,7 @@ private final class FilterRowHost { hosting.rootView = AnyView( FilterRowView( filter: binding, - columns: ["id", "name", "email"], + columnMenu: FilterColumnMenu.build(columns: ["id", "name", "email"], fieldPaths: [], order: .table), completions: [], onAdd: {}, onDuplicate: {}, From 4ec76db1ea3203d8b78bdf253be1c85338b7c082 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 25 Nov 2026 11:01:36 +0700 Subject: [PATCH 2/2] docs(changelog): add fragments for #4479 --- apple/changelog.d/4479.added.md | 1 + apple/changelog.d/4479.fixed.1.md | 1 + apple/changelog.d/4479.fixed.2.md | 1 + apple/changelog.d/4479.fixed.md | 1 + 4 files changed, 4 insertions(+) create mode 100644 apple/changelog.d/4479.added.md create mode 100644 apple/changelog.d/4479.fixed.1.md create mode 100644 apple/changelog.d/4479.fixed.2.md create mode 100644 apple/changelog.d/4479.fixed.md diff --git a/apple/changelog.d/4479.added.md b/apple/changelog.d/4479.added.md new file mode 100644 index 0000000000..3f64e9afe4 --- /dev/null +++ b/apple/changelog.d/4479.added.md @@ -0,0 +1 @@ +The filter column picker can list columns alphabetically, from Settings > Data > Filters or the filter bar's ⋯ menu. diff --git a/apple/changelog.d/4479.fixed.1.md b/apple/changelog.d/4479.fixed.1.md new file mode 100644 index 0000000000..a66b83175a --- /dev/null +++ b/apple/changelog.d/4479.fixed.1.md @@ -0,0 +1 @@ +Inserting or deleting a column in a data file moved its filters, hidden columns and Display As onto another column. diff --git a/apple/changelog.d/4479.fixed.2.md b/apple/changelog.d/4479.fixed.2.md new file mode 100644 index 0000000000..96468a9af3 --- /dev/null +++ b/apple/changelog.d/4479.fixed.2.md @@ -0,0 +1 @@ +Undoing an edit in a data file reset the hidden columns chosen after it. diff --git a/apple/changelog.d/4479.fixed.md b/apple/changelog.d/4479.fixed.md new file mode 100644 index 0000000000..f51d2cecca --- /dev/null +++ b/apple/changelog.d/4479.fixed.md @@ -0,0 +1 @@ +Reset All Settings left the Filters settings unchanged.