diff --git a/apple/TablePro/Models/Query/TableRows.swift b/apple/TablePro/Models/Query/TableRows.swift index 45cbd23053..f1fb269893 100644 --- a/apple/TablePro/Models/Query/TableRows.swift +++ b/apple/TablePro/Models/Query/TableRows.swift @@ -604,3 +604,11 @@ struct TableRows: Sendable { return index } } + +extension TableRows { + // A SET cell holds several of its values at once, so only an ENUM is filtered by picking one. + var filterPickerValues: [String: [String]] { + let setColumns = Set(zip(columns, columnTypes).compactMap { name, type in type.isSetType ? name : nil }) + return columnEnumValues.filter { !setColumns.contains($0.key) } + } +} diff --git a/apple/TablePro/Views/Filter/FilterControlMetrics.swift b/apple/TablePro/Views/Filter/FilterControlMetrics.swift new file mode 100644 index 0000000000..a36e18c1ac --- /dev/null +++ b/apple/TablePro/Views/Filter/FilterControlMetrics.swift @@ -0,0 +1,90 @@ +// +// FilterControlMetrics.swift +// TablePro +// + +import AppKit +import SwiftUI + +// Every row of a rule editor reserves the same width for its pop-ups, measured from AppKit's own +// pop-up button: SwiftUI draws a small one within a point of it on macOS 26 and later, and is one before. +@MainActor +enum FilterControlMetrics { + private struct PopUpKey: Hashable { + let titles: [String] + let pullsDown: Bool + } + + private static var popUpWidths: [PopUpKey: CGFloat] = [:] + private static var operatorWidths: [Bool: CGFloat] = [:] + + static func popUpWidth(titles: [String], pullsDown: Bool = false) -> CGFloat { + let key = PopUpKey(titles: titles, pullsDown: pullsDown) + if let width = popUpWidths[key] { return width } + let button = NSPopUpButton(frame: .zero, pullsDown: pullsDown) + button.controlSize = .small + button.font = .systemFont(ofSize: NSFont.systemFontSize(for: .small)) + button.addItems(withTitles: titles) + let width = ceil(button.intrinsicContentSize.width) + 1 + popUpWidths[key] = width + return width + } + + static func operatorWidth(reservesCaseIndicator: Bool) -> CGFloat { + if let width = operatorWidths[reservesCaseIndicator] { return width } + let widest = FilterOperator.allCases + .map { popUpWidth(titles: [$0.displayName], pullsDown: true) } + .max() ?? 0 + let width = widest + (reservesCaseIndicator ? caseIndicatorWidth : 0) + operatorWidths[reservesCaseIndicator] = width + return width + } + + static func textWidth(_ text: String) -> CGFloat { + let font = NSFont.preferredFont(forTextStyle: .subheadline) + return ceil((text as NSString).size(withAttributes: [.font: font]).width) + } + + static let caseIndicatorSpacing: CGFloat = 3 + + // SwiftUI draws a small pop-up no narrower than 29.5pt on macOS 27. + static let popUpMinimumWidth: CGFloat = 32 + + static func operatorMinimumWidth(reservesCaseIndicator: Bool) -> CGFloat { + popUpMinimumWidth + (reservesCaseIndicator ? caseIndicatorWidth : 0) + } + + private static var caseIndicatorWidth: CGFloat { + let configuration = NSImage.SymbolConfiguration( + pointSize: NSFont.systemFontSize(for: .small), + weight: .regular, + scale: .small + ) + let image = NSImage(systemSymbolName: "textformat", accessibilityDescription: nil)? + .withSymbolConfiguration(configuration) + return caseIndicatorSpacing + ceil(image?.size.width ?? 12) + } +} + +extension View { + // Lets a pop-up fill the width its row reserves; before macOS 26 a menu pop-up already fills it. + @ViewBuilder + func fillsReservedWidth() -> some View { + if #available(macOS 26.0, *) { + buttonSizing(.flexible) + } else { + self + } + } +} + +extension VerticalAlignment { + private enum FilterRowLine: AlignmentID { + static func defaultValue(in context: ViewDimensions) -> CGFloat { + context[VerticalAlignment.center] + } + } + + // The centre of a row's first line, so a wrapped condition keeps the row's controls beside its first line. + static let filterRowLine = VerticalAlignment(FilterRowLine.self) +} diff --git a/apple/TablePro/Views/Filter/FilterPanelView.swift b/apple/TablePro/Views/Filter/FilterPanelView.swift index ddb50e4bda..9ea24f230d 100644 --- a/apple/TablePro/Views/Filter/FilterPanelView.swift +++ b/apple/TablePro/Views/Filter/FilterPanelView.swift @@ -50,8 +50,13 @@ struct FilterPanelView: View { } private var filterHeader: some View { - HStack(spacing: 8) { + HStack(spacing: FilterRowView.spacing) { if !state.filters.isEmpty { + // Holds the rows' drag handle column, so this checkbox sits over the rows' checkboxes. + Color.clear + .frame(width: FilterRowDragHandle.gutterWidth, height: 1) + .accessibilityHidden(true) + TristateCheckbox( state: TristateCheckbox.State(allEnabled: state.allEnabledState), action: toggleAllFiltersEnabled @@ -84,7 +89,6 @@ struct FilterPanelView: View { actions.focusGrid() } .buttonStyle(.bordered) - .controlSize(.small) .disabled(!state.hasAppliedFilters) .help(String(localized: "Clear applied filters without removing filter rows")) @@ -92,12 +96,12 @@ struct FilterPanelView: View { applyAllValidFilters() } .buttonStyle(.borderedProminent) - .controlSize(.small) .keyboardShortcut(.return, modifiers: .command) .disabled(enabledValidFilterCount == 0 && !state.hasAppliedFilters) .help(String(localized: "Apply active filters (Cmd+Return)")) } - .padding(.horizontal, 12) + .controlSize(.small) + .padding(.horizontal, FilterRowView.horizontalInset) .padding(.vertical, 8) .paneBarBackground(Color(nsColor: .controlBackgroundColor)) .contentShape(Rectangle()) @@ -200,7 +204,7 @@ struct FilterPanelView: View { } private var filterRows: some View { - VStack(spacing: 0) { + VStack(alignment: .leading, spacing: 0) { ForEach(state.filters) { filter in FilterRowView( filter: filterBinding(for: filter), @@ -213,6 +217,7 @@ struct FilterPanelView: View { fieldPaths: configuration.fieldPaths, offersRawFilter: configuration.offersRawFilter, rawFilterLabel: configuration.rawFilterLabel, + reservesElementScope: reservesElementScope, onAdd: { focusedFilterId = addDefaultFilter(columns: configuration.columns) }, @@ -252,6 +257,12 @@ struct FilterPanelView: View { } } + private var reservesElementScope: Bool { + state.filters.contains { filter in + !filter.isRawSQL && FilterColumnMenu.elementScope(for: filter.columnName, in: configuration.fieldPaths) != nil + } + } + private var enabledValidFilterCount: Int { state.filters.count { $0.isEnabled && $0.isValid } } diff --git a/apple/TablePro/Views/Filter/FilterRowLayout.swift b/apple/TablePro/Views/Filter/FilterRowLayout.swift new file mode 100644 index 0000000000..4ac0adf5dc --- /dev/null +++ b/apple/TablePro/Views/Filter/FilterRowLayout.swift @@ -0,0 +1,146 @@ +// +// FilterRowLayout.swift +// TablePro +// + +import SwiftUI + +// An HStack hands out width greedily, so its rows overflow a narrow pane and drift apart at middle +// widths; every row here gives way the same amount, keeping its cells on one grid at any width. +struct FilterRowLayout: Layout { + // A slot's minimum is declared rather than read from its control, so every row gives way alike. + enum Role: Equatable { + case fixed + case reserved(CGFloat, minimum: CGFloat) + // Keeps the slot's width in the grid, and the fill cell after it starts at the slot instead. + case spannedByFill(CGFloat, minimum: CGFloat) + case fill + } + + var spacing: CGFloat + // The same for every row, so a row with a smaller value cell still gives way like the others. + var fillMinimum: CGFloat = 0 + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let widths = widths(for: proposal.width, subviews: subviews) + let line = lineExtent(frames: frames(widths: widths, subviews: subviews), subviews: subviews) + return CGSize(width: widths.reduce(0, +) + gaps(subviews), height: line.above + line.below) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let frames = frames(widths: widths(for: bounds.width, subviews: subviews), subviews: subviews) + let line = lineExtent(frames: frames, subviews: subviews) + let lineY = bounds.minY + (bounds.height - line.above - line.below) / 2 + line.above + for (subview, frame) in zip(subviews, frames) { + let proposal = ProposedViewSize(width: frame.width, height: nil) + let guide = subview.dimensions(in: proposal)[.filterRowLine] + subview.place(at: CGPoint(x: bounds.minX + frame.x, y: lineY - guide), anchor: .topLeading, proposal: proposal) + } + } + + private func gaps(_ subviews: Subviews) -> CGFloat { + spacing * CGFloat(max(subviews.count - 1, 0)) + } + + private func frames(widths: [CGFloat], subviews: Subviews) -> [(x: CGFloat, width: CGFloat)] { + var frames: [(x: CGFloat, width: CGFloat)] = [] + var x: CGFloat = 0 + for (index, width) in widths.enumerated() { + if subviews[index][FilterRowRoleKey.self] == .fill, + let previous = frames.last, + case .spannedByFill = subviews[index - 1][FilterRowRoleKey.self] { + frames.append((previous.x, x + width - previous.x)) + } else { + frames.append((x, width)) + } + x += width + spacing + } + return frames + } + + private func lineExtent(frames: [(x: CGFloat, width: CGFloat)], subviews: Subviews) -> (above: CGFloat, below: CGFloat) { + var above: CGFloat = 0 + var below: CGFloat = 0 + for (subview, frame) in zip(subviews, frames) { + let dimensions = subview.dimensions(in: ProposedViewSize(width: frame.width, height: nil)) + above = max(above, dimensions[.filterRowLine]) + below = max(below, dimensions.height - dimensions[.filterRowLine]) + } + return (above, below) + } + + private func widths(for proposedWidth: CGFloat?, subviews: Subviews) -> [CGFloat] { + var widths = [CGFloat](repeating: 0, count: subviews.count) + var reserved: [(index: Int, target: CGFloat, minimum: CGFloat)] = [] + var fills: [(index: Int, minimum: CGFloat)] = [] + for (index, subview) in subviews.enumerated() { + switch subview[FilterRowRoleKey.self] { + case .fixed: + widths[index] = subview.sizeThatFits(.unspecified).width + case .reserved(let target, let minimum), .spannedByFill(let target, let minimum): + reserved.append((index, target, minimum)) + case .fill: + fills.append((index, max(minimumWidth(of: subview), fillMinimum))) + } + } + + guard let proposedWidth else { + for cell in reserved { widths[cell.index] = cell.target } + for cell in fills { + widths[cell.index] = max(subviews[cell.index].sizeThatFits(.unspecified).width, cell.minimum) + } + return widths + } + + var available = proposedWidth - gaps(subviews) - widths.reduce(0, +) + let forReserved = max(available - fills.reduce(0) { $0 + $1.minimum }, 0) + for (index, width) in Self.share(forReserved, among: reserved) { + widths[index] = width + available -= width + } + let fillShare = fills.isEmpty ? 0 : available / CGFloat(fills.count) + for cell in fills { widths[cell.index] = max(fillShare, cell.minimum) } + return widths + } + + // Scales the slots down together; one that reaches its minimum stays there and the rest share what is left. + private static func share( + _ budget: CGFloat, + among slots: [(index: Int, target: CGFloat, minimum: CGFloat)] + ) -> [(index: Int, width: CGFloat)] { + var open = slots + var budget = budget + var shares: [(index: Int, width: CGFloat)] = [] + while !open.isEmpty { + let targets = open.reduce(0) { $0 + $1.target } + guard targets > budget, targets > 0 else { + return shares + open.map { ($0.index, $0.target) } + } + let scale = budget / targets + let clamped = open.filter { $0.target * scale < $0.minimum } + guard !clamped.isEmpty else { + return shares + open.map { ($0.index, $0.target * scale) } + } + for slot in clamped { + shares.append((slot.index, slot.minimum)) + budget = max(budget - slot.minimum, 0) + } + open.removeAll { slot in clamped.contains { $0.index == slot.index } } + } + return shares + } + + private func minimumWidth(of subview: LayoutSubview) -> CGFloat { + subview.sizeThatFits(ProposedViewSize(width: 0, height: nil)).width + } +} + +private struct FilterRowRoleKey: LayoutValueKey { + static let defaultValue: FilterRowLayout.Role = .fixed +} + +extension View { + func filterRowRole(_ role: FilterRowLayout.Role) -> some View { + layoutValue(key: FilterRowRoleKey.self, value: role) + } +} diff --git a/apple/TablePro/Views/Filter/FilterRowView.swift b/apple/TablePro/Views/Filter/FilterRowView.swift index d1762fed7a..3a5d1d0526 100644 --- a/apple/TablePro/Views/Filter/FilterRowView.swift +++ b/apple/TablePro/Views/Filter/FilterRowView.swift @@ -17,6 +17,7 @@ struct FilterRowView: View { var fieldPaths: [PluginFieldPath] = [] var offersRawFilter = true var rawFilterLabel = String(localized: "Raw SQL") + var reservesElementScope = false let onAdd: () -> Void let onDuplicate: () -> Void let onRemove: () -> Void @@ -34,10 +35,18 @@ struct FilterRowView: View { @State private var isDropTargeted = false @State private var showNestedPathPicker = false - private let rowButtonGlyphSize: CGFloat = 14 + // NSRuleEditor spaces its row controls 6pt apart. + static let spacing: CGFloat = 6 + static let horizontalInset: CGFloat = 12 - /// How much of a column name the row will spend width on before truncating it. + private let rowButtonGlyphSize: CGFloat = 14 private static let columnPickerMaximumWidth: CGFloat = 160 + static let valueFieldMinimumWidth: CGFloat = 28 + + // Room for a Between pair, the widest value cell, before the column and operator give way. + static func valueCellMinimumWidth(spacing: CGFloat) -> CGFloat { + 2 * valueFieldMinimumWidth + 2 * spacing + FilterControlMetrics.textWidth(String(localized: "and")) + } private var pickerEligibleOperators: Set { [.equal, .notEqual] @@ -58,7 +67,7 @@ struct FilterRowView: View { } var body: some View { - HStack(spacing: 4) { + FilterRowLayout(spacing: Self.spacing, fillMinimum: Self.valueCellMinimumWidth(spacing: Self.spacing)) { dragHandle enabledToggle @@ -66,22 +75,37 @@ struct FilterRowView: View { Group { columnPicker - if arrayPrefix != nil { - elementScopePicker + if columnMenu.hasMorePaths { + nestedFieldPathButton } - if !filter.isRawSQL { + elementScopeSlot + + if filter.isRawSQL { + // The condition covers the operator's slot, so the column before it stays on the grid. + Color.clear + .frame(width: 1, height: 1) + .accessibilityHidden(true) + .filterRowRole(.spannedByFill(operatorCellWidth, minimum: operatorCellMinimumWidth)) + } else { operatorPicker } - valueFields + HStack(alignment: .filterRowLine, spacing: Self.spacing) { + valueFields + } + .frame(maxWidth: .infinity, alignment: .leading) + .filterRowRole(.fill) } .opacity(filter.isEnabled ? 1 : 0.5) rowButtons } - .padding(.vertical, 4) - .padding(.horizontal, 8) + .controlSize(.small) + .frame(minHeight: FilterValueTextField.singleLineHeight(for: .small)) + .padding(.vertical, 5) + .padding(.horizontal, Self.horizontalInset) + .frame(maxWidth: .infinity, alignment: .leading) .background(dropHighlight) .dropDestination(for: FilterRowTransfer.self) { items, _ in guard let dragged = items.first else { return false } @@ -155,54 +179,52 @@ struct FilterRowView: View { .help(String(localized: "Include this filter when applying")) } - /// A restored or preset filter can name a path the sample has not returned yet, and a Picker - /// whose selection matches no tag renders blank and can reset the binding. Carrying the value - /// as its own item keeps it visible and selected until the paths land. + // A restored filter can name a path not loaded yet, and a Picker matching no tag renders blank. private var driftedColumn: String? { guard !filter.isRawSQL, !filter.columnName.isEmpty else { return nil } return columnMenu.contains(filter.columnName) ? nil : filter.columnName } private var columnPicker: some View { - HStack(spacing: 4) { - Picker(String(localized: "Filter column"), selection: columnSelection) { - if offersRawFilter || filter.isRawSQL { - Text(rawFilterLabel).tag(String?.none) - Divider() - } - ForEach(columns, id: \.self) { column in - Text(column).tag(String?.some(column)) - } - ForEach(columnMenu.groups) { group in - Divider() - ForEach(group.paths, id: \.path) { path in - Text(path.path).tag(String?.some(path.path)) - } - } - if let driftedColumn { - Divider() - Text(driftedColumn).tag(String?.some(driftedColumn)) + columnMenuPicker + .fillsReservedWidth() + .filterRowRole(.reserved(columnCellWidth, minimum: FilterControlMetrics.popUpMinimumWidth)) + } + + // 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 + return min(FilterControlMetrics.popUpWidth(titles: titles), Self.columnPickerMaximumWidth) + } + + private var columnMenuPicker: some View { + Picker(String(localized: "Filter column"), selection: columnSelection) { + if offersRawFilter || filter.isRawSQL { + Text(rawFilterLabel).tag(String?.none) + Divider() + } + ForEach(columns, id: \.self) { column in + Text(column).tag(String?.some(column)) + } + ForEach(columnMenu.groups) { group in + Divider() + ForEach(group.paths, id: \.path) { path in + Text(path.path).tag(String?.some(path.path)) } } - .pickerStyle(.menu) - .controlSize(.small) - /// Bounded rather than `.fixedSize()`. A pull-down takes the width of its widest menu - /// item, and the items here are the table's column names, so one long name made the - /// whole filter row wider than the pane: measured, a 62-character column name alone - /// needs 412pt, and the row reached 681pt inside a 420pt host and was clipped at both - /// edges. Capped, the name truncates and the row stays the width of its host. - .frame(maxWidth: Self.columnPickerMaximumWidth) - .labelsHidden() - .accessibilityValue(filter.isRawSQL ? rawFilterLabel : filter.columnName) - .help(String(localized: "Select filter column")) - - if columnMenu.hasMorePaths { - nestedFieldPathButton + if let driftedColumn { + Divider() + Text(driftedColumn).tag(String?.some(driftedColumn)) } } + .pickerStyle(.menu) + .labelsHidden() + .accessibilityValue(filter.isRawSQL ? rawFilterLabel : filter.columnName) + .help(String(localized: "Select filter column")) } - /// Nil is the raw condition, so a table column that shares the raw row's name stays a column. + // Nil is the raw condition, so a table column that shares the raw row's name stays a column. private var columnSelection: Binding { Binding( get: { filter.isRawSQL ? nil : filter.columnName }, @@ -220,7 +242,6 @@ struct FilterRowView: View { .frame(width: rowButtonGlyphSize, height: rowButtonGlyphSize) } .buttonStyle(.bordered) - .controlSize(.small) .accessibilityLabel(String(localized: "Nested field path")) .accessibilityIdentifier("filter-nested-field-path") .help(String(localized: "Filter on a nested field path")) @@ -234,20 +255,38 @@ struct FilterRowView: View { } } - /// MongoDB reads two conditions on the same array as "any element satisfies each", so - /// binding them to one element is a different query the user has to ask for. - private var elementScopePicker: some View { - Picker("", selection: elementScopeBinding) { + // Another row's scope picker would push this row's operator right, so the slot stays reserved. + @ViewBuilder + private var elementScopeSlot: some View { + if let arrayPrefix { + elementScopePicker(prefix: arrayPrefix) + .fillsReservedWidth() + .accessibilityIdentifier("filter-element-scope") + .help(elementScopeHelp) + .filterRowRole(.reserved(Self.elementScopeWidth, minimum: FilterControlMetrics.popUpMinimumWidth)) + } else if reservesElementScope { + Color.clear + .frame(width: 1, height: 1) + .accessibilityHidden(true) + .filterRowRole(.reserved(Self.elementScopeWidth, minimum: FilterControlMetrics.popUpMinimumWidth)) + } + } + + private static var elementScopeWidth: CGFloat { + FilterControlMetrics.popUpWidth(titles: [ + String(localized: "any element"), + String(localized: "same element"), + ]) + } + + // MongoDB reads two conditions on one array as "any element satisfies each"; binding them to one element is another query. + private func elementScopePicker(prefix: String) -> some View { + Picker(String(localized: "Array element scope"), selection: elementScopeBinding) { Text("any element").tag("") - Text("same element").tag(arrayPrefix ?? "") + Text("same element").tag(prefix) } .pickerStyle(.menu) - .controlSize(.small) - .fixedSize() .labelsHidden() - .accessibilityLabel(String(localized: "Array element scope")) - .accessibilityIdentifier("filter-element-scope") - .help(elementScopeHelp) } private var arrayPrefix: String? { @@ -270,6 +309,20 @@ struct FilterRowView: View { } private var operatorPicker: some View { + operatorMenu + .fillsReservedWidth() + .filterRowRole(.reserved(operatorCellWidth, minimum: operatorCellMinimumWidth)) + } + + private var operatorCellWidth: CGFloat { + FilterControlMetrics.operatorWidth(reservesCaseIndicator: caseMatching.isAdjustable) + } + + private var operatorCellMinimumWidth: CGFloat { + FilterControlMetrics.operatorMinimumWidth(reservesCaseIndicator: caseMatching.isAdjustable) + } + + private var operatorMenu: some View { Menu { Picker(String(localized: "Filter operator"), selection: operatorSelection) { ForEach(FilterOperator.allCases) { op in @@ -288,12 +341,17 @@ struct FilterRowView: View { } } } label: { - operatorMenuTitle - .accessibilityLabel(String(localized: "Filter operator")) + HStack(spacing: FilterControlMetrics.caseIndicatorSpacing) { + Text(filter.filterOperator.displayName) + if casePresentation.showsIndicator { + Image(systemName: "textformat") + .imageScale(.small) + .foregroundStyle(.secondary) + } + } + .accessibilityLabel(String(localized: "Filter operator")) } .menuStyle(.button) - .controlSize(.small) - .fixedSize() .accessibilityValue(operatorAccessibilityValue) .help(caseSensitivityHelp) } @@ -305,18 +363,6 @@ struct FilterRowView: View { ) } - @ViewBuilder - private var operatorMenuTitle: some View { - HStack(spacing: 3) { - OperatorMenuLabel(op: filter.filterOperator) - if casePresentation.showsIndicator { - Image(systemName: "textformat") - .imageScale(.small) - .foregroundStyle(.secondary) - } - } - } - private var casePresentation: FilterCaseSensitivityPresentation { FilterCaseSensitivityPresentation( filterOperator: filter.filterOperator, @@ -355,11 +401,14 @@ struct FilterRowView: View { onSubmit: onSubmit, onCancel: onCancel ) + .alignmentGuide(.filterRowLine) { _ in FilterValueTextField.singleLineHeight(for: .small) / 2 } .accessibilityLabel(String(localized: "WHERE clause")) } else if filter.filterOperator.requiresValue { if let allowedValues = allowedValuesForCurrentColumn, pickerEligibleOperators.contains(filter.filterOperator) { - enumValuePicker(allowedValues: allowedValues) + IdealWidthCap { + enumValuePicker(allowedValues: allowedValues) + } } else { FilterValueTextField( text: $filter.value, @@ -370,7 +419,7 @@ struct FilterRowView: View { onSubmit: onSubmit, onCancel: onCancel ) - .frame(minWidth: 80) + .frame(minWidth: Self.valueFieldMinimumWidth) .accessibilityLabel(String(localized: "Filter value")) } @@ -378,24 +427,30 @@ struct FilterRowView: View { Text("and") .font(.subheadline) .foregroundStyle(.secondary) + .fixedSize() - TextField("Value", text: Binding( - get: { filter.secondValue ?? "" }, - set: { filter.secondValue = $0 } - )) - .textFieldStyle(.roundedBorder) - .controlSize(.small) - .font(.callout) - .autocorrectionDisabled(true) - .frame(minWidth: 80) + FilterValueTextField( + text: secondValueBinding, + focusedId: $focusedFilterId, + identity: FilterValueTextField.secondFieldIdentity(for: filter.id), + placeholder: String(localized: "Value"), + completionSource: .staticValues(completions), + onSubmit: onSubmit, + onCancel: onCancel + ) + .frame(minWidth: Self.valueFieldMinimumWidth) .accessibilityLabel(String(localized: "Second filter value")) - .onSubmit { onSubmit() } } - } else { - Spacer(minLength: 0) } } + private var secondValueBinding: Binding { + Binding( + get: { filter.secondValue ?? "" }, + set: { filter.secondValue = $0 } + ) + } + private var rowButtons: some View { HStack(spacing: 4) { Button(action: onAdd) { @@ -403,7 +458,6 @@ struct FilterRowView: View { .frame(width: rowButtonGlyphSize, height: rowButtonGlyphSize) } .buttonStyle(.bordered) - .controlSize(.small) .accessibilityLabel(String(localized: "Add filter")) .help(String(localized: "Add filter row")) @@ -412,7 +466,6 @@ struct FilterRowView: View { .frame(width: rowButtonGlyphSize, height: rowButtonGlyphSize) } .buttonStyle(.bordered) - .controlSize(.small) .accessibilityLabel(String(localized: "Remove filter")) .help(String(localized: "Remove filter row")) } @@ -470,6 +523,11 @@ struct FilterRowView: View { private func enumValuePicker(allowedValues: [String]) -> some View { let isDrift = !filter.value.isEmpty && !allowedValues.contains(filter.value) Picker(String(localized: "Filter value"), selection: $filter.value) { + // An empty value matches no tag, and a pop-up with no selection draws blank. + if filter.value.isEmpty { + Text("Value").tag("") + Divider() + } ForEach(allowedValues, id: \.self) { value in Text(value).tag(value) } @@ -479,8 +537,6 @@ struct FilterRowView: View { } } .pickerStyle(.menu) - .controlSize(.small) - .frame(minWidth: 100) .labelsHidden() } diff --git a/apple/TablePro/Views/Filter/FilterValueTextField.swift b/apple/TablePro/Views/Filter/FilterValueTextField.swift index 87da03e305..d92e107261 100644 --- a/apple/TablePro/Views/Filter/FilterValueTextField.swift +++ b/apple/TablePro/Views/Filter/FilterValueTextField.swift @@ -70,15 +70,7 @@ struct FilterValueTextField: NSViewRepresentable { case passThrough } - /// The popup owns a key only once the user has picked a row in it. - /// - /// An auto-triggered list that preselects its first row owns `Return` from the moment it - /// appears, and in a filter field `Return` already means "apply this filter": the user had to - /// press `Escape` first to get their own key back. AppKit spells the alternative `-1`, "no - /// initial selection", on the `indexOfSelectedItem` its own completion delegate hands a text - /// field, and Finder's search field is the shipping shape: the suggestion menu opens with - /// nothing highlighted, one `Return` commits what was typed, and `Down` is what reaches the - /// first row. + // Return already means "apply this filter", so the list owns a key only once a row is picked in it. nonisolated static func suggestionCommandOutcome( for commandSelector: Selector, hasSelection: Bool, @@ -95,9 +87,7 @@ struct FilterValueTextField: NSViewRepresentable { } } - /// Arrowing into an unselected list enters it from the end the arrow points away from, so - /// `Down` reaches the first row and `Up` the last. Within the list both clamp, matching the - /// query editor's panel. + // Matches the query editor's panel: Down enters at the first row, Up at the last, both clamp. nonisolated static func selection( movedBy delta: Int, from current: Int?, @@ -120,21 +110,74 @@ struct FilterValueTextField: NSViewRepresentable { return .closeBar } + // A row lines its pop-ups up against one line of this field, whatever control holds its value. + static func singleLineHeight(for controlSize: NSControl.ControlSize) -> CGFloat { + if let height = singleLineHeights[controlSize] { return height } + let field = NSTextField() + field.bezelStyle = .roundedBezel + applyFont(to: field, controlSize: controlSize) + let height = field.intrinsicContentSize.height + singleLineHeights[controlSize] = height + return height + } + + private static var singleLineHeights: [NSControl.ControlSize: CGFloat] = [:] + + // A rounded field wraps only on some macOS versions (measured: one line before 26); one that cannot + // wrap ends a long condition in an ellipsis rather than cutting it off mid-clause. + private static let roundedFieldWraps: Bool = { + let field = NSTextField() + field.bezelStyle = .roundedBezel + applyFont(to: field, controlSize: .small) + field.usesSingleLineMode = false + field.cell?.wraps = true + field.cell?.isScrollable = false + field.stringValue = String(repeating: "condition ", count: 20) + let bounds = NSRect(x: 0, y: 0, width: 120, height: CGFloat.greatestFiniteMagnitude) + let wrapped = field.cell?.cellSize(forBounds: bounds).height ?? 0 + return wrapped > singleLineHeight(for: .small) * 1.5 + }() + + // Two fields of one row each need an identity, or focusing one makes the other claim focus. + nonisolated static func secondFieldIdentity(for identity: UUID) -> UUID { + var bytes = identity.uuid + bytes.0 ^= 0xFF + return UUID(uuid: bytes) + } + + // SwiftUI sets a hosted control's size from the environment, so the font follows it rather than + // keeping a fixed size that mismatched the pop-ups beside it. + private static func applyFont(to field: NSTextField, controlSize: NSControl.ControlSize) { + field.controlSize = controlSize + field.font = .systemFont(ofSize: NSFont.systemFontSize(for: controlSize)) + } + + private static func controlSize(of environment: EnvironmentValues) -> NSControl.ControlSize { + switch environment.controlSize { + case .mini: .mini + case .small: .small + case .large: .large + default: .regular + } + } + func makeNSView(context: Context) -> NSTextField { let textField = SubstitutionDisabledTextField() textField.bezelStyle = .roundedBezel - textField.controlSize = .small - textField.font = .systemFont(ofSize: 12) + Self.applyFont(to: textField, controlSize: Self.controlSize(of: context.environment)) textField.placeholderString = placeholder textField.delegate = context.coordinator textField.stringValue = text - if allowsMultiLine { + if allowsMultiLine, Self.roundedFieldWraps { textField.usesSingleLineMode = false textField.cell?.wraps = true textField.cell?.isScrollable = false textField.lineBreakMode = .byWordWrapping textField.maximumNumberOfLines = 0 + } else if allowsMultiLine { + textField.usesSingleLineMode = false + textField.lineBreakMode = .byTruncatingTail } else { textField.lineBreakMode = .byTruncatingTail } @@ -160,6 +203,10 @@ struct FilterValueTextField: NSViewRepresentable { context.coordinator.onCancel = onCancel context.coordinator.textField = textField + let controlSize = Self.controlSize(of: context.environment) + if textField.font?.pointSize != NSFont.systemFontSize(for: controlSize) { + Self.applyFont(to: textField, controlSize: controlSize) + } textField.placeholderString = placeholder let fieldEditor = textField.currentEditor() as? NSTextView @@ -171,6 +218,17 @@ struct FilterValueTextField: NSViewRepresentable { context.coordinator.focusIfRequested() } + // A wrapping field's intrinsic height is one line, so a long condition wrapped out of sight. + func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSTextField, context: Context) -> CGSize? { + guard allowsMultiLine, Self.roundedFieldWraps, + let width = proposal.width, width.isFinite, width > 0, + let cell = nsView.cell?.copy() as? NSCell else { return nil } + cell.stringValue = text + let bounds = NSRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude) + let height = max(cell.cellSize(forBounds: bounds).height, nsView.intrinsicContentSize.height) + return CGSize(width: width, height: ceil(height)) + } + func makeCoordinator() -> Coordinator { Coordinator( text: $text, @@ -443,10 +501,7 @@ struct FilterValueTextField: NSViewRepresentable { suggestionPopover = popover } - /// The completion list never takes focus, so nothing in it is ever the accessibility - /// focus. Without an announcement on the field there is no signal that it opened at all, - /// and the announcement names the arrow because nothing in the list is selected until one - /// is pressed. + // The list never takes focus, so without this announcement VoiceOver gives no sign it opened. private func announceSuggestions(count: Int, on textField: NSTextField) { guard count > 0 else { return } NSAccessibility.post( @@ -555,8 +610,7 @@ struct FilterValueTextField: NSViewRepresentable { private struct SuggestionItem: Equatable { let label: String let insertText: String - /// Caret position relative to the insertion start, so a function completion parks the - /// caret between its parentheses here exactly as it does in the query editor. + // Relative to the insertion start, so a function completion parks the caret between its parentheses. let cursorOffset: Int init(label: String, insertText: String, cursorOffset: Int? = nil) { diff --git a/apple/TablePro/Views/Filter/IdealWidthCap.swift b/apple/TablePro/Views/Filter/IdealWidthCap.swift new file mode 100644 index 0000000000..d6f837bb4a --- /dev/null +++ b/apple/TablePro/Views/Filter/IdealWidthCap.swift @@ -0,0 +1,23 @@ +// +// IdealWidthCap.swift +// TablePro +// + +import SwiftUI + +// Before macOS 26 a menu Picker stretches to whatever it is offered; this keeps its ideal width and shrinks only when squeezed. +struct IdealWidthCap: Layout { + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + guard let child = subviews.first else { return .zero } + let width = min(child.sizeThatFits(.unspecified).width, proposal.width ?? .infinity) + return child.sizeThatFits(ProposedViewSize(width: width, height: proposal.height)) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + subviews.first?.place( + at: CGPoint(x: bounds.minX, y: bounds.midY), + anchor: .leading, + proposal: ProposedViewSize(width: bounds.width, height: bounds.height) + ) + } +} diff --git a/apple/TablePro/Views/Highlight/HighlightRuleRow.swift b/apple/TablePro/Views/Highlight/HighlightRuleRow.swift index 00f4382119..864c435fb6 100644 --- a/apple/TablePro/Views/Highlight/HighlightRuleRow.swift +++ b/apple/TablePro/Views/Highlight/HighlightRuleRow.swift @@ -16,12 +16,7 @@ struct HighlightRuleRow: View { let onRemove: () -> Void let onCancel: () -> Void - /// Bounded rather than `.fixedSize()`. A pull-down takes the width of its widest menu item, - /// and the items here are the table's column names, so one long name pushed the BETWEEN - /// second value field past the popover's edge: measured, a 29-character name puts the row at - /// 582pt and a 62-character one at 791pt, against the 523pt a row actually gets inside this - /// popover's 540pt list. Capped, both measure 511pt. The filter bar's own 160 does not fit - /// here, because that row lives in a wider host. + // Narrower than the filter bar's 160: a row gets 523pt inside this popover's list. private static let columnPickerMaximumWidth: CGFloat = 140 private var isColumnMissing: Bool { @@ -60,6 +55,7 @@ struct HighlightRuleRow: View { .padding(.leading, 22) .opacity(rule.isEnabled ? 1 : 0.5) } + .controlSize(.small) .padding(.vertical, 4) .accessibilityElement(children: .contain) .accessibilityLabel(HighlightRuleDescription.condition(of: rule)) @@ -74,11 +70,27 @@ struct HighlightRuleRow: View { } private var conditionEditor: some View { - HStack(spacing: 6) { + FilterRowLayout(spacing: 6, fillMinimum: FilterRowView.valueCellMinimumWidth(spacing: 6)) { columnPicker + .fillsReservedWidth() + .filterRowRole(.reserved(columnCellWidth, minimum: FilterControlMetrics.popUpMinimumWidth)) operatorMenu - valueFields + .fillsReservedWidth() + .filterRowRole(.reserved( + FilterControlMetrics.operatorWidth(reservesCaseIndicator: true), + minimum: FilterControlMetrics.operatorMinimumWidth(reservesCaseIndicator: true) + )) + HStack(spacing: 6) { + valueFields + } + .frame(maxWidth: .infinity, alignment: .leading) + .filterRowRole(.fill) } + .frame(minHeight: FilterValueTextField.singleLineHeight(for: .small)) + } + + private var columnCellWidth: CGFloat { + min(FilterControlMetrics.popUpWidth(titles: columnOptions.map(\.label)), Self.columnPickerMaximumWidth) } private var columnSelection: Binding { @@ -103,8 +115,6 @@ struct HighlightRuleRow: View { } } .pickerStyle(.menu) - .controlSize(.small) - .frame(maxWidth: Self.columnPickerMaximumWidth) .labelsHidden() .accessibilityValue(rule.columnName) .accessibilityIdentifier("highlight-rule-column") @@ -137,8 +147,8 @@ struct HighlightRuleRow: View { Toggle(String(localized: "Match Case"), isOn: $rule.isCaseSensitive) } } label: { - HStack(spacing: 3) { - Text(Self.operatorLabel(rule.filterOperator)) + HStack(spacing: FilterControlMetrics.caseIndicatorSpacing) { + Text(rule.filterOperator.displayName) if rule.filterOperator.supportsCaseSensitivity, rule.isCaseSensitive != rule.filterOperator.defaultIsCaseSensitive { Image(systemName: "textformat") @@ -149,8 +159,6 @@ struct HighlightRuleRow: View { .accessibilityLabel(String(localized: "Rule operator")) } .menuStyle(.button) - .controlSize(.small) - .fixedSize() .accessibilityValue(rule.filterOperator.displayName) .accessibilityIdentifier("highlight-rule-operator") } @@ -165,25 +173,27 @@ struct HighlightRuleRow: View { placeholder: String(localized: "Value"), onCancel: onCancel ) - .frame(minWidth: 90) + .frame(minWidth: FilterRowView.valueFieldMinimumWidth) .accessibilityLabel(String(localized: "Rule value")) if rule.filterOperator.requiresSecondValue { Text("and") .font(.subheadline) .foregroundStyle(.secondary) - TextField("Value", text: Binding( - get: { rule.secondValue ?? "" }, - set: { rule.secondValue = $0 } - )) - .textFieldStyle(.roundedBorder) - .controlSize(.small) - .autocorrectionDisabled(true) - .frame(minWidth: 70) + .fixedSize() + FilterValueTextField( + text: Binding( + get: { rule.secondValue ?? "" }, + set: { rule.secondValue = $0 } + ), + focusedId: $focusedRuleID, + identity: FilterValueTextField.secondFieldIdentity(for: rule.id), + placeholder: String(localized: "Value"), + onCancel: onCancel + ) + .frame(minWidth: FilterRowView.valueFieldMinimumWidth) .accessibilityLabel(String(localized: "Second rule value")) } - } else { - Spacer(minLength: 0) } } @@ -199,7 +209,6 @@ struct HighlightRuleRow: View { } } .pickerStyle(.menu) - .controlSize(.small) .fixedSize() .labelsHidden() .accessibilityValue(rule.color.displayName) @@ -212,7 +221,6 @@ struct HighlightRuleRow: View { } } .pickerStyle(.segmented) - .controlSize(.small) .fixedSize() .labelsHidden() .accessibilityLabel(String(localized: "Apply To")) @@ -223,7 +231,6 @@ struct HighlightRuleRow: View { Button(String(localized: "Remove Rule"), systemImage: "minus", action: onRemove) .labelStyle(.iconOnly) .buttonStyle(.bordered) - .controlSize(.small) .help(String(localized: "Remove this rule")) } diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index 10f531ed79..c2387f5f25 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -836,7 +836,7 @@ struct MainEditorContentView: View { columns: rows.columns, primaryKeyColumn: changeManager.primaryKeyColumn, databaseType: connection.type, - enumValuesByColumn: rows.columnEnumValues + enumValuesByColumn: rows.filterPickerValues ) } Divider() diff --git a/apple/TableProTests/Models/Query/TableRowsTests.swift b/apple/TableProTests/Models/Query/TableRowsTests.swift index 0d86475188..9fd8d204e4 100644 --- a/apple/TableProTests/Models/Query/TableRowsTests.swift +++ b/apple/TableProTests/Models/Query/TableRowsTests.swift @@ -772,3 +772,19 @@ struct TableRowsColumnTypeNamesTests { #expect(table.columnTypeNames == ["id": "INT"]) } } + +struct TableRowsFilterPickerTests { + @Test("Only an ENUM column offers its values as a filter pop-up; a SET value can hold several") + func setColumnsAreLeftToTheTextField() { + let table = TableRows( + columns: ["status", "perms", "name"], + columnTypes: [ + .enumType(rawType: "ENUM", values: ["open", "closed"]), + .set(rawType: "SET", values: ["read", "write"]), + .text(rawType: nil), + ], + columnEnumValues: ["status": ["open", "closed"], "perms": ["read", "write"]] + ) + #expect(table.filterPickerValues == ["status": ["open", "closed"]]) + } +} diff --git a/apple/TableProTests/Views/Filter/FilterRowLayoutTests.swift b/apple/TableProTests/Views/Filter/FilterRowLayoutTests.swift new file mode 100644 index 0000000000..2227ddc922 --- /dev/null +++ b/apple/TableProTests/Views/Filter/FilterRowLayoutTests.swift @@ -0,0 +1,332 @@ +// +// FilterRowLayoutTests.swift +// TableProTests +// +// Filter rows line up as a grid: every row spans its pane, its value starts at the same x whatever +// the operator, and its height does not depend on the control holding the value. +// + +import AppKit +import SwiftUI +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct FilterRowLayoutTests { + private static let columns = ["id", "title", "status", "a_rather_long_column_name_for_the_cap"] + private static let enumValues = ["status": ["open", "pending", "closed"]] + + private func row(_ filter: TableFilter, focusedId: Binding = .constant(nil)) -> FilterRowView { + FilterRowView( + filter: .constant(filter), + columns: Self.columns, + completions: [], + caseMatching: .inMemory, + enumValuesByColumn: Self.enumValues, + onAdd: {}, + onDuplicate: {}, + onRemove: {}, + onApply: {}, + onSubmit: {}, + onCancel: {}, + isReorderEnabled: true, + canMoveUp: false, + canMoveDown: false, + onMoveUp: {}, + onMoveDown: {}, + onDropFilter: { _ in }, + focusedFilterId: focusedId + ) + } + + private static let textEquals = TableFilter(columnName: "title", filterOperator: .equal, value: "a") + private static let textContains = TableFilter(columnName: "title", filterOperator: .notContains, value: "a") + private static let enumEquals = TableFilter(columnName: "status", filterOperator: .equal, value: "open") + private static let between = TableFilter(columnName: "id", filterOperator: .between, value: "1", secondValue: "3") + private static let isNull = TableFilter(columnName: "title", filterOperator: .isNull) + + @Test("A row whose value is a pop-up spans its pane instead of being centred", arguments: [700, 500] as [CGFloat]) + func popUpRowSpansThePane(width: CGFloat) { + for filter in [Self.enumEquals, Self.isNull, Self.textEquals] { + let frame = measureFrame(of: row(filter), width: width) + #expect(frame.minX == 0, "\(filter.filterOperator) row placed at \(frame.minX)") + #expect(frame.width == width, "\(filter.filterOperator) row is \(frame.width)pt in a \(width)pt pane") + } + } + + @Test("Every row is the same height whatever control holds its value") + func rowsShareOneHeight() { + let heights = [Self.textEquals, Self.enumEquals, Self.isNull, Self.between] + .map { measureFrame(of: row($0), width: 700).height } + #expect(Set(heights).count == 1, "row heights \(heights)") + } + + @Test("The value starts at the same x whatever the operator", arguments: [700, 520] as [CGFloat]) + func valuesShareOneColumn(width: CGFloat) throws { + let starts = try [Self.textEquals, Self.textContains, Self.between].map { filter in + try #require(valueFields(in: row(filter), width: width).first).minX + } + #expect(Set(starts).count == 1, "value fields start at \(starts)") + } + + @Test("A raw condition starts where the other rows' operator does") + func rawConditionStartsAtTheOperatorColumn() throws { + let value = try #require(valueFields(in: row(Self.textEquals), width: 700).first).minX + let raw = try #require(valueFields(in: row(TableFilter.rawCondition("id = 1")), width: 700).first).minX + let operatorStart = value - FilterControlMetrics.operatorWidth(reservesCaseIndicator: true) - FilterRowView.spacing + #expect(raw == operatorStart, "a raw condition starts at \(raw), the operator column at \(operatorStart)") + } + + @Test("A row never grows past the pane at the pane's narrowest") + func rowFitsTheNarrowestPane() { + let width = MainSplitViewController.defaultDetailMinThickness + let longColumn = TableFilter(columnName: Self.columns[3], filterOperator: .between, value: "1", secondValue: "3") + let rowHeight = measureFrame(of: row(Self.textEquals), width: 700).height + for filter in [Self.textContains, Self.between, Self.enumEquals, longColumn] { + let frame = measureFrame(of: row(filter), width: width) + #expect(frame.width <= width, "\(filter.columnName) \(filter.filterOperator) row is \(frame.width)pt in \(width)pt") + #expect(frame.minX >= 0) + #expect(frame.height == rowHeight, "\(filter.filterOperator) row is \(frame.height)pt tall at \(width)pt") + } + } + + @Test("Both Between fields are the same field, sharing the value column's width") + func betweenFieldsMatch() { + let fields = valueFields(in: row(Self.between), width: 700) + #expect(fields.count == 2) + guard fields.count == 2 else { return } + #expect(abs(fields[0].width - fields[1].width) <= 1, "Between fields \(fields[0].width) and \(fields[1].width)") + #expect(fields[0].height == fields[1].height) + } + + @Test("Focusing one Between field never hands focus to the other") + func betweenFieldsKeepTheirOwnFocus() throws { + let focus = FocusBox(Self.between.id) + let binding = Binding(get: { focus.id }, set: { focus.id = $0 }) + let host = hosted(row(Self.between, focusedId: binding), width: 700) + defer { host.window?.orderOut(nil) } + let rerender = { + host.rootView = AnyView(self.row(Self.between, focusedId: binding).frame(width: 700)) + host.layoutSubtreeIfNeeded() + } + rerender() + let fields = editableFields(in: host).sorted { $0.frame(in: host).minX < $1.frame(in: host).minX } + try #require(fields.count == 2) + #expect(firstResponderField(in: host) === fields[0]) + + rerender() + #expect(firstResponderField(in: host) === fields[0], "a second render moved focus off the first field") + } + + @Test("A row asked to focus its second Between field focuses that one") + func secondBetweenFieldHasItsOwnIdentity() throws { + let focus = FocusBox(FilterValueTextField.secondFieldIdentity(for: Self.between.id)) + let binding = Binding(get: { focus.id }, set: { focus.id = $0 }) + let host = hosted(row(Self.between, focusedId: binding), width: 700) + defer { host.window?.orderOut(nil) } + host.rootView = AnyView(row(Self.between, focusedId: binding).frame(width: 700)) + host.layoutSubtreeIfNeeded() + let fields = editableFields(in: host).sorted { $0.frame(in: host).minX < $1.frame(in: host).minX } + try #require(fields.count == 2) + #expect(firstResponderField(in: host) === fields[1]) + } + + @Test("Highlight rules line their values up the same way") + func highlightValuesShareOneColumn() throws { + let options = HighlightColumnOption.options(for: Self.columns) + let starts = try [ + HighlightRule(columnName: "title", filterOperator: .equal, value: "a"), + HighlightRule(columnName: "id", filterOperator: .between, value: "1", secondValue: "3"), + HighlightRule(columnName: "title", filterOperator: .notContains, value: "a"), + ].map { rule in + let view = HighlightRuleRow( + rule: .constant(rule), + columnOptions: options, + focusedRuleID: .constant(nil), + canMoveUp: false, + canMoveDown: false, + onMoveUp: {}, + onMoveDown: {}, + onRemove: {}, + onCancel: {} + ) + return try #require(valueFields(in: view, width: 523).first).minX + } + #expect(Set(starts).count == 1, "rule values start at \(starts)") + } + + @Test("A long raw condition wraps onto more lines instead of hiding past the first") + func rawConditionGrowsWithItsText() throws { + let condition = "status = 'active' AND created_at >= '2024-01-01' AND (owner_id IN (1, 2, 3) OR team = 'core')" + let raw = TableFilter.rawCondition(condition) + let field = try #require(valueFields(in: row(raw), width: 420).first) + #expect(field.height > FilterValueTextField.singleLineHeight(for: .small) + 1, "raw field is \(field.height)pt tall") + } + + @Test("The operator slot fits every operator's pull-down as SwiftUI draws it") + func operatorSlotFitsEveryOperator() { + let slot = FilterControlMetrics.operatorWidth(reservesCaseIndicator: false) + for op in FilterOperator.allCases { + let menu = Menu { Button("x") {} } label: { Text(op.displayName) } + .menuStyle(.button) + .controlSize(.small) + .fixedSize() + let drawn = NSHostingView(rootView: menu).fittingSize.width + #expect(drawn <= slot, "\(op.displayName) draws \(drawn)pt in a \(slot)pt slot") + } + #expect(FilterControlMetrics.operatorWidth(reservesCaseIndicator: true) > slot) + } + + @Test("A drifted column lines its row up with the others instead of widening its pop-up") + func driftedColumnKeepsTheGrid() throws { + let drifted = TableFilter(columnName: "a_column_this_table_no_longer_has_at_all", filterOperator: .equal, value: "a") + let starts = try [Self.textEquals, drifted].map { filter in + try #require(valueFields(in: row(filter), width: 700).first).minX + } + #expect(starts[0] == starts[1], "value fields start at \(starts)") + } + + @Test("Rows on an array path, a badged operator and a plain row line up and fit", arguments: [800, 400] as [CGFloat]) + func elementScopeSlotKeepsTheGrid(width: CGFloat) throws { + // MongoDB reports array members two levels down, which also brings the nested path button. + let paths = [PluginFieldPath(path: "orders.items.sku", typeName: "string", depth: 2, arrayPrefixes: ["orders.items"])] + let scoped = TableFilter(columnName: "orders.items.sku", filterOperator: .equal, value: "a") + let badged = TableFilter(columnName: "title", filterOperator: .contains, value: "a", isCaseSensitive: true) + let starts = try [scoped, badged, Self.textEquals].map { filter in + let view = FilterRowView( + filter: .constant(filter), + columns: Self.columns, + completions: [], + caseMatching: .inMemory, + columnMenu: FilterColumnMenu.build(columns: Self.columns, fieldPaths: paths), + fieldPaths: paths, + reservesElementScope: true, + onAdd: {}, + onDuplicate: {}, + onRemove: {}, + onApply: {}, + onSubmit: {}, + onCancel: {}, + isReorderEnabled: true, + canMoveUp: false, + canMoveDown: false, + onMoveUp: {}, + onMoveDown: {}, + onDropFilter: { _ in }, + focusedFilterId: .constant(nil) + ) + #expect(measureFrame(of: view, width: width).width <= width) + return try #require(valueFields(in: view, width: width).first).minX + } + #expect(Set(starts).count == 1, "value fields start at \(starts)") + } + + @Test("A pop-up keeps its ideal width and shrinks only when squeezed") + func idealWidthCapKeepsTheIdealWidth() { + func width(_ text: String, proposal: CGFloat) -> CGFloat { + let box = FrameBox() + let host = NSHostingView(rootView: IdealWidthCap { Text(text).lineLimit(1) } + .overlay(FrameProbe(box: box)) + .frame(width: proposal, alignment: .leading)) + host.frame = NSRect(x: 0, y: 0, width: 600, height: 40) + host.layoutSubtreeIfNeeded() + return box.frame?.width ?? .nan + } + let ideal = NSHostingView(rootView: Text("pending")).fittingSize.width + #expect(abs(width("pending", proposal: 400) - ideal) <= 1) + #expect(width("pending", proposal: 20) <= 20) + } + + // MARK: - Hosting + + private func hosted(_ content: some View, width: CGFloat) -> NSHostingView { + let host = NSHostingView(rootView: AnyView(content.frame(width: width))) + host.sizingOptions = [] + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: width, height: 120), + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = host + host.layoutSubtreeIfNeeded() + return host + } + + private func measureFrame(of content: some View, width: CGFloat) -> CGRect { + let box = FrameBox() + let host = hosted(VStack(spacing: 0) { content.overlay(FrameProbe(box: box)) }, width: width) + defer { host.window?.orderOut(nil) } + return box.frame ?? CGRect(x: CGFloat.nan, y: CGFloat.nan, width: CGFloat.nan, height: CGFloat.nan) + } + + private func valueFields(in content: some View, width: CGFloat) -> [CGRect] { + let host = hosted(content, width: width) + defer { host.window?.orderOut(nil) } + return editableFields(in: host) + .map { $0.frame(in: host) } + .sorted { $0.minX < $1.minX } + } + + private func editableFields(in view: NSView) -> [NSTextField] { + let own = (view as? NSTextField).map { $0.isEditable ? [$0] : [] } ?? [] + return own + view.subviews.flatMap(editableFields(in:)) + } + + private func firstResponderField(in host: NSView) -> NSTextField? { + guard let editor = host.window?.firstResponder as? NSTextView else { return nil } + return editor.delegate as? NSTextField + } +} + +@MainActor +private final class FrameBox { + var frame: CGRect? +} + +@MainActor +private final class FocusBox { + var id: UUID? + + init(_ id: UUID?) { + self.id = id + } +} + +private struct FrameProbe: NSViewRepresentable { + let box: FrameBox + + func makeNSView(context: Context) -> NSView { ProbeView(box: box) } + + func updateNSView(_ nsView: NSView, context: Context) {} + + private final class ProbeView: NSView { + private let box: FrameBox + + init(box: FrameBox) { + self.box = box + super.init(frame: .zero) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("FrameProbe does not support NSCoder init") + } + + override func layout() { + super.layout() + var root: NSView = self + while let parent = root.superview { root = parent } + let measured = convert(bounds, to: root) + MainActor.assumeIsolated { box.frame = measured } + } + } +} + +private extension NSView { + func frame(in ancestor: NSView) -> CGRect { + convert(bounds, to: ancestor) + } +} diff --git a/apple/changelog.d/4164.fixed.md b/apple/changelog.d/4164.fixed.md new file mode 100644 index 0000000000..54c56888bf --- /dev/null +++ b/apple/changelog.d/4164.fixed.md @@ -0,0 +1 @@ +Filter bar rows no longer center or drift out of line when a value is a pop-up, Between or Raw SQL.