Skip to content

Commit 36a29a8

Browse files
Merge pull request #4 from SolidProgramming/feature/column-filters
Add per-column filters to FancyTable and FancyTreeTable
2 parents 309d733 + 1237876 commit 36a29a8

23 files changed

Lines changed: 1612 additions & 8 deletions

‎.github/workflows/dotnet-build.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,6 @@ jobs:
2626

2727
- name: Build project
2828
run: dotnet build SoPro.FancyTable.csproj --configuration Release --no-restore
29+
30+
- name: Test
31+
run: dotnet test tests/SoPro.FancyTable.Tests --configuration Release

‎Components/FancyColumn.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ public sealed class FancyColumn<TItem>
1010
public bool Hideable { get; init; }
1111
public bool Resizable { get; init; } = true;
1212
public bool Reorderable { get; init; } = true;
13+
public bool Filterable { get; init; }
1314

1415
public double? Width { get; init; }
1516
public double? MinWidth { get; init; }

‎Components/FancyColumnFilter.cs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public enum FancyColumnFilterOperator
2+
{
3+
Equals = 0,
4+
NotEquals = 1,
5+
Contains = 2,
6+
NotContains = 3,
7+
StartsWith = 4,
8+
EndsWith = 5,
9+
IsEmpty = 6,
10+
IsNotEmpty = 7
11+
}
12+
13+
public sealed record FancyColumnFilter(string Key, FancyColumnFilterOperator Operator, string? Value = null);
14+
15+
internal static class FancyColumnFilterExtensions
16+
{
17+
internal static bool RequiresValue(this FancyColumnFilterOperator op)
18+
{
19+
return op is not (FancyColumnFilterOperator.IsEmpty or FancyColumnFilterOperator.IsNotEmpty);
20+
}
21+
22+
internal static bool IsEffective(this FancyColumnFilter filter)
23+
{
24+
return !filter.Operator.RequiresValue() || !string.IsNullOrWhiteSpace(filter.Value);
25+
}
26+
}
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
@implements IAsyncDisposable
2+
@using System.Globalization
3+
@using Microsoft.AspNetCore.Components.Web
4+
@using Microsoft.JSInterop
5+
@inject IJSRuntime JS
6+
7+
<button type="button"
8+
class="btn btn-link p-0 border-0 fancy-filter-button"
9+
aria-label="@FormatColumnLabel(Texts.FilterColumnFormat, ColumnTitle)"
10+
aria-haspopup="dialog"
11+
aria-expanded="@(isOpen ? "true" : "false")"
12+
popovertarget="@popupId"
13+
@ref="anchorElement"
14+
@onclick="Open">
15+
<i class="bi @(ActiveFilter is null ? "bi-funnel" : "bi-funnel-fill")" aria-hidden="true"></i>
16+
</button>
17+
18+
<div popover="auto" id="@popupId" class="fancy-filter-popup" @ref="popupElement">
19+
<div class="d-flex flex-column gap-2 p-2">
20+
<select class="form-select form-select-sm" @bind="draftOperator">
21+
@foreach (FancyColumnFilterOperator op in Operators)
22+
{
23+
<option value="@op.ToString()">@GetOperatorLabel(op)</option>
24+
}
25+
</select>
26+
27+
@if (draftOperator.RequiresValue())
28+
{
29+
<input type="text"
30+
class="form-control form-control-sm"
31+
placeholder="@Texts.FilterValuePlaceholder"
32+
value="@draftValue"
33+
@oninput="OnValueInput"
34+
@onkeydown="OnValueKeyDown" />
35+
}
36+
37+
<div class="d-flex justify-content-end gap-2">
38+
<button type="button"
39+
class="btn btn-sm btn-outline-secondary"
40+
disabled="@(ActiveFilter is null)"
41+
@onclick="ClearAsync">
42+
@Texts.ClearFilterLabel
43+
</button>
44+
<button type="button"
45+
class="btn btn-sm btn-primary"
46+
disabled="@(!CanApply)"
47+
@onclick="ApplyAsync">
48+
@Texts.ApplyFilterLabel
49+
</button>
50+
</div>
51+
</div>
52+
</div>
53+
54+
@code {
55+
private static readonly FancyColumnFilterOperator[] Operators = Enum.GetValues<FancyColumnFilterOperator>();
56+
57+
private readonly string popupId = $"fancy-filter-{Guid.NewGuid():N}";
58+
private ElementReference anchorElement;
59+
private ElementReference popupElement;
60+
private IJSObjectReference? module;
61+
private DotNetObjectReference<FancyColumnFilterPopup>? dotNetReference;
62+
private FancyColumnFilterOperator draftOperator = FancyColumnFilterOperator.Contains;
63+
private string draftValue = string.Empty;
64+
private bool isOpen;
65+
private bool showPending;
66+
67+
[Parameter, EditorRequired]
68+
public string ColumnKey { get; set; } = string.Empty;
69+
70+
[Parameter, EditorRequired]
71+
public string ColumnTitle { get; set; } = string.Empty;
72+
73+
[Parameter]
74+
public FancyColumnFilter? ActiveFilter { get; set; }
75+
76+
[Parameter, EditorRequired]
77+
public FancyTableTexts Texts { get; set; } = FancyTableTexts.Default;
78+
79+
[Parameter]
80+
public EventCallback<FancyColumnFilter> OnApply { get; set; }
81+
82+
[Parameter]
83+
public EventCallback OnClear { get; set; }
84+
85+
private FancyColumnFilter Draft => new(
86+
ColumnKey,
87+
draftOperator,
88+
draftOperator.RequiresValue() ? draftValue : null);
89+
90+
private bool CanApply => Draft.IsEffective();
91+
92+
private void Open()
93+
{
94+
// The button is a native popover invoker: while open, this click is closed by the browser
95+
// (reported back through OnPopoverClosed), so the open path must not run again.
96+
if (isOpen)
97+
{
98+
return;
99+
}
100+
101+
draftOperator = ActiveFilter?.Operator ?? FancyColumnFilterOperator.Contains;
102+
draftValue = ActiveFilter?.Value ?? string.Empty;
103+
isOpen = true;
104+
showPending = true;
105+
}
106+
107+
protected override async Task OnAfterRenderAsync(bool firstRender)
108+
{
109+
if (!showPending)
110+
{
111+
return;
112+
}
113+
114+
showPending = false;
115+
module ??= await JS.InvokeAsync<IJSObjectReference>("import", "./_content/SoPro.FancyTable/fancy-table-filter.js");
116+
dotNetReference ??= DotNetObjectReference.Create(this);
117+
await module.InvokeVoidAsync("show", anchorElement, popupElement, dotNetReference);
118+
}
119+
120+
private void OnValueInput(ChangeEventArgs args)
121+
{
122+
draftValue = args.Value?.ToString() ?? string.Empty;
123+
}
124+
125+
private async Task OnValueKeyDown(KeyboardEventArgs args)
126+
{
127+
if (args.Key == "Enter" && CanApply)
128+
{
129+
await ApplyAsync();
130+
}
131+
}
132+
133+
private async Task ApplyAsync()
134+
{
135+
if (!CanApply)
136+
{
137+
return;
138+
}
139+
140+
await OnApply.InvokeAsync(Draft);
141+
await HideAsync();
142+
}
143+
144+
private async Task ClearAsync()
145+
{
146+
await OnClear.InvokeAsync();
147+
await HideAsync();
148+
}
149+
150+
private async Task HideAsync()
151+
{
152+
if (module is not null)
153+
{
154+
await module.InvokeVoidAsync("hide", popupElement);
155+
}
156+
}
157+
158+
[JSInvokable]
159+
public Task OnPopoverClosed()
160+
{
161+
isOpen = false;
162+
StateHasChanged();
163+
return Task.CompletedTask;
164+
}
165+
166+
private string GetOperatorLabel(FancyColumnFilterOperator op) => op switch
167+
{
168+
FancyColumnFilterOperator.Equals => Texts.FilterOperatorEqualsLabel,
169+
FancyColumnFilterOperator.NotEquals => Texts.FilterOperatorNotEqualsLabel,
170+
FancyColumnFilterOperator.Contains => Texts.FilterOperatorContainsLabel,
171+
FancyColumnFilterOperator.NotContains => Texts.FilterOperatorNotContainsLabel,
172+
FancyColumnFilterOperator.StartsWith => Texts.FilterOperatorStartsWithLabel,
173+
FancyColumnFilterOperator.EndsWith => Texts.FilterOperatorEndsWithLabel,
174+
FancyColumnFilterOperator.IsEmpty => Texts.FilterOperatorIsEmptyLabel,
175+
FancyColumnFilterOperator.IsNotEmpty => Texts.FilterOperatorIsNotEmptyLabel,
176+
_ => op.ToString()
177+
};
178+
179+
private static string FormatColumnLabel(string format, string title) =>
180+
string.Format(CultureInfo.CurrentCulture, format, title);
181+
182+
public async ValueTask DisposeAsync()
183+
{
184+
if (module is not null)
185+
{
186+
try
187+
{
188+
await module.InvokeVoidAsync("dispose", popupElement);
189+
await module.DisposeAsync();
190+
}
191+
catch (JSDisconnectedException)
192+
{
193+
}
194+
}
195+
196+
dotNetReference?.Dispose();
197+
}
198+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
.fancy-filter-popup {
2+
min-width: 14rem;
3+
padding: 0;
4+
background: #fff;
5+
border: 1px solid #dee2e6;
6+
border-radius: 6px;
7+
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
8+
}
9+
10+
.fancy-filter-popup:not([data-positioned]) {
11+
visibility: hidden;
12+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
internal sealed class FancyColumnFilterState<TItem>
2+
{
3+
private readonly Dictionary<string, FancyColumnFilter> filters = new(StringComparer.Ordinal);
4+
private List<string> columnOrder = [];
5+
private HashSet<string> filterableKeys = new(StringComparer.Ordinal);
6+
private bool initialApplied;
7+
8+
public bool HasActiveFilters => filters.Count > 0;
9+
10+
public void Synchronize(
11+
IReadOnlyList<FancyColumn<TItem>> columns,
12+
IReadOnlyList<FancyColumnFilter>? initialFilters)
13+
{
14+
columnOrder = columns.Select(column => column.Key).Distinct(StringComparer.Ordinal).ToList();
15+
filterableKeys = columns
16+
.Where(column => column.Filterable)
17+
.Select(column => column.Key)
18+
.ToHashSet(StringComparer.Ordinal);
19+
20+
if (!initialApplied)
21+
{
22+
foreach (FancyColumnFilter filter in initialFilters ?? [])
23+
{
24+
FancyColumnFilter normalized = Normalize(filter);
25+
if (normalized.IsEffective()
26+
&& filterableKeys.Contains(normalized.Key)
27+
&& !filters.ContainsKey(normalized.Key))
28+
{
29+
filters[normalized.Key] = normalized;
30+
}
31+
}
32+
33+
initialApplied = true;
34+
}
35+
36+
foreach (string key in filters.Keys.Where(key => !filterableKeys.Contains(key)).ToList())
37+
{
38+
filters.Remove(key);
39+
}
40+
}
41+
42+
public FancyColumnFilter? Get(string key) =>
43+
filters.TryGetValue(key, out FancyColumnFilter? filter) ? filter : null;
44+
45+
public bool Set(FancyColumnFilter filter)
46+
{
47+
FancyColumnFilter normalized = Normalize(filter);
48+
if (!normalized.IsEffective()
49+
|| !filterableKeys.Contains(normalized.Key)
50+
|| (filters.TryGetValue(normalized.Key, out FancyColumnFilter? existing) && existing == normalized))
51+
{
52+
return false;
53+
}
54+
55+
filters[normalized.Key] = normalized;
56+
return true;
57+
}
58+
59+
public bool Remove(string key) => filters.Remove(key);
60+
61+
public IReadOnlyList<FancyColumnFilter> GetFilters() =>
62+
columnOrder.Where(filters.ContainsKey).Select(key => filters[key]).ToList();
63+
64+
private static FancyColumnFilter Normalize(FancyColumnFilter filter) =>
65+
filter.Operator.RequiresValue() || filter.Value is null ? filter : filter with { Value = null };
66+
}

0 commit comments

Comments
 (0)