Repository navigation
Expand file tree
/
Copy pathFancyTreeTable.razor
More file actions
988 lines (826 loc) · 33.6 KB
/
Copy pathFancyTreeTable.razor
File metadata and controls
988 lines (826 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
@typeparam TItem where TItem : notnull
@implements IAsyncDisposable
@using System.Globalization
@using Microsoft.JSInterop
@inject IJSRuntime JS
@{
PagedNodesResult pagedNodes = GetPagedNodes();
}
<div class="@GetTopBarClass()">
@if (ShouldRenderPageSizeSelector)
{
<div class="@GetPageSizeContainerClass()">
@if (PageSizeTemplate is not null)
{
@PageSizeTemplate(pagedNodes.Context)
}
else
{
<label class="d-inline-flex align-items-center gap-2 small text-muted">
<span>@ResolvedRowsPerPageLabel</span>
<select class="form-select form-select-sm w-auto" value="@PaginationPageSize" @onchange="OnPageSizeChanged">
@foreach (int option in EffectivePageSizeOptions)
{
<option value="@option">@(option == 0 ? ResolvedAllItemsLabel : option.ToString(CultureInfo.CurrentCulture))</option>
}
</select>
</label>
}
</div>
}
@if (ToolbarTemplate is not null)
{
<div class="@GetToolbarContainerClass()">
@ToolbarTemplate
</div>
}
else
{
<div class="@GetToolbarContainerClass()">
<input class="form-control form-control-md" placeholder="@ResolvedSearchPlaceholder" value="@SearchText" @oninput="OnSearchInput" @onkeyup="HandleSearchKeyPress" />
@if (string.IsNullOrWhiteSpace(SearchText))
{
<button class="btn btn-sm btn-outline-secondary mx-1" @onclick="ApplySearch">
<i class="bi bi-search"></i>
</button>
}
else
{
<button class="btn btn-sm btn-outline-secondary mx-1" @onclick="ClearSearch">
<i class="bi bi-x-lg"></i>
</button>
}
</div>
}
</div>
@if (TreeActionsTemplate is not null)
{
<div class="@GetTreeActionsContainerClass()">
@TreeActionsTemplate(TreeContext)
</div>
}
<div class="tree-table-container">
<table class="@GetTableClass()" @ref="tableElement">
<colgroup>
@foreach (FancyColumn<TItem> column in VisibleColumns)
{
<col data-column-key="@column.Key" style="@columnLayout.GetColumnStyle(column.Key)" />
}
</colgroup>
<thead>
<tr>
@foreach (FancyColumn<TItem> column in VisibleColumns)
{
<th class="@column.HeaderClass"
style="@columnLayout.GetColumnStyle(column.Key)"
data-column-key="@column.Key"
data-reorderable="@(CanReorder(column) ? "true" : "false")"
data-min-width="@GetDataWidth(column.MinWidth)"
data-max-width="@GetDataWidth(column.MaxWidth)">
<div class="fancy-column-header d-inline-flex align-items-center gap-1">
@if (CanReorder(column))
{
<button type="button"
class="fancy-column-reorder-handle"
data-column-reorder-handle
aria-label="@FormatColumnLabel(ResolvedTexts.ReorderColumnFormat, column.Title)">
<i class="bi bi-grip-vertical" aria-hidden="true"></i>
</button>
}
<span class="col-title">@column.Title</span>
@if (column.Sortable)
{
<button class="btn btn-link p-0 border-0" @onclick="() => SortBy(column.Key)">
<i class="bi @(GetSortIcon(column.Key))"></i>
</button>
}
@if (column.Hideable && !IsPinnedTreeColumn(column.Key))
{
<button class="btn btn-link p-0 border-0" @onclick="() => HideColumn(column.Key)">
<i class="bi bi-eye-slash"></i>
</button>
}
</div>
@if (EnableColumnResizing && column.Resizable)
{
<span class="fancy-column-resize-handle"
data-column-resize-handle
role="separator"
tabindex="0"
aria-orientation="vertical"
aria-label="@FormatColumnLabel(ResolvedTexts.ResizeColumnFormat, column.Title)"></span>
}
</th>
}
</tr>
</thead>
<tbody>
@foreach (TreeNodeState<TItem> node in pagedNodes.Items)
{
<FancyTreeRow TItem="TItem"
Node="node"
VisibleColumns="VisibleColumnsList"
ColumnWidths="columnLayout.Widths"
ToggleNode="ToggleNodeAsync"
RowClassSelector="RowClassSelector"
RowAttributesSelector="RowAttributesSelector"
RowLeadingContentTemplate="RowLeadingContentTemplate"
RowTemplate="RowTemplate"
RowTemplateSelector="RowTemplateSelector"
ExpandLabel="ResolvedExpandLabel"
CollapseLabel="ResolvedCollapseLabel" />
}
</tbody>
</table>
</div>
@if (HiddenColumns.Count > 0)
{
<div class="mt-2 ps-2 py-1">
<small class="text-muted me-2">@ResolvedHiddenColumnsLabel</small>
@foreach (string key in HiddenColumns)
{
FancyColumn<TItem>? column = Columns.FirstOrDefault(c => c.Key == key);
if (column is not null)
{
<button class="btn btn-sm btn-outline-secondary me-1" @onclick="() => ShowColumn(key)">
<i class="bi bi-eye me-1"></i>@column.Title
</button>
}
}
</div>
}
@if (ShouldRenderPaginationFooter(pagedNodes.Context))
{
<div class="@GetPaginationContainerClass()">
@if (PaginationTemplate is not null)
{
@PaginationTemplate(pagedNodes.Context)
}
else
{
<div class="@GetPaginationSummaryClass()">
@if (PaginationSummaryTemplate is not null)
{
@PaginationSummaryTemplate(pagedNodes.Context)
}
else if (ShowPaginationSummary)
{
@GetDefaultPaginationSummary(pagedNodes.Context)
}
</div>
@if (pagedNodes.Context.PageCount > 1)
{
<div class="btn-group btn-group-sm" role="group" aria-label="@ResolvedPaginationAriaLabel">
<button type="button"
class="btn btn-outline-secondary"
disabled="@(!pagedNodes.Context.HasPreviousPage)"
@onclick="pagedNodes.Context.GoToPreviousPage">
@ResolvedPreviousPageLabel
</button>
@foreach (int pageNumber in GetVisiblePageNumbers(pagedNodes.Context))
{
<button type="button"
class="btn @(pageNumber == pagedNodes.Context.CurrentPage ? "btn-primary" : "btn-outline-secondary")"
@onclick="() => pagedNodes.Context.GoToPage(pageNumber)">
@pageNumber
</button>
}
<button type="button"
class="btn btn-outline-secondary"
disabled="@(!pagedNodes.Context.HasNextPage)"
@onclick="pagedNodes.Context.GoToNextPage">
@ResolvedNextPageLabel
</button>
</div>
}
}
</div>
}
@code {
private static readonly IReadOnlyList<int> DefaultPageSizeOptions = [10, 25, 50, 100];
[Parameter, EditorRequired]
public required IReadOnlyList<TItem> Items { get; set; } = Array.Empty<TItem>();
[Parameter, EditorRequired]
public required IReadOnlyList<FancyColumn<TItem>> Columns { get; set; } = Array.Empty<FancyColumn<TItem>>();
[Parameter, EditorRequired]
public required Func<TItem, IEnumerable<TItem>?> ChildItemsSelector { get; set; }
[Parameter]
public Func<TItem, bool>? HasChildrenSelector { get; set; }
[Parameter]
public Func<TItem, bool>? InitiallyExpandedSelector { get; set; }
[Parameter]
public FancyTableTexts? Texts { get; set; }
[Parameter]
public RenderFragment? ToolbarTemplate { get; set; }
[Parameter]
public Func<TItem, string, bool>? SearchPredicate { get; set; }
[Parameter]
public Func<TItem, string?>? RowClassSelector { get; set; }
[Parameter]
public Func<FancyRowContext<TItem>, IReadOnlyDictionary<string, object?>?>? RowAttributesSelector { get; set; }
[Parameter]
public RenderFragment<FancyRowContext<TItem>>? RowLeadingContentTemplate { get; set; }
[Parameter]
public RenderFragment<FancyRowContext<TItem>>? RowTemplate { get; set; }
[Parameter]
public Func<FancyRowContext<TItem>, bool>? RowTemplateSelector { get; set; }
[Parameter]
public bool PaginationEnabled { get; set; }
[Parameter]
public int PageSize { get; set; } = 25;
[Parameter]
public EventCallback<int> PageSizeChanged { get; set; }
[Parameter]
public int CurrentPage { get; set; } = 1;
[Parameter]
public EventCallback<int> CurrentPageChanged { get; set; }
[Parameter]
public IReadOnlyList<int>? PageSizeOptions { get; set; }
[Parameter]
public bool ShowPaginationSummary { get; set; } = true;
[Parameter]
public bool ShowPageSizeSelector { get; set; }
[Parameter]
public RenderFragment<FancyPaginationContext<TItem>>? PaginationSummaryTemplate { get; set; }
[Parameter]
public RenderFragment<FancyPaginationContext<TItem>>? PaginationTemplate { get; set; }
[Parameter]
public RenderFragment<FancyPaginationContext<TItem>>? PageSizeTemplate { get; set; }
[Parameter]
public RenderFragment<FancyTreeTableContext<TItem>>? TreeActionsTemplate { get; set; }
[Parameter]
public string? TopBarClass { get; set; }
[Parameter]
public string? ToolbarContainerClass { get; set; }
[Parameter]
public string? PageSizeContainerClass { get; set; }
[Parameter]
public string? TreeActionsContainerClass { get; set; }
[Parameter]
public string? PaginationContainerClass { get; set; }
[Parameter]
public string? PaginationSummaryClass { get; set; }
[Parameter]
public bool EnableColumnResizing { get; set; }
[Parameter]
public bool EnableColumnReordering { get; set; }
[Parameter]
public IReadOnlyList<FancyColumnLayout>? InitialColumnLayout { get; set; }
[Parameter]
public EventCallback<IReadOnlyList<FancyColumnLayout>> ColumnLayoutChanged { get; set; }
private readonly HashSet<string> HiddenColumns = new(StringComparer.Ordinal);
private readonly FancyColumnLayoutController<TItem> columnLayout = new();
private readonly Dictionary<TItem, bool> ExpandedStates = new();
private readonly List<TreeNodeState<TItem>> RootNodes = [];
private ElementReference tableElement;
private IJSObjectReference? columnModule;
private DotNetObjectReference<FancyTreeTable<TItem>>? dotNetReference;
private string? SortColumnKey;
private bool SortAscending = true;
private string SearchText = string.Empty;
private string AppliedSearchText = string.Empty;
private Timer? debounceTimer;
private int paginationCurrentPage = 1;
private int paginationPageSize = 25;
private bool paginationStateInitialized;
private FancyTableTexts ResolvedTexts => Texts ?? FancyTableTexts.Default;
private string ResolvedSearchPlaceholder => ResolvedTexts.SearchPlaceholder;
private string ResolvedRowsPerPageLabel => ResolvedTexts.RowsPerPageLabel;
private string ResolvedAllItemsLabel => ResolvedTexts.AllItemsLabel;
private string ResolvedHiddenColumnsLabel => ResolvedTexts.HiddenColumnsLabel;
private string ResolvedPaginationAriaLabel => ResolvedTexts.PaginationAriaLabel;
private string ResolvedPreviousPageLabel => ResolvedTexts.PreviousPageLabel;
private string ResolvedNextPageLabel => ResolvedTexts.NextPageLabel;
private string ResolvedExpandLabel => ResolvedTexts.ExpandLabel;
private string ResolvedCollapseLabel => ResolvedTexts.CollapseLabel;
private string? PinnedTreeColumnKey => EnableColumnReordering ? Columns.FirstOrDefault()?.Key : null;
private IEnumerable<FancyColumn<TItem>> VisibleColumns =>
columnLayout.GetOrderedColumns().Where(c => !HiddenColumns.Contains(c.Key));
private IReadOnlyList<FancyColumn<TItem>> VisibleColumnsList => VisibleColumns.ToList();
private bool IsPaginationActive => PaginationEnabled && PaginationPageSize > 0;
private bool IsColumnLayoutEnabled =>
EnableColumnResizing || EnableColumnReordering || Columns.Any(column => column.Width.HasValue || column.MaxWidth.HasValue);
private bool ShouldRenderPageSizeSelector => PaginationEnabled && ShowPageSizeSelector;
private int PaginationPageSize => paginationPageSize > 0 ? paginationPageSize : 0;
private FancyTreeTableContext<TItem> TreeContext => BuildTreeContext();
private string CurrentFilter =>
string.IsNullOrWhiteSpace(AppliedSearchText) ? SearchText : AppliedSearchText;
private IReadOnlyList<int> EffectivePageSizeOptions
{
get
{
IEnumerable<int> options = (PageSizeOptions ?? DefaultPageSizeOptions)
.Where(static option => option >= 0)
.Distinct()
.OrderBy(static option => option);
if (!options.Contains(0))
{
options = options.Append(0).OrderBy(static option => option);
}
if (PageSize >= 0 && !options.Contains(PageSize))
{
options = options.Append(PageSize).OrderBy(static option => option);
}
if (PaginationPageSize >= 0 && !options.Contains(PaginationPageSize))
{
options = options.Append(PaginationPageSize).OrderBy(static option => option);
}
List<int> normalizedOptions = options.ToList();
return normalizedOptions.Count > 0 ? normalizedOptions : [0, .. DefaultPageSizeOptions];
}
}
protected override void OnParametersSet()
{
columnLayout.Synchronize(Columns, InitialColumnLayout, PinnedTreeColumnKey);
if (PinnedTreeColumnKey is string pinnedKey)
{
HiddenColumns.Remove(pinnedKey);
}
SyncPaginationStateFromParameters();
RebuildTree();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!EnableColumnResizing
&& !EnableColumnReordering
&& columnLayout.Widths.Count == 0
&& !columnLayout.GetOrderedColumns().Any(column => column.MaxWidth.HasValue))
{
return;
}
columnModule ??= await JS.InvokeAsync<IJSObjectReference>("import", "./_content/SoPro.FancyTable/fancy-table-columns.js");
dotNetReference ??= DotNetObjectReference.Create(this);
await columnModule.InvokeVoidAsync("initialize", tableElement, dotNetReference, new
{
resizing = EnableColumnResizing,
reordering = EnableColumnReordering
});
}
private void RebuildTree()
{
RootNodes.Clear();
IEnumerable<TItem> sortedRootItems = ApplySiblingSort(FilterNullItems(Items));
foreach (TItem item in sortedRootItems)
{
TreeNodeState<TItem> rootNode = BuildNode(item, depth: 0, parent: null, ancestors: []);
RootNodes.Add(rootNode);
}
RemoveObsoleteExpandedStates();
}
private TreeNodeState<TItem> BuildNode(
TItem item,
int depth,
TreeNodeState<TItem>? parent,
HashSet<TItem> ancestors)
{
bool addedToAncestors = ancestors.Add(item);
IEnumerable<TItem> childItems = Enumerable.Empty<TItem>();
if (addedToAncestors)
{
childItems = FilterNullItems(ChildItemsSelector(item) ?? Enumerable.Empty<TItem>());
}
List<TItem> orderedChildren = ApplySiblingSort(childItems).ToList();
bool hasChildren = HasChildrenSelector?.Invoke(item) ?? orderedChildren.Count > 0;
bool isExpanded = GetOrInitializeExpandedState(item);
TreeNodeState<TItem> node = new()
{
Item = item,
Depth = depth,
Parent = parent,
HasChildren = hasChildren,
IsExpanded = hasChildren && isExpanded,
Children = []
};
if (addedToAncestors)
{
foreach (TItem childItem in orderedChildren)
{
TreeNodeState<TItem> childNode = BuildNode(childItem, depth + 1, node, ancestors);
node.Children.Add(childNode);
}
ancestors.Remove(item);
}
return node;
}
private IEnumerable<TItem> ApplySiblingSort(IEnumerable<TItem> items) =>
TableQueryHelpers.ApplySort(items, SortColumnKey, SortAscending, Columns);
private static IEnumerable<TItem> FilterNullItems(IEnumerable<TItem> items) =>
items.Where(static item => item is not null);
private bool MatchesSearch(TItem item, string filter) =>
TableQueryHelpers.MatchesSearch(item, filter, Columns, SearchPredicate);
private PagedNodesResult GetPagedNodes()
{
List<TreeNodeState<TItem>> visibleNodes = BuildVisibleNodes();
FancyPaginationContext<TItem> paginationContext = BuildPaginationContext(
totalItemCount: RootNodes.Count,
filteredItemCount: visibleNodes.Count);
IReadOnlyList<TreeNodeState<TItem>> pagedItems = ApplyPagination(visibleNodes, paginationContext);
return new PagedNodesResult { Items = pagedItems, Context = paginationContext };
}
private List<TreeNodeState<TItem>> BuildVisibleNodes()
{
string filter = CurrentFilter;
List<TreeNodeState<TItem>> visibleNodes = [];
if (string.IsNullOrWhiteSpace(filter))
{
foreach (TreeNodeState<TItem> root in RootNodes)
{
CollectExpandedNodes(root, visibleNodes);
}
}
else
{
foreach (TreeNodeState<TItem> root in RootNodes)
{
CollectSearchNodes(root, filter, visibleNodes, out _);
}
}
return visibleNodes;
}
private void CollectExpandedNodes(TreeNodeState<TItem> node, List<TreeNodeState<TItem>> visibleNodes)
{
visibleNodes.Add(node);
if (!node.IsExpanded)
{
return;
}
foreach (TreeNodeState<TItem> child in node.Children)
{
CollectExpandedNodes(child, visibleNodes);
}
}
private bool CollectSearchNodes(
TreeNodeState<TItem> node,
string filter,
List<TreeNodeState<TItem>> visibleNodes,
out bool includeNode)
{
bool matchesSelf = MatchesSearch(node.Item, filter);
int insertIndex = visibleNodes.Count;
List<TreeNodeState<TItem>> childMatches = [];
foreach (TreeNodeState<TItem> child in node.Children)
{
CollectSearchNodes(child, filter, childMatches, out bool childIncluded);
_ = childIncluded;
}
includeNode = matchesSelf || childMatches.Count > 0;
if (!includeNode)
{
return false;
}
visibleNodes.Insert(insertIndex, node);
visibleNodes.AddRange(childMatches);
return true;
}
private void SortBy(string columnKey)
{
if (SortColumnKey == columnKey)
{
SortAscending = !SortAscending;
}
else
{
SortColumnKey = columnKey;
SortAscending = true;
}
RebuildTree();
}
private string GetSortIcon(string key)
{
if (SortColumnKey != key)
{
return "bi-arrow-down-up";
}
return SortAscending ? "bi-sort-up" : "bi-sort-down";
}
private void HideColumn(string key) => HiddenColumns.Add(key);
private void ShowColumn(string key) => HiddenColumns.Remove(key);
private bool IsPinnedTreeColumn(string key) => PinnedTreeColumnKey == key;
private bool CanReorder(FancyColumn<TItem> column) =>
EnableColumnReordering && column.Reorderable && !IsPinnedTreeColumn(column.Key);
private static string FormatColumnLabel(string format, string title) =>
string.Format(CultureInfo.CurrentCulture, format, title);
private static string? GetDataWidth(double? width) =>
width is double value ? value.ToString(CultureInfo.InvariantCulture) : null;
[JSInvokable]
public async Task OnColumnResizeCompleted(FancyColumnLayout[] measurements)
{
columnLayout.ApplyMeasuredWidths(measurements);
await ColumnLayoutChanged.InvokeAsync(columnLayout.GetLayout());
await InvokeAsync(StateHasChanged);
}
[JSInvokable]
public async Task OnColumnReorderCompleted(string sourceKey, string targetKey, bool insertAfter)
{
if (!EnableColumnReordering || !columnLayout.TryReorder(sourceKey, targetKey, insertAfter, PinnedTreeColumnKey))
{
return;
}
await ColumnLayoutChanged.InvokeAsync(columnLayout.GetLayout());
await InvokeAsync(StateHasChanged);
}
private bool GetOrInitializeExpandedState(TItem item)
{
if (ExpandedStates.TryGetValue(item, out bool isExpanded))
{
return isExpanded;
}
bool initialState = InitiallyExpandedSelector?.Invoke(item) ?? false;
ExpandedStates[item] = initialState;
return initialState;
}
private Task ToggleNodeAsync(TreeNodeState<TItem> node)
{
node.IsExpanded = !node.IsExpanded;
ExpandedStates[node.Item] = node.IsExpanded;
return Task.CompletedTask;
}
public async Task ExpandAllAsync()
{
SetExpandedStateForAllNodes(expanded: true);
await InvokeAsync(StateHasChanged);
}
public async Task CollapseAllAsync()
{
SetExpandedStateForAllNodes(expanded: false);
await InvokeAsync(StateHasChanged);
}
private void HandleSearchKeyPress(KeyboardEventArgs e)
{
if (e.Key == "Enter")
{
debounceTimer?.Dispose();
ApplySearch();
}
}
private void ApplySearch()
{
AppliedSearchText = SearchText;
paginationCurrentPage = 1;
StateHasChanged();
}
private void ClearSearch()
{
SearchText = string.Empty;
AppliedSearchText = string.Empty;
paginationCurrentPage = 1;
StateHasChanged();
}
private void OnSearchInput(ChangeEventArgs e)
{
SearchText = e.Value?.ToString() ?? string.Empty;
debounceTimer?.Dispose();
debounceTimer = new Timer(_ =>
{
_ = InvokeAsync(() =>
{
AppliedSearchText = SearchText;
paginationCurrentPage = 1;
StateHasChanged();
});
}, null, 250, Timeout.Infinite);
}
private FancyPaginationContext<TItem> BuildPaginationContext(int totalItemCount, int filteredItemCount)
{
int pageCount = !IsPaginationActive || filteredItemCount == 0
? 1
: Math.Max(1, (int)Math.Ceiling(filteredItemCount / (double)PaginationPageSize));
int clampedPage = Math.Clamp(paginationCurrentPage, 1, pageCount);
if (clampedPage != paginationCurrentPage)
{
paginationCurrentPage = clampedPage;
}
int startItemIndex = filteredItemCount == 0 ? 0 : ((clampedPage - 1) * Math.Max(PaginationPageSize, 1)) + 1;
int endItemIndex = filteredItemCount == 0
? 0
: (IsPaginationActive
? Math.Min(filteredItemCount, clampedPage * PaginationPageSize)
: filteredItemCount);
return new FancyPaginationContext<TItem>(
currentPage: clampedPage,
pageSize: PaginationPageSize,
totalItemCount: totalItemCount,
filteredItemCount: filteredItemCount,
pageCount: pageCount,
startItemIndex: startItemIndex,
endItemIndex: endItemIndex,
goToPageAsync: SetCurrentPageAsync,
goToPreviousPageAsync: () => SetCurrentPageAsync(paginationCurrentPage - 1),
goToNextPageAsync: () => SetCurrentPageAsync(paginationCurrentPage + 1),
setPageSizeAsync: SetPageSizeAsync);
}
private FancyTreeTableContext<TItem> BuildTreeContext()
{
TreeNodeStatistics stats = GetTreeNodeStatistics();
return new FancyTreeTableContext<TItem>(
rootItemCount: RootNodes.Count,
visibleNodeCount: BuildVisibleNodes().Count,
expandedNodeCount: stats.ExpandedNodeCount,
hasExpandableNodes: stats.ExpandableNodeCount > 0,
canExpandAny: stats.CollapsedExpandableNodeCount > 0,
canCollapseAny: stats.ExpandedNodeCount > 0,
expandAllAsync: ExpandAllAsync,
collapseAllAsync: CollapseAllAsync);
}
private void SetExpandedStateForAllNodes(bool expanded)
{
foreach (TreeNodeState<TItem> rootNode in RootNodes)
{
SetExpandedStateRecursive(rootNode, expanded);
}
}
private void SetExpandedStateRecursive(TreeNodeState<TItem> node, bool expanded)
{
if (node.HasChildren)
{
node.IsExpanded = expanded;
if (expanded)
{
ExpandedStates[node.Item] = true;
}
else
{
ExpandedStates[node.Item] = false;
}
}
else
{
node.IsExpanded = false;
ExpandedStates[node.Item] = false;
}
foreach (TreeNodeState<TItem> child in node.Children)
{
SetExpandedStateRecursive(child, expanded);
}
}
private void RemoveObsoleteExpandedStates()
{
HashSet<TItem> activeItems = [];
foreach (TreeNodeState<TItem> rootNode in RootNodes)
{
CollectNodeItems(rootNode, activeItems);
}
List<TItem> obsoleteItems = ExpandedStates.Keys.Where(key => !activeItems.Contains(key)).ToList();
foreach (TItem obsoleteItem in obsoleteItems)
{
ExpandedStates.Remove(obsoleteItem);
}
}
private static void CollectNodeItems(TreeNodeState<TItem> node, HashSet<TItem> activeItems)
{
activeItems.Add(node.Item);
foreach (TreeNodeState<TItem> child in node.Children)
{
CollectNodeItems(child, activeItems);
}
}
private TreeNodeStatistics GetTreeNodeStatistics()
{
TreeNodeStatistics stats = new();
foreach (TreeNodeState<TItem> rootNode in RootNodes)
{
CollectTreeNodeStatistics(rootNode, stats);
}
return stats;
}
private static void CollectTreeNodeStatistics(TreeNodeState<TItem> node, TreeNodeStatistics stats)
{
if (node.HasChildren)
{
stats.ExpandableNodeCount++;
if (node.IsExpanded)
{
stats.ExpandedNodeCount++;
}
else
{
stats.CollapsedExpandableNodeCount++;
}
}
foreach (TreeNodeState<TItem> child in node.Children)
{
CollectTreeNodeStatistics(child, stats);
}
}
private IReadOnlyList<TreeNodeState<TItem>> ApplyPagination(
IReadOnlyList<TreeNodeState<TItem>> items,
FancyPaginationContext<TItem> paginationContext)
{
if (!IsPaginationActive)
{
return items;
}
int skip = (paginationContext.CurrentPage - 1) * PaginationPageSize;
return items.Skip(skip).Take(PaginationPageSize).ToList();
}
private void SyncPaginationStateFromParameters()
{
if (!paginationStateInitialized)
{
paginationCurrentPage = Math.Max(1, CurrentPage);
paginationPageSize = PageSize;
paginationStateInitialized = true;
return;
}
if (CurrentPageChanged.HasDelegate)
{
paginationCurrentPage = Math.Max(1, CurrentPage);
}
if (PageSizeChanged.HasDelegate)
{
paginationPageSize = PageSize;
}
}
private async Task SetCurrentPageAsync(int page)
{
int normalizedPage = Math.Max(1, page);
if (paginationCurrentPage == normalizedPage)
{
return;
}
paginationCurrentPage = normalizedPage;
await CurrentPageChanged.InvokeAsync(normalizedPage);
}
private async Task SetPageSizeAsync(int pageSize)
{
int normalizedPageSize = Math.Max(0, pageSize);
if (paginationPageSize == normalizedPageSize)
{
return;
}
paginationPageSize = normalizedPageSize;
paginationCurrentPage = 1;
await PageSizeChanged.InvokeAsync(normalizedPageSize);
await CurrentPageChanged.InvokeAsync(paginationCurrentPage);
}
private async Task OnPageSizeChanged(ChangeEventArgs e)
{
if (int.TryParse(e.Value?.ToString(), out int selectedPageSize))
{
await SetPageSizeAsync(selectedPageSize);
}
}
private bool ShouldRenderPaginationFooter(FancyPaginationContext<TItem> context) =>
IsPaginationActive && (PaginationTemplate is not null || ShowPaginationSummary || context.PageCount > 1);
private string GetDefaultPaginationSummary(FancyPaginationContext<TItem> context)
{
if (context.FilteredItemCount == 0)
{
return context.TotalItemCount == 0
? ResolvedTexts.NoRowsLabel
: FormatResolvedText(ResolvedTexts.NoMatchingRootItemsFormat, context.TotalItemCount);
}
return context.FilteredItemCount == context.TotalItemCount
? FormatResolvedText(ResolvedTexts.ShowingItemsFormat, context.StartItemIndex, context.EndItemIndex, context.FilteredItemCount)
: FormatResolvedText(ResolvedTexts.ShowingVisibleRowsFormat, context.StartItemIndex, context.EndItemIndex, context.FilteredItemCount);
}
private IReadOnlyList<int> GetVisiblePageNumbers(FancyPaginationContext<TItem> context)
{
const int windowSize = 5;
int startPage = Math.Max(1, context.CurrentPage - 2);
int endPage = Math.Min(context.PageCount, startPage + windowSize - 1);
if ((endPage - startPage) < windowSize - 1)
{
startPage = Math.Max(1, endPage - windowSize + 1);
}
return Enumerable.Range(startPage, endPage - startPage + 1).ToList();
}
private string GetTopBarClass() => CombineClasses("fancy-table-topbar d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2", TopBarClass);
private string GetTableClass() => IsColumnLayoutEnabled ? "tree-table fancy-column-layout-enabled" : "tree-table";
private string GetToolbarContainerClass() => CombineClasses("d-flex ms-auto", ToolbarContainerClass);
private string GetPageSizeContainerClass() => CombineClasses("fancy-page-size", PageSizeContainerClass);
private string GetTreeActionsContainerClass() => CombineClasses("fancy-tree-actions", TreeActionsContainerClass);
private string GetPaginationContainerClass() => CombineClasses("fancy-pagination d-flex flex-wrap align-items-center justify-content-between gap-2 mt-3", PaginationContainerClass);
private string GetPaginationSummaryClass() => CombineClasses("fancy-pagination-summary text-muted small", PaginationSummaryClass);
private static string CombineClasses(string baseClass, string? additionalClass) =>
string.IsNullOrWhiteSpace(additionalClass) ? baseClass : $"{baseClass} {additionalClass}";
private static string FormatResolvedText(string format, params object[] args) =>
string.Format(CultureInfo.CurrentCulture, format, args);
private sealed class PagedNodesResult
{
public required IReadOnlyList<TreeNodeState<TItem>> Items { get; init; }
public required FancyPaginationContext<TItem> Context { get; init; }
}
private sealed class TreeNodeStatistics
{
public int ExpandableNodeCount { get; set; }
public int ExpandedNodeCount { get; set; }
public int CollapsedExpandableNodeCount { get; set; }
}
public async ValueTask DisposeAsync()
{
debounceTimer?.Dispose();
if (columnModule is not null)
{
try
{
await columnModule.InvokeVoidAsync("dispose", tableElement);
await columnModule.DisposeAsync();
}
catch (JSDisconnectedException)
{
}
}
dotNetReference?.Dispose();
}
}