diff --git a/CHANGELOG.md b/CHANGELOG.md index c2e0e2fa..21973145 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] ### Added +- Per-column filter settings (#373) on `KumikoColumn`, which is a Core object, so MAUI and Uno XAML and code get them alike. `AllowedTextFilterOperators`, `AllowedNumericFilterOperators` and `AllowedDateFilterOperators` list the operators the filter popup offers, in order (null offers all), and `AllowedFilterOperatorsString` is the XAML form (`"Equals,StartsWith"`, parsed for the column's type; an unknown name throws at assignment). `DefaultTextFilterOperator`, `DefaultNumericFilterOperator` and `DefaultDateFilterOperator` set the operator a new condition starts with, and `CreateDefaultFilterCondition()` returns a condition using them. `FilterCompareOptions` replaces the source's `StringCompareOptions` for that column's conditions and value list (for example `None` to match case-sensitively), in foreground and background rebuilds and in `GetUniqueColumnValues`, without affecting other columns. The restriction is for the UI only: conditions set from code with any operator still apply, and the popup keeps listing the operator of a condition the column already has. (#373) - Scroll bars: the grid draws a vertical bar at the right edge of the scrolling rows and a horizontal bar across the scrolling columns. `VerticalScrollBarVisibility` and `HorizontalScrollBarVisibility` (`KumikoScrollBarVisibility`: `Auto`, the default, an overlay shown while the grid scrolls or a mouse rests over it that then fades; `Always`; `Never`) on `KumikoStyle` and on both grids, plus `ScrollBarThickness`, `ScrollBarExpandedThickness`, `ScrollBarMinThumbLength`, `ScrollBarThumbColor` and `ScrollBarTrackColor`. With a mouse or a pen a bar expands on hover, its thumb drags and its track pages (repeating while held); a finger pans through it. New `HitRegion` values `VerticalScrollBarThumb`, `VerticalScrollBarTrack`, `HorizontalScrollBarThumb` and `HorizontalScrollBarTrack`. A mouse or pen press within 10 px of the rows' right or bottom edge now lands on the bar instead of the cell under it (#316). - A built-in column header menu, drawn by the grid so it looks the same on every platform and opens at the pointer (#319). Turn it on with `IsColumnMenuEnabled` (MAUI and Uno, off by default): a right click or a long press on a column header, the optional header menu button (`ShowColumnMenuButton`) or the Menu key / Shift+F10 opens it with sort ascending, sort descending, clear sort, filter, group by this column or ungroup, hide and auto-fit width, as far as the grid and the column allow. `ColumnMenuOpening` (`KumikoColumnMenuOpeningEventArgs`) lets an app remove, reorder or add items or cancel the menu, `ShowColumnMenu(column)` opens it in code, and its texts are new `KumikoStrings` members. `ContextMenuRequested` is raised first and the menu opens only when no handler set the new `KumikoContextRequestedEventArgs.Handled`, so an app that shows its own header menu sets it before turning the built-in one on. The menu is a reusable `DrawnMenu` of `DrawnMenuItem`s (separators, icons, check marks, disabled items, keyboard navigation with typeahead, scrolling, screen-reader announcements). Also new: `KumikoKey.ContextMenu`, `HitRegion.HeaderMenuButton`, `KumikoIcon.ColumnMenu` and `ShowColumnMenuButton` on `KumikoRenderer`, `KumikoInputController` and `KumikoHitTester`. - Incremental "load more" loading (#318): the grid asks for the next batch as the user nears the end of the loaded rows, draws a loading row after the last row while it waits, and an error row with Retry when a batch fails (never retried automatically). One batch runs at a time; replacing or resetting the items, `Detach` and `Dispose` cancel it. Sources: `IKumikoIncrementalSource` (detected on the items or set through `IncrementalSource`), the ready-made `KumikoIncrementalCollection`, an MVVM `LoadMoreCommand` with two-way `IsLoadingMore` and `LoadMoreErrorText`, and on Uno an `ISupportIncrementalLoading` items source. Both hosts add `LoadMoreMode` (Automatic, Manual, None), `LoadMoreThreshold`, `LoadMoreBatchSize`, the read-only `LoadMoreState`, the `LoadMoreRequested` and `LoadMoreCompleted` events, `LoadMoreAsync` and `ResetLoadMore`; Core adds `KumikoSource.IncrementalLoading` (`KumikoIncrementalLoader`), `HitRegion.LoadMoreRow`, the `KumikoStyle.LoadMore*` members, the `KumikoStrings.LoadMore*` and `AnnounceLoadMore*` strings and `KumikoAnnouncements.LoadMoreStarted`/`LoadMoreCompleted`. A multi-item collection `Add` now raises one `ViewChanged` `Insert` (no sort, grouping or summary) instead of a rebuild. diff --git a/README.md b/README.md index 3d73ae8c..f9d21970 100644 --- a/README.md +++ b/README.md @@ -953,6 +953,15 @@ Each column header with `AllowFiltering` (the default) shows a filter icon. Tapp OK applies both pages, combined with And: the checked values and the conditions. A page you did not change keeps what the filter had, so OK on Values keeps the conditions and OK on Conditions keeps the checked values, and the tab of the page not shown has a dot while it holds criteria. A value that does not parse keeps the popup open with the `EnterNumber` or `EnterDate` message. The popup opens on Conditions when the column's filter has a condition. Set `KumikoColumn.AllowConditionFilter` to false to show only the values for a column; Boolean, Image and Template columns have no Conditions page. +Shape the conditions per column with `KumikoColumn` settings. `AllowedFilterOperatorsString="Equals,StartsWith"` (or `AllowedTextFilterOperators`, `AllowedNumericFilterOperators`, `AllowedDateFilterOperators` from code) limits the operators the popup lists, in that order; `DefaultTextFilterOperator`, `DefaultNumericFilterOperator` and `DefaultDateFilterOperator` choose the operator a new condition starts with (`CreateDefaultFilterCondition()` builds one); and `FilterCompareOptions="None"` makes that column's conditions and value list case-sensitive while other columns keep the grid's `StringCompareOptions`. The operator lists restrict the popup only: a condition set from code with another operator still applies. + +```xml + +``` + The value list scrolls by drag, mouse wheel, its scrollbar, and Up/Down, Page Up/Page Down, Space, Enter and Escape. Tab and Shift+Tab move between the switch (Left/Right change the page), the search box or the operators and values, And/Or (Space switches) and the buttons; Enter applies, and Escape closes an open operator list or calendar before the popup, as does a tap outside it. The value boxes take text like the search box (input methods, the soft keyboard, the clipboard), and a screen reader hears the page, the operator and where Tab moved (with the grid's `AnnounceChanges` on). Filters on several columns combine. The filter icon is drawn in `FilterActiveIconColor` while the column has a filter. From code, filter by predicate or per column: diff --git a/src/KumikoUI.Core/Components/DrawnFilterPopup.Conditions.cs b/src/KumikoUI.Core/Components/DrawnFilterPopup.Conditions.cs index baf3e474..72a37fd4 100644 --- a/src/KumikoUI.Core/Components/DrawnFilterPopup.Conditions.cs +++ b/src/KumikoUI.Core/Components/DrawnFilterPopup.Conditions.cs @@ -146,8 +146,15 @@ private void InitConditions() if (_kind == FilterConditionKind.None) return; + // The column's allowed operators, plus those of conditions it already has (set from code, #373). + var existing = _column.ActiveFilter; + _operatorChoices = FilterConditionTypes.Operators(_kind, _column, new[] + { + existing?.Condition1 is { } c1 ? FilterConditionTypes.OperatorOf(_kind, c1) : null, + existing?.Condition2 is { } c2 ? FilterConditionTypes.OperatorOf(_kind, c2) : null, + }); var items = new List(); - foreach (var op in FilterConditionTypes.Operators(_kind)) + foreach (var op in _operatorChoices) items.Add(new DrawnComboBoxItem(Strings.FilterOperatorLabel(op), op)); _operators[0].SetItems(items); _operators[1].SetItems(items); @@ -160,6 +167,9 @@ private void InitConditions() } } + /// The operators the drop-downs list: the column's allowed ones and those of conditions it already has. + private IReadOnlyList _operatorChoices = Array.Empty(); + /// Shows the column's conditions: the first in row 1, the second in row 2, each with the default operator when absent. private void LoadConditions() { @@ -173,8 +183,10 @@ private void LoadConditions() private void LoadRow(int row, FilterCondition? condition) { - var operators = FilterConditionTypes.Operators(_kind); - object? op = condition != null ? FilterConditionTypes.OperatorOf(_kind, condition) : null; + var operators = _operatorChoices; + object? op = condition != null + ? FilterConditionTypes.OperatorOf(_kind, condition) + : FilterConditionTypes.DefaultOperator(_kind, _column); int index = 0; for (int i = 0; i < operators.Count; i++) if (Equals(operators[i], op)) index = i; diff --git a/src/KumikoUI.Core/Components/FilterConditionTypes.cs b/src/KumikoUI.Core/Components/FilterConditionTypes.cs index ddc90408..d343c429 100644 --- a/src/KumikoUI.Core/Components/FilterConditionTypes.cs +++ b/src/KumikoUI.Core/Components/FilterConditionTypes.cs @@ -53,6 +53,81 @@ internal static class FilterConditionTypes _ => FilterConditionKind.None, }; + /// + /// The operator family of a column type for the per-column operator settings: like , + /// and the date family also covers DateTime and Time columns, whose conditions evaluate the date operators. + /// + /// The column type. + internal static FilterConditionKind OperatorKindOf(KumikoColumnType type) => type switch + { + KumikoColumnType.DateTime or KumikoColumnType.Time => FilterConditionKind.Date, + _ => KindOf(type), + }; + + /// + /// The operators the drop-down of lists for : the column's allowed + /// operators in its order, or all of them when it sets none. Operators in (those of + /// conditions the column already has) are added at the end when missing, so editing never changes them silently. + /// + /// The condition editor. + /// The column. + /// Boxed operators that must stay listed, or null. + internal static IReadOnlyList Operators(FilterConditionKind kind, KumikoColumn column, IEnumerable? keep = null) + { + IReadOnlyList all = Operators(kind); + List? allowed = kind switch + { + FilterConditionKind.Text => Boxed(column.AllowedTextFilterOperators), + FilterConditionKind.Number => Boxed(column.AllowedNumericFilterOperators), + FilterConditionKind.Date => Boxed(column.AllowedDateFilterOperators), + _ => null, + }; + if (allowed == null) return all; + if (keep != null) + foreach (var op in keep) + if (op != null && !allowed.Contains(op)) allowed.Add(op); + return allowed; + } + + private static List? Boxed(IReadOnlyList? list) where T : struct, Enum + { + if (list == null || list.Count == 0) return null; + var result = new List(list.Count); + foreach (var op in list) + if (!result.Contains(op)) result.Add(op); + return result; + } + + /// + /// The operator a new condition of starts with for : its default + /// operator, or the stock one (Contains, Equals, Equals) when it sets none, or the first allowed operator when the + /// column does not allow the stock one. Boxed; null for a kind without conditions. + /// + /// The condition editor. + /// The column. + internal static object? DefaultOperator(FilterConditionKind kind, KumikoColumn column) + { + object? preferred = kind switch + { + FilterConditionKind.Text => column.DefaultTextFilterOperator ?? TextFilterOperator.Contains, + FilterConditionKind.Number => column.DefaultNumericFilterOperator ?? NumericFilterOperator.Equals, + FilterConditionKind.Date => column.DefaultDateFilterOperator ?? DateFilterOperator.Equals, + _ => null, + }; + if (kind == FilterConditionKind.None) return null; + // An explicit default is honored as given (it also applies to conditions created in code); only the stock + // one gives way to the first allowed operator. + bool explicitDefault = kind switch + { + FilterConditionKind.Text => column.DefaultTextFilterOperator.HasValue, + FilterConditionKind.Number => column.DefaultNumericFilterOperator.HasValue, + _ => column.DefaultDateFilterOperator.HasValue, + }; + if (explicitDefault) return preferred; + var operators = Operators(kind, column); + return operators.Contains(preferred!) ? preferred : operators[0]; + } + /// The condition editor of a column: none when it turns condition filters off. /// The column. internal static FilterConditionKind KindOf(KumikoColumn column) => diff --git a/src/KumikoUI.Core/Models/FilterDescription.cs b/src/KumikoUI.Core/Models/FilterDescription.cs index c8bcf237..0bb702ed 100644 --- a/src/KumikoUI.Core/Models/FilterDescription.cs +++ b/src/KumikoUI.Core/Models/FilterDescription.cs @@ -45,12 +45,15 @@ public FilterDescription(KumikoColumn column) /// /// Evaluate this filter against a cell value and its display text, with the current culture and - /// case-insensitive text rules (). + /// case-insensitive text rules (), or the column's . /// public bool Evaluate(object? cellValue, string displayText) => + EvaluateWith(cellValue, displayText, Column.ResolveFilterComparer(KumikoComparer.Default)); + + private bool EvaluateWith(object? cellValue, string displayText, KumikoComparer comparer) => Evaluate(cellValue, displayText, SelectedValues is { } selected - ? new HashSet(selected, KumikoComparer.Default.TextComparer) - : null, KumikoComparer.Default); + ? new HashSet(selected, comparer.TextComparer) + : null, comparer); /// /// A copy whose conditions are copies too, for a view build on a worker (#254): later changes to this diff --git a/src/KumikoUI.Core/Models/KumikoColumn.FilterOptions.cs b/src/KumikoUI.Core/Models/KumikoColumn.FilterOptions.cs new file mode 100644 index 00000000..8e35eb21 --- /dev/null +++ b/src/KumikoUI.Core/Models/KumikoColumn.FilterOptions.cs @@ -0,0 +1,190 @@ +using System.Globalization; +using KumikoUI.Core.Components; + +namespace KumikoUI.Core.Models; + +// Per-column filter settings (#373): which operators the filter UI offers, the operator a new condition starts with, +// and how this column's filters compare text. +public partial class KumikoColumn +{ + private IReadOnlyList? _allowedTextFilterOperators; + private IReadOnlyList? _allowedNumericFilterOperators; + private IReadOnlyList? _allowedDateFilterOperators; + private TextFilterOperator? _defaultTextFilterOperator; + private NumericFilterOperator? _defaultNumericFilterOperator; + private DateFilterOperator? _defaultDateFilterOperator; + private CompareOptions? _filterCompareOptions; + private string? _allowedFilterOperatorsString; + private KumikoComparer? _filterComparer; + + /// + /// The text operators the filter popup offers for this column, in this order. Null (the default), or an empty list, + /// offers every operator. Only the UI is restricted: a condition set from code with another operator still applies, + /// and the popup keeps showing the operator of a condition the column already has. + /// + public IReadOnlyList? AllowedTextFilterOperators + { + get => _allowedTextFilterOperators; + set => SetField(ref _allowedTextFilterOperators, value); + } + + /// + /// The numeric operators the filter popup offers for this column, in this order. Null (the default), or an empty + /// list, offers every operator. Only the UI is restricted; see . + /// + public IReadOnlyList? AllowedNumericFilterOperators + { + get => _allowedNumericFilterOperators; + set => SetField(ref _allowedNumericFilterOperators, value); + } + + /// + /// The date operators the filter popup offers for this column, in this order. Null (the default), or an empty list, + /// offers every operator. Only the UI is restricted; see . + /// + public IReadOnlyList? AllowedDateFilterOperators + { + get => _allowedDateFilterOperators; + set => SetField(ref _allowedDateFilterOperators, value); + } + + /// + /// The text operator a new condition starts with. Null (the default): , or + /// the first of when that list does not contain it. + /// + public TextFilterOperator? DefaultTextFilterOperator + { + get => _defaultTextFilterOperator; + set => SetField(ref _defaultTextFilterOperator, value); + } + + /// + /// The numeric operator a new condition starts with. Null (the default): , + /// or the first of when that list does not contain it. + /// + public NumericFilterOperator? DefaultNumericFilterOperator + { + get => _defaultNumericFilterOperator; + set => SetField(ref _defaultNumericFilterOperator, value); + } + + /// + /// The date operator a new condition starts with. Null (the default): , or + /// the first of when that list does not contain it. + /// + public DateFilterOperator? DefaultDateFilterOperator + { + get => _defaultDateFilterOperator; + set => SetField(ref _defaultDateFilterOperator, value); + } + + /// + /// How text compares in this column's filters: its conditions (equals, contains, starts with and the like) and its + /// value list. Null (the default): . Other columns are not affected. + /// The culture is always the source's . Set to + /// match case-sensitively in a source that ignores case. + /// + public CompareOptions? FilterCompareOptions + { + get => _filterCompareOptions; + set => SetField(ref _filterCompareOptions, value); + } + + /// + /// The operators the filter popup offers, as a comma-separated list of names for XAML (for example + /// "Equals,StartsWith"). The names are parsed against the operator enum of (text + /// for Text, ComboBox and Picker; numeric for Numeric and ProgressBar; date for Date, DateTime and Time) into + /// , or + /// . Names are case-insensitive. Null or empty clears the list. If + /// changes afterward the names are parsed again for the new type, and names that no longer + /// fit are dropped. + /// + /// A name is not an operator of the column's type. + public string? AllowedFilterOperatorsString + { + get => _allowedFilterOperatorsString; + set + { + var text = string.IsNullOrWhiteSpace(value) ? null : value; + ApplyAllowedFilterOperators(text, strict: true); + _allowedFilterOperatorsString = text; + RaisePropertyChanged(nameof(AllowedFilterOperatorsString)); + } + } + + /// + /// A new condition for this column with its default operators applied: , + /// and (or the fallbacks they + /// describe) and no value. The filter popup starts its operator drop-downs from the same operators. + /// + /// A new condition that the caller owns. + public FilterCondition CreateDefaultFilterCondition() => new() + { + TextOperator = (TextFilterOperator)FilterConditionTypes.DefaultOperator(FilterConditionKind.Text, this)!, + NumericOperator = (NumericFilterOperator)FilterConditionTypes.DefaultOperator(FilterConditionKind.Number, this)!, + DateOperator = (DateFilterOperator)FilterConditionTypes.DefaultOperator(FilterConditionKind.Date, this)!, + }; + + /// + /// The comparer for this column's filters: when is null, + /// otherwise one with the source's culture and the column's options, cached so a rebuild reuses it. + /// + internal KumikoComparer ResolveFilterComparer(KumikoComparer source) + { + if (_filterCompareOptions is not { } options) return source; + var culture = source.Culture; + var cached = _filterComparer; + if (cached != null && cached.Options == options && ReferenceEquals(cached.Culture, culture)) return cached; + return _filterComparer = new KumikoComparer(culture, options); + } + + private void ReparseAllowedFilterOperators() + { + if (_allowedFilterOperatorsString == null) return; + _allowedTextFilterOperators = null; + _allowedNumericFilterOperators = null; + _allowedDateFilterOperators = null; + ApplyAllowedFilterOperators(_allowedFilterOperatorsString, strict: false); + } + + private void ApplyAllowedFilterOperators(string? text, bool strict) + { + switch (FilterConditionTypes.OperatorKindOf(_columnType)) + { + case FilterConditionKind.Text: + AllowedTextFilterOperators = Parse(text, strict); + break; + case FilterConditionKind.Number: + AllowedNumericFilterOperators = Parse(text, strict); + break; + case FilterConditionKind.Date: + AllowedDateFilterOperators = Parse(text, strict); + break; + default: + if (strict && text != null) + throw new ArgumentException($"A {_columnType} column has no filter operators."); + break; + } + } + + private static List? Parse(string? text, bool strict) where TEnum : struct, Enum + { + if (text == null) return null; + var list = new List(); + foreach (var part in text.Split(',')) + { + var name = part.Trim(); + if (name.Length == 0) continue; + if (char.IsLetter(name[0]) && Enum.TryParse(name, ignoreCase: true, out var value) && Enum.IsDefined(value)) + { + if (!list.Contains(value)) list.Add(value); + } + else if (strict) + { + throw new ArgumentException( + $"'{name}' is not a {typeof(TEnum).Name} operator."); + } + } + return list.Count == 0 ? null : list; + } +} diff --git a/src/KumikoUI.Core/Models/KumikoColumn.cs b/src/KumikoUI.Core/Models/KumikoColumn.cs index b0e3531e..b1608607 100644 --- a/src/KumikoUI.Core/Models/KumikoColumn.cs +++ b/src/KumikoUI.Core/Models/KumikoColumn.cs @@ -21,7 +21,7 @@ namespace KumikoUI.Core.Models; /// . The editor settings (Editor* properties and editor factories) /// are read when an editor opens and raise no notification. /// -public class KumikoColumn : INotifyPropertyChanged +public partial class KumikoColumn : INotifyPropertyChanged { /// /// Raised after a configuration property changed; names it. @@ -105,7 +105,10 @@ internal Data.KumikoValuePath ResolvePath(Type itemType) public KumikoColumnType ColumnType { get => _columnType; - set => SetField(ref _columnType, value); + set + { + if (SetField(ref _columnType, value)) ReparseAllowedFilterOperators(); + } } private KumikoColumnType _columnType = KumikoColumnType.Text; diff --git a/src/KumikoUI.Core/Models/KumikoSource.cs b/src/KumikoUI.Core/Models/KumikoSource.cs index 6258aa97..34bf64c9 100644 --- a/src/KumikoUI.Core/Models/KumikoSource.cs +++ b/src/KumikoUI.Core/Models/KumikoSource.cs @@ -1065,7 +1065,8 @@ private void OnColumnPropertyChanged(object? sender, PropertyChangedEventArgs e) } if (sender is KumikoColumn column && e.PropertyName is nameof(KumikoColumn.PropertyName) or nameof(KumikoColumn.ValueAccessor) - or nameof(KumikoColumn.CustomComparer) or nameof(KumikoColumn.ColumnType) && + or nameof(KumikoColumn.CustomComparer) or nameof(KumikoColumn.ColumnType) + or nameof(KumikoColumn.FilterCompareOptions) && (column.SortDirection != KumikoSortDirection.None || column.ActiveFilter != null || _groupDescriptions.Count > 0 || _tableSummaryRows.Count > 0)) { @@ -1692,7 +1693,9 @@ public void ClearAllFilters() public List GetUniqueColumnValues(KumikoColumn column) { // The same text rules as filtering: values that compare equal are one entry. - var values = new HashSet(_comparer.TextComparer); + // The column's own text rules when it sets FilterCompareOptions (#373), so the list and the filter agree. + var comparer = column.ResolveFilterComparer(_comparer); + var values = new HashSet(comparer.TextComparer); var filters = PrepareFilters(column); var search = CaptureSearchFilter(_comparer); for (int i = 0; i < _sourceItems.Count; i++) @@ -1711,7 +1714,7 @@ public List GetUniqueColumnValues(KumikoColumn column) } var sorted = values.ToList(); - sorted.Sort(_comparer.CompareText); + sorted.Sort(comparer.CompareText); return sorted; } @@ -2111,11 +2114,14 @@ private FilterSpec[] PrepareFilters(KumikoColumn? exclude = null, KumikoComparer foreach (var col in _columns) { if (col == exclude || col.ActiveFilter is not { IsActive: true } filter) continue; + // A column with its own FilterCompareOptions filters under its own text rules (cached on the column). + var colComparer = col.ResolveFilterComparer(comparer); ISet? values = filter.SelectedValues is { } selected - ? new HashSet(selected, comparer.TextComparer) + ? new HashSet(selected, colComparer.TextComparer) : null; (prepared ??= new()).Add(new FilterSpec(col, new ItemReader(col), - forWorker ? filter.CloneForBuild() : filter, values, col.DisplayFormat)); + forWorker ? filter.CloneForBuild() : filter, values, col.DisplayFormat, + ReferenceEquals(colComparer, comparer) ? null : colComparer)); } return prepared?.ToArray() ?? Array.Empty(); } diff --git a/src/KumikoUI.Core/Models/ViewBuilder.cs b/src/KumikoUI.Core/Models/ViewBuilder.cs index 1fa81766..fb6264aa 100644 --- a/src/KumikoUI.Core/Models/ViewBuilder.cs +++ b/src/KumikoUI.Core/Models/ViewBuilder.cs @@ -43,8 +43,12 @@ public ItemReader(Func? accessor, string? path) /// A sort column, captured for one build: its reader, comparer and direction (1 or -1). internal readonly record struct SortSpec(ItemReader Reader, IComparer Comparer, int Direction); -/// A column filter, captured for one build: its value list as a set under the build's text rules. -internal sealed record FilterSpec(KumikoColumn Column, ItemReader Reader, FilterDescription Filter, ISet? Values, string? Format); +/// +/// A column filter, captured for one build: its value list as a set under the text rules of the filter, which are the +/// build's unless the column sets (, #373). +/// +internal sealed record FilterSpec(KumikoColumn Column, ItemReader Reader, FilterDescription Filter, ISet? Values, string? Format, + KumikoComparer? Comparer = null); /// One group level, captured for one build. internal sealed record GroupSpec( @@ -200,8 +204,8 @@ public static bool Passes(object item, Func? predicate, FilterSpec { var cellValue = spec.Reader.Read(item); // Only a value list compares display text; conditions read the value, so don't format for them. - string displayText = spec.Values != null ? comparer.Format(cellValue, spec.Format) : string.Empty; - if (!spec.Filter.Evaluate(cellValue, displayText, spec.Values, comparer)) + string displayText = spec.Values != null ? (spec.Comparer ?? comparer).Format(cellValue, spec.Format) : string.Empty; + if (!spec.Filter.Evaluate(cellValue, displayText, spec.Values, spec.Comparer ?? comparer)) return false; } diff --git a/src/KumikoUI.Core/PublicAPI.Unshipped.txt b/src/KumikoUI.Core/PublicAPI.Unshipped.txt index 3e3893c9..e392061a 100644 --- a/src/KumikoUI.Core/PublicAPI.Unshipped.txt +++ b/src/KumikoUI.Core/PublicAPI.Unshipped.txt @@ -523,8 +523,25 @@ KumikoUI.Core.Models.KumikoColumn.AllowHide.get -> bool KumikoUI.Core.Models.KumikoColumn.AllowHide.set -> void KumikoUI.Core.Models.KumikoColumn.AllowSearching.get -> bool KumikoUI.Core.Models.KumikoColumn.AllowSearching.set -> void +KumikoUI.Core.Models.KumikoColumn.AllowedDateFilterOperators.get -> System.Collections.Generic.IReadOnlyList? +KumikoUI.Core.Models.KumikoColumn.AllowedDateFilterOperators.set -> void +KumikoUI.Core.Models.KumikoColumn.AllowedFilterOperatorsString.get -> string? +KumikoUI.Core.Models.KumikoColumn.AllowedFilterOperatorsString.set -> void +KumikoUI.Core.Models.KumikoColumn.AllowedNumericFilterOperators.get -> System.Collections.Generic.IReadOnlyList? +KumikoUI.Core.Models.KumikoColumn.AllowedNumericFilterOperators.set -> void +KumikoUI.Core.Models.KumikoColumn.AllowedTextFilterOperators.get -> System.Collections.Generic.IReadOnlyList? +KumikoUI.Core.Models.KumikoColumn.AllowedTextFilterOperators.set -> void +KumikoUI.Core.Models.KumikoColumn.CreateDefaultFilterCondition() -> KumikoUI.Core.Models.FilterCondition! KumikoUI.Core.Models.KumikoColumn.CustomHeaderRenderer.get -> KumikoUI.Core.Rendering.IHeaderCellRenderer? KumikoUI.Core.Models.KumikoColumn.CustomHeaderRenderer.set -> void +KumikoUI.Core.Models.KumikoColumn.DefaultDateFilterOperator.get -> KumikoUI.Core.Models.DateFilterOperator? +KumikoUI.Core.Models.KumikoColumn.DefaultDateFilterOperator.set -> void +KumikoUI.Core.Models.KumikoColumn.DefaultNumericFilterOperator.get -> KumikoUI.Core.Models.NumericFilterOperator? +KumikoUI.Core.Models.KumikoColumn.DefaultNumericFilterOperator.set -> void +KumikoUI.Core.Models.KumikoColumn.DefaultTextFilterOperator.get -> KumikoUI.Core.Models.TextFilterOperator? +KumikoUI.Core.Models.KumikoColumn.DefaultTextFilterOperator.set -> void +KumikoUI.Core.Models.KumikoColumn.FilterCompareOptions.get -> System.Globalization.CompareOptions? +KumikoUI.Core.Models.KumikoColumn.FilterCompareOptions.set -> void KumikoUI.Core.Models.KumikoColumn.IsAutoGenerated.get -> bool KumikoUI.Core.Models.KumikoColumn.ShowInChooser.get -> bool KumikoUI.Core.Models.KumikoColumn.ShowInChooser.set -> void diff --git a/tests/KumikoUI.Core.Tests/BackgroundRebuildTests.cs b/tests/KumikoUI.Core.Tests/BackgroundRebuildTests.cs index e2f85596..01b06b95 100644 --- a/tests/KumikoUI.Core.Tests/BackgroundRebuildTests.cs +++ b/tests/KumikoUI.Core.Tests/BackgroundRebuildTests.cs @@ -1,6 +1,7 @@ using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; +using System.Globalization; using System.Runtime.CompilerServices; using KumikoUI.Core.Editing; using KumikoUI.Core.Models; @@ -435,6 +436,45 @@ public async Task SummaryChangesMadeWhileABuildRuns_AreInTheSummariesOfThePublis } } + // ── Per-column filter text rules (#373) ────────────────────── + + [Fact] + public async Task AColumnsFilterCompareOptions_ApplyInABackgroundRebuild_OnlyToThatColumn() + { + using var ui = new TestUiThread(); + var items = NewItems(2000); + var source = ui.Invoke(() => NewSource(items, threshold: 1000, out _)); + await Updated(ui, source); + int oslo = items.Count(i => i.City == "Oslo"); + + ui.Invoke(() => + { + var city = source.Columns[2]; + city.FilterCompareOptions = CompareOptions.None; + source.SetColumnFilter(city, new FilterDescription(city) + { + Condition1 = new FilterCondition { TextOperator = TextFilterOperator.Equals, Value = "oslo" }, + }); + }); + await Updated(ui, source); + Assert.Empty(ui.Invoke(() => Ids(source))); // case-sensitive: "oslo" is not "Oslo" + + ui.Invoke(() => source.SetColumnFilter(source.Columns[2], new FilterDescription(source.Columns[2]) + { + SelectedValues = new HashSet { "Oslo" }, + })); + await Updated(ui, source); + Assert.Equal(oslo, ui.Invoke(() => source.RowCount)); + + ui.Invoke(() => source.Columns[2].FilterCompareOptions = null); // back to the source's rule: ignore case + ui.Invoke(() => source.SetColumnFilter(source.Columns[2], new FilterDescription(source.Columns[2]) + { + Condition1 = new FilterCondition { TextOperator = TextFilterOperator.Equals, Value = "oslo" }, + })); + await Updated(ui, source); + Assert.Equal(oslo, ui.Invoke(() => source.RowCount)); + } + // ── A background view equals the synchronous one ───────────── [Fact] diff --git a/tests/KumikoUI.Core.Tests/ColumnFilterOptionsTests.cs b/tests/KumikoUI.Core.Tests/ColumnFilterOptionsTests.cs new file mode 100644 index 00000000..40e595e9 --- /dev/null +++ b/tests/KumikoUI.Core.Tests/ColumnFilterOptionsTests.cs @@ -0,0 +1,328 @@ +using System.Globalization; +using KumikoUI.Core.Components; +using KumikoUI.Core.Input; +using KumikoUI.Core.Models; +using KumikoUI.Core.Rendering; +using KumikoUI.Core.Tests.TestHelpers; + +namespace KumikoUI.Core.Tests; + +/// Per-column filter operators, default operator and text comparison (#373). +public class ColumnFilterOptionsTests +{ + private sealed class Row + { + public string Code { get; set; } = ""; + public string Name { get; set; } = ""; + public double Amount { get; set; } + } + + private static List Rows() => new() + { + new Row { Code = "ab", Name = "Ab", Amount = 1 }, + new Row { Code = "AB", Name = "AB", Amount = 2 }, + new Row { Code = "cd", Name = "cd", Amount = 3 }, + }; + + private static (KumikoSource Source, KumikoColumn Code, KumikoColumn Name) Create() + { + var source = new KumikoSource { Culture = CultureInfo.InvariantCulture }; + var code = new KumikoColumn { Header = "Code", PropertyName = "Code" }; + var name = new KumikoColumn { Header = "Name", PropertyName = "Name" }; + source.SetColumns(new[] { code, name }); + source.SetItems(Rows()); + return (source, code, name); + } + + private static List Codes(KumikoSource source) + { + var list = new List(); + for (int i = 0; i < source.RowCount; i++) list.Add(((Row)source.GetItem(i)).Code); + return list; + } + + // ── Defaults and the default condition ─────────────────────── + + [Fact] + public void Defaults_AreNull_AndTheDefaultConditionIsTheStockOne() + { + var column = new KumikoColumn(); + Assert.Null(column.AllowedTextFilterOperators); + Assert.Null(column.DefaultTextFilterOperator); + Assert.Null(column.FilterCompareOptions); + Assert.Null(column.AllowedFilterOperatorsString); + + var condition = column.CreateDefaultFilterCondition(); + Assert.Equal(TextFilterOperator.Contains, condition.TextOperator); + Assert.Equal(NumericFilterOperator.Equals, condition.NumericOperator); + Assert.Equal(DateFilterOperator.Equals, condition.DateOperator); + Assert.Null(condition.Value); + } + + [Fact] + public void CreateDefaultFilterCondition_HonorsTheDefaultOperators() + { + var column = new KumikoColumn + { + DefaultTextFilterOperator = TextFilterOperator.StartsWith, + DefaultNumericFilterOperator = NumericFilterOperator.GreaterThan, + DefaultDateFilterOperator = DateFilterOperator.After, + }; + var condition = column.CreateDefaultFilterCondition(); + Assert.Equal(TextFilterOperator.StartsWith, condition.TextOperator); + Assert.Equal(NumericFilterOperator.GreaterThan, condition.NumericOperator); + Assert.Equal(DateFilterOperator.After, condition.DateOperator); + } + + [Fact] + public void CreateDefaultFilterCondition_FallsBackToTheFirstAllowedOperator_WhenTheStockOneIsNotAllowed() + { + var column = new KumikoColumn + { + AllowedTextFilterOperators = new[] { TextFilterOperator.StartsWith, TextFilterOperator.Equals }, + }; + Assert.Equal(TextFilterOperator.StartsWith, column.CreateDefaultFilterCondition().TextOperator); + } + + [Fact] + public void CreateDefaultFilterCondition_ReturnsANewConditionEachTime() + { + var column = new KumikoColumn(); + Assert.NotSame(column.CreateDefaultFilterCondition(), column.CreateDefaultFilterCondition()); + } + + // ── Change notification ────────────────────────────────────── + + [Fact] + public void TheNewProperties_RaisePropertyChanged() + { + var column = new KumikoColumn(); + var names = new List(); + column.PropertyChanged += (_, e) => names.Add(e.PropertyName); + + column.AllowedTextFilterOperators = new[] { TextFilterOperator.Equals }; + column.AllowedNumericFilterOperators = new[] { NumericFilterOperator.Equals }; + column.AllowedDateFilterOperators = new[] { DateFilterOperator.Equals }; + column.DefaultTextFilterOperator = TextFilterOperator.Equals; + column.DefaultNumericFilterOperator = NumericFilterOperator.LessThan; + column.DefaultDateFilterOperator = DateFilterOperator.Before; + column.FilterCompareOptions = CompareOptions.None; + column.AllowedFilterOperatorsString = "Equals"; + + Assert.Equal(new[] + { + nameof(KumikoColumn.AllowedTextFilterOperators), nameof(KumikoColumn.AllowedNumericFilterOperators), + nameof(KumikoColumn.AllowedDateFilterOperators), nameof(KumikoColumn.DefaultTextFilterOperator), + nameof(KumikoColumn.DefaultNumericFilterOperator), nameof(KumikoColumn.DefaultDateFilterOperator), + nameof(KumikoColumn.FilterCompareOptions), nameof(KumikoColumn.AllowedTextFilterOperators), + nameof(KumikoColumn.AllowedFilterOperatorsString), + }, names); + } + + // ── The XAML string form ───────────────────────────────────── + + [Fact] + public void AllowedFilterOperatorsString_ParsesIntoTheListOfTheColumnType() + { + var text = new KumikoColumn { ColumnType = KumikoColumnType.Text, AllowedFilterOperatorsString = "StartsWith, equals" }; + Assert.Equal(new[] { TextFilterOperator.StartsWith, TextFilterOperator.Equals }, text.AllowedTextFilterOperators); + Assert.Null(text.AllowedNumericFilterOperators); + + var number = new KumikoColumn { ColumnType = KumikoColumnType.Numeric, AllowedFilterOperatorsString = "GreaterThan,Equals" }; + Assert.Equal(new[] { NumericFilterOperator.GreaterThan, NumericFilterOperator.Equals }, number.AllowedNumericFilterOperators); + + var date = new KumikoColumn { ColumnType = KumikoColumnType.Date, AllowedFilterOperatorsString = "Before,After" }; + Assert.Equal(new[] { DateFilterOperator.Before, DateFilterOperator.After }, date.AllowedDateFilterOperators); + Assert.Equal("Before,After", date.AllowedFilterOperatorsString); + } + + [Fact] + public void AllowedFilterOperatorsString_NullOrEmptyClearsTheList() + { + var column = new KumikoColumn { AllowedFilterOperatorsString = "Equals" }; + column.AllowedFilterOperatorsString = ""; + Assert.Null(column.AllowedTextFilterOperators); + Assert.Null(column.AllowedFilterOperatorsString); + } + + [Theory] + [InlineData(KumikoColumnType.Text, "Before")] + [InlineData(KumikoColumnType.Text, "Nope")] + [InlineData(KumikoColumnType.Text, "7")] + [InlineData(KumikoColumnType.Numeric, "StartsWith")] + [InlineData(KumikoColumnType.Date, "Contains")] + [InlineData(KumikoColumnType.Boolean, "Equals")] + public void AllowedFilterOperatorsString_ThrowsForANameTheColumnTypeDoesNotHave(KumikoColumnType type, string names) + { + var column = new KumikoColumn { ColumnType = type }; + Assert.Throws(() => column.AllowedFilterOperatorsString = names); + Assert.Null(column.AllowedFilterOperatorsString); + } + + [Fact] + public void AllowedFilterOperatorsString_IsParsedAgain_WhenTheColumnTypeChanges() + { + var column = new KumikoColumn { AllowedFilterOperatorsString = "Equals,NotEquals" }; + column.ColumnType = KumikoColumnType.Numeric; + Assert.Null(column.AllowedTextFilterOperators); + Assert.Equal(new[] { NumericFilterOperator.Equals, NumericFilterOperator.NotEquals }, column.AllowedNumericFilterOperators); + + column.ColumnType = KumikoColumnType.Date; // "Equals,NotEquals" fit the date operators too + Assert.Equal(new[] { DateFilterOperator.Equals, DateFilterOperator.NotEquals }, column.AllowedDateFilterOperators); + } + + // ── Case sensitivity ───────────────────────────────────────── + + [Fact] + public void FilterCompareOptions_ChangesHowTheColumnsConditionsCompare_WithoutAffectingOtherColumns() + { + var (source, code, name) = Create(); + code.FilterCompareOptions = CompareOptions.None; + + source.SetColumnFilter(code, new FilterDescription(code) + { + Condition1 = new FilterCondition { TextOperator = TextFilterOperator.Equals, Value = "ab" }, + }); + Assert.Equal(new[] { "ab" }, Codes(source)); + + source.SetColumnFilter(code, null); + source.SetColumnFilter(name, new FilterDescription(name) + { + Condition1 = new FilterCondition { TextOperator = TextFilterOperator.Equals, Value = "ab" }, + }); + Assert.Equal(new[] { "ab", "AB" }, Codes(source)); // the grid-wide rule: ignore case + } + + [Fact] + public void FilterCompareOptions_AppliesToTheValueListAndItsUniqueValues() + { + var (source, code, name) = Create(); + Assert.Equal(2, source.GetUniqueColumnValues(code).Count); + + code.FilterCompareOptions = CompareOptions.None; + Assert.Equal(3, source.GetUniqueColumnValues(code).Count); // "ab" and "AB" are two entries now + Assert.Equal(2, source.GetUniqueColumnValues(name).Count); + + source.SetColumnFilter(code, new FilterDescription(code) { SelectedValues = new HashSet { "ab" } }); + Assert.Equal(new[] { "ab" }, Codes(source)); + } + + [Fact] + public void FilterCompareOptions_ChangeRebuildsAnActiveFilter() + { + var (source, code, _) = Create(); + source.SetColumnFilter(code, new FilterDescription(code) + { + Condition1 = new FilterCondition { TextOperator = TextFilterOperator.Equals, Value = "ab" }, + }); + Assert.Equal(new[] { "ab", "AB" }, Codes(source)); + + code.FilterCompareOptions = CompareOptions.None; + Assert.Equal(new[] { "ab" }, Codes(source)); + + code.FilterCompareOptions = null; + Assert.Equal(new[] { "ab", "AB" }, Codes(source)); + } + + [Fact] + public void FilterDescriptionEvaluate_UsesTheColumnsOptions() + { + var column = new KumikoColumn { PropertyName = "Code", FilterCompareOptions = CompareOptions.None }; + var filter = new FilterDescription(column) + { + Condition1 = new FilterCondition { TextOperator = TextFilterOperator.StartsWith, Value = "ab" }, + SelectedValues = new HashSet { "abc" }, + }; + Assert.True(filter.Evaluate("abc", "abc")); + Assert.False(filter.Evaluate("ABC", "ABC")); + } + + [Fact] + public void TheColumnComparer_IsCached_AndFollowsTheCultureAndOptions() + { + var column = new KumikoColumn { FilterCompareOptions = CompareOptions.None }; + var invariant = new KumikoComparer(CultureInfo.InvariantCulture, CompareOptions.IgnoreCase); + var first = column.ResolveFilterComparer(invariant); + Assert.Same(first, column.ResolveFilterComparer(invariant)); + Assert.Equal(CompareOptions.None, first.Options); + + column.FilterCompareOptions = CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols; + Assert.NotSame(first, column.ResolveFilterComparer(invariant)); + + column.FilterCompareOptions = null; + Assert.Same(invariant, column.ResolveFilterComparer(invariant)); + } + + // ── The popup ──────────────────────────────────────────────── + + private static DrawnFilterPopup Open(KumikoSource source, KumikoColumn column) + { + var popup = new DrawnFilterPopup(column, source); + var manager = new PopupManager(); + manager.Show(popup, new KumikoRect(0, 0, 150, 0)); + var focus = new DrawnFocusManager(); + focus.Register(popup); + focus.SetFocus(popup); + popup.OnDraw(new RecordingDrawingContext()); + return popup; + } + + [Fact] + public void ThePopup_ListsOnlyTheAllowedOperators_InTheirOrder_AndStartsOnTheDefault() + { + var (source, code, _) = Create(); + code.AllowedFilterOperatorsString = "Equals,StartsWith"; + code.DefaultTextFilterOperator = TextFilterOperator.StartsWith; + + var popup = Open(source, code); + var strings = source.Strings; + Assert.Equal( + new[] { strings.FilterOperatorLabel(TextFilterOperator.Equals), strings.FilterOperatorLabel(TextFilterOperator.StartsWith) }, + popup.OperatorBox(0).Items.Select(i => i.DisplayText)); + Assert.Equal(TextFilterOperator.StartsWith, popup.OperatorBox(0).SelectedValue); + Assert.Equal(TextFilterOperator.StartsWith, popup.OperatorBox(1).SelectedValue); + } + + [Fact] + public void ThePopup_WithoutSettings_ListsEveryOperator_AndStartsOnContains() + { + var (source, code, _) = Create(); + var popup = Open(source, code); + Assert.Equal(8, popup.OperatorBox(0).Items.Count); + Assert.Equal(TextFilterOperator.Contains, popup.OperatorBox(0).SelectedValue); + } + + [Fact] + public void ThePopup_KeepsTheOperatorOfAConditionSetFromCode_EvenWhenNotAllowed() + { + var (source, code, _) = Create(); + code.AllowedTextFilterOperators = new[] { TextFilterOperator.Equals }; + source.SetColumnFilter(code, new FilterDescription(code) + { + Condition1 = new FilterCondition { TextOperator = TextFilterOperator.EndsWith, Value = "d" }, + }); + Assert.Equal(new[] { "cd" }, Codes(source)); // the code-set condition still filters + + var popup = Open(source, code); + Assert.Equal(2, popup.OperatorBox(0).Items.Count); + Assert.Equal(TextFilterOperator.EndsWith, popup.OperatorBox(0).SelectedValue); + } + + [Fact] + public void ThePopup_NumericAllowedOperatorsAndDefault() + { + var source = new KumikoSource { Culture = CultureInfo.InvariantCulture }; + var amount = new KumikoColumn + { + PropertyName = "Amount", + ColumnType = KumikoColumnType.Numeric, + AllowedNumericFilterOperators = new[] { NumericFilterOperator.GreaterThan, NumericFilterOperator.LessThan }, + DefaultNumericFilterOperator = NumericFilterOperator.LessThan, + }; + source.SetColumns(new[] { amount }); + source.SetItems(Rows()); + var popup = Open(source, amount); + Assert.Equal(2, popup.OperatorBox(0).Items.Count); + Assert.Equal(NumericFilterOperator.LessThan, popup.OperatorBox(0).SelectedValue); + } +}