Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions apple/TablePro/Core/Coordinators/FilterCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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,
Expand All @@ -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]

Expand Down
6 changes: 6 additions & 0 deletions apple/TablePro/Core/DataFiles/DataFileColumnNames.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
25 changes: 4 additions & 21 deletions apple/TablePro/Core/DataFiles/DataFileController+Editing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -180,37 +180,20 @@ extension DataFileController {

func deleteColumns(_ ids: Set<TabularColumnID>) {
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) {
Expand Down
4 changes: 2 additions & 2 deletions apple/TablePro/Core/DataFiles/DataFileController+Query.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
45 changes: 41 additions & 4 deletions apple/TablePro/Core/DataFiles/DataFileController+Undo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -30,6 +31,7 @@ extension DataFileController {
kindOverrides: kindOverrides,
displayKeys: displayKeys,
columnLayout: columnLayout,
displayFormats: displayFormatsByColumn,
filterState: includesFilters ? filterState : nil,
queryRevision: queryRevision
)
Expand All @@ -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)
Expand All @@ -53,6 +58,9 @@ extension DataFileController {
registerUndo(restoring: previous, actionName: actionName)
onEdited?()
refreshPage()
if rerunsQuery {
runQuery()
}
}

private func registerUndo(restoring state: DataFileEditState, actionName: String) {
Expand All @@ -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
}
Expand All @@ -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<TabularColumnID>) {
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
}
}
}
35 changes: 35 additions & 0 deletions apple/TablePro/Core/DataFiles/DataFileController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
59 changes: 45 additions & 14 deletions apple/TablePro/Core/Services/Query/FilterColumnMenu.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
}
1 change: 1 addition & 0 deletions apple/TablePro/Core/Storage/AppSettingsManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading