/
HxSearchBox.razor.cs
495 lines (418 loc) · 14.8 KB
/
HxSearchBox.razor.cs
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
using System.Threading;
using Havit.Blazor.Components.Web.Bootstrap.Internal;
using Microsoft.JSInterop;
namespace Havit.Blazor.Components.Web.Bootstrap;
/// <summary>
/// A search input component witch automatic suggestions, initial dropdown template and free-text queries support.<br />
/// Full documentation and demos: <see href="https://havit.blazor.eu/components/HxSearchBox">https://havit.blazor.eu/components/HxSearchBox</see>
/// </summary>
/// <typeparam name="TItem"></typeparam>
public partial class HxSearchBox<TItem> : IAsyncDisposable
{
protected const string ArrowUpKeyCode = "ArrowUp";
protected const string ArrowDownKeyCode = "ArrowDown";
protected const string EnterKeyCode = "Enter";
protected const string NumpadEnterKeyCode = "NumpadEnter";
/// <summary>
/// Returns application-wide defaults for the component.
/// Enables overriding defaults in descandants (use separate set of defaults).
/// </summary>
protected virtual SearchBoxSettings GetDefaults() => HxSearchBox.Defaults;
/// <summary>
/// Set of settings to be applied to the component instance (overrides <see cref="HxSearchBox.Defaults"/>, overriden by individual parameters).
/// </summary>
[Parameter] public SearchBoxSettings Settings { get; set; }
/// <summary>
/// Returns optional set of component settings.
/// </summary>
/// <remarks>
/// Similar to <see cref="GetDefaults"/>, enables defining wider <see cref="Settings"/> in components descandants (by returning a derived settings class).
/// </remarks>
protected virtual SearchBoxSettings GetSettings() => this.Settings;
/// <summary>
/// Method (delegate) which provides data of the suggestions.
/// </summary>
[Parameter] public SearchBoxDataProviderDelegate<TItem> DataProvider { get; set; }
/// <summary>
/// Allows you to disable the input. Default is <c>true</c>.
/// </summary>
[Parameter] public bool Enabled { get; set; } = true;
/// <summary>
/// Text written by the user (input text).
/// </summary>
[Parameter]
public string TextQuery { get; set; }
[Parameter] public EventCallback<string> TextQueryChanged { get; set; }
/// <summary>
/// Triggers the <see cref="TextQueryChanged"/> event. Allows interception of the event in derived components.
/// </summary>
protected virtual Task InvokeTextQueryChangedAsync(string newTextQueryValue) => TextQueryChanged.InvokeAsync(newTextQueryValue);
/// <summary>
/// Raised, when the enter key is pressed or when the text-query item is selected in the dropdown menu.
/// (Does not trigger when <see cref="AllowTextQuery"/> is <c>false</c>.)
/// </summary>
[Parameter] public EventCallback<string> OnTextQueryTriggered { get; set; }
/// <summary>
/// Triggers the <see cref="OnTextQueryTriggered"/> event. Allows interception of the event in derived components.
/// </summary>
protected virtual Task InvokeOnTextQueryTriggeredAsync(string textQuery) => OnTextQueryTriggered.InvokeAsync(textQuery);
/// <summary>
/// Occurs, when any of suggested items (other than plain text-query) is selected.
/// </summary>
[Parameter] public EventCallback<TItem> OnItemSelected { get; set; }
/// <summary>
/// Triggers the <see cref="OnItemSelected"/> event. Allows interception of the event in derived components.
/// </summary>
protected virtual Task InvokeOnItemSelectedAsync(TItem selectedItem) => OnItemSelected.InvokeAsync(selectedItem);
/// <summary>
/// Placeholder text for the search input.
/// </summary>
[Parameter] public string Placeholder { get; set; }
/// <summary>
/// Selector to display item title from data item.
/// </summary>
[Parameter] public Func<TItem, string> ItemTitleSelector { get; set; }
/// <summary>
/// Selector to display item subtitle from data item.
/// </summary>
[Parameter] public Func<TItem, string> ItemSubtitleSelector { get; set; }
/// <summary>
/// Selector to display icon from data item.
/// </summary>
[Parameter] public Func<TItem, IconBase> ItemIconSelector { get; set; }
/// <summary>
/// Template for the item content.
/// </summary>
[Parameter] public RenderFragment<TItem> ItemTemplate { get; set; }
/// <summary>
/// Template for the text-query item content (requires <c><see cref="AllowTextQuery"/>="true"</c>).
/// </summary>
[Parameter] public RenderFragment<string> TextQueryItemTemplate { get; set; }
/// <summary>
/// Rendered when the <see cref="DataProvider" /> doesn't return any data.
/// </summary>
[Parameter] public RenderFragment NotFoundTemplate { get; set; }
/// <summary>
/// Rendered when no input is entered (i.e. initial state).
/// </summary>
[Parameter] public RenderFragment DefaultContentTemplate { get; set; }
/// <summary>
/// Additional css classes for the dropdown.
/// </summary>
[Parameter] public string CssClass { get; set; }
protected string CssClassEffective => this.CssClass ?? this.GetSettings()?.CssClass ?? GetDefaults().CssClass;
/// <summary>
/// Additional CSS classes for the items in the dropdown menu.
/// </summary>
[Parameter] public string ItemCssClass { get; set; }
protected string ItemCssClassEffective => this.ItemCssClass ?? this.GetSettings()?.ItemCssClass ?? GetDefaults().ItemCssClass;
/// <summary>
/// Additional CSS classes for the search box input.
/// </summary>
[Parameter] public string InputCssClass { get; set; }
protected string InputCssClassEffective => this.ItemCssClass ?? this.GetSettings()?.InputCssClass ?? GetDefaults().InputCssClass;
/// <summary>
/// Icon of the input, when no text is written.
/// </summary>
[Parameter] public IconBase SearchIcon { get; set; }
protected IconBase SearchIconEffective => this.SearchIcon ?? this.GetSettings()?.SearchIcon ?? GetDefaults().SearchIcon;
/// <summary>
/// Icon of the input, when text is written allowing the user to clear the text.
/// </summary>
[Parameter] public IconBase ClearIcon { get; set; }
protected IconBase ClearIconEffective => this.ClearIcon ?? this.GetSettings()?.ClearIcon ?? GetDefaults().ClearIcon;
/// <summary>
/// Offset between the dropdown and the input.
/// <see href="https://popper.js.org/docs/v2/modifiers/offset/#options"/>
/// </summary>
[Parameter] public (int Skidding, int Distance) DropdownOffset { get; set; } = (0, 4);
/// <summary>
/// Label of the input field.
/// </summary>
[Parameter] public string Label { get; set; }
/// <summary>
/// Label type of the input field.
/// </summary>
[Parameter] public LabelType LabelType { get; set; }
/// <summary>
/// Input size of the input field.
/// </summary>
[Parameter] public InputSize? InputSize { get; set; }
protected InputSize InputSizeEffective => this.InputSize ?? this.GetSettings()?.InputSize ?? this.GetDefaults()?.InputSize ?? throw new InvalidOperationException(nameof(InputSize) + " default for " + nameof(HxSearchBox) + " has to be set.");
/// <summary>
/// Minimum lenght to call the data provider (display any results). Default is <c>2</c>.
/// </summary>
[Parameter] public int? MinimumLength { get; set; }
protected int MinimumLengthEffective => this.MinimumLength ?? this.GetSettings()?.MinimumLength ?? GetDefaults().MinimumLength ?? throw new InvalidOperationException(nameof(MinimumLength) + " default for " + nameof(HxSearchBox) + " has to be set.");
/// <summary>
/// Debounce delay in miliseconds. Default is <c>300</c> ms.
/// </summary>
[Parameter] public int? Delay { get; set; }
protected int DelayEffective => this.Delay ?? this.GetSettings()?.Delay ?? GetDefaults().Delay ?? throw new InvalidOperationException(nameof(Delay) + " default for " + nameof(HxSearchBox) + " has to be set.");
/// <summary>
/// Indicates whether text-query mode is enabled (accepts free text in addition to suggested items).
/// </summary>
[Parameter] public bool AllowTextQuery { get; set; } = true;
/// <summary>
/// Input-group at the beginning of the input.
/// </summary>
[Parameter] public string InputGroupStartText { get; set; }
/// <summary>
/// Input-group at the beginning of the input.
/// </summary>
[Parameter] public RenderFragment InputGroupStartTemplate { get; set; }
/// <summary>
/// Input-group at the end of the input.<br/>
/// Hides the search icon when used!
/// </summary>
[Parameter] public string InputGroupEndText { get; set; }
/// <summary>
/// Input-group at the end of the input.<br/>
/// Hides the search icon when used!
/// </summary>
[Parameter] public RenderFragment InputGroupEndTemplate { get; set; }
private string dropdownToggleElementId = "hx" + Guid.NewGuid().ToString("N");
private string dropdownId = "hx" + Guid.NewGuid().ToString("N");
private List<TItem> searchResults = new();
private int focusedItemIndex = -1;
private HxDropdownToggleElement dropdownToggle;
private bool dropdownMenuActive = false;
private bool initialized = false;
/// <summary>
/// Shows whether the <see cref="TextQuery"/> has been below minimum required length recently (before data provider loading is completed).
/// </summary>
private bool textQueryHasBeenBelowMinimumLength = true;
private System.Timers.Timer timer;
private CancellationTokenSource cancellationTokenSource;
private bool dataProviderInProgress;
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
initialized = true;
}
}
protected async Task ClearInputAsync()
{
if (TextQuery != string.Empty)
{
TextQuery = string.Empty;
await HandleTextQueryValueChanged(string.Empty);
await HandleTextQueryTriggered();
}
}
protected async Task UpdateSuggestionsAsync()
{
await HideDropdownMenu();
if (string.IsNullOrEmpty(TextQuery) || TextQuery.Length < MinimumLengthEffective)
{
return;
}
// Cancelation is performed in HandleTextQueryValueChanged method
cancellationTokenSource?.Dispose();
cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
dataProviderInProgress = true;
StateHasChanged();
SearchBoxDataProviderRequest request = new()
{
UserInput = TextQuery,
CancellationToken = cancellationToken
};
SearchBoxDataProviderResult<TItem> result = null;
try
{
result = await DataProvider.Invoke(request);
}
catch (OperationCanceledException)
{
return;
}
if (cancellationToken.IsCancellationRequested)
{
return;
}
dataProviderInProgress = false;
focusedItemIndex = default;
searchResults = result?.Data.ToList();
textQueryHasBeenBelowMinimumLength = false;
await ShowDropdownMenu();
StateHasChanged();
}
protected bool HasItemFocus(TItem item)
{
TItem focusedItem = GetItemByIndex(focusedItemIndex);
if ((focusedItem is not null) && (!focusedItem.Equals(default)))
{
return item.Equals(focusedItem);
}
else
{
return false;
}
}
protected bool HasFreeTextItemFocus()
{
return focusedItemIndex == GetFreeTextItemIndex();
}
protected async Task HandleTextQueryValueChanged(string newTextQuery)
{
this.TextQuery = newTextQuery;
CancelDataProviderAndDebounce();
// start new time interval
if (TextQuery.Length >= MinimumLengthEffective)
{
if (timer == null)
{
timer = new System.Timers.Timer
{
AutoReset = false // just once
};
timer.Elapsed += HandleTimerElapsed;
}
timer.Interval = DelayEffective;
timer.Start();
}
else
{
textQueryHasBeenBelowMinimumLength = true;
}
if (ShouldDropdownMenuBeDisplayed())
{
await ShowDropdownMenu();
}
else if (dropdownMenuActive)
{
await HideDropdownMenu();
}
await InvokeTextQueryChangedAsync(newTextQuery);
}
private async Task UpdateFocusedItem(KeyboardEventArgs keyboardEventArgs)
{
// Confirm selection on the focused item if an item is focused and the enter key is pressed.
TItem focusedItem = GetItemByIndex(focusedItemIndex);
if (keyboardEventArgs.Code == EnterKeyCode || keyboardEventArgs.Code == NumpadEnterKeyCode)
{
if ((focusedItem is not null) && (!focusedItem.Equals(default)))
{
await HandleItemSelected(focusedItem);
}
else if (focusedItemIndex == GetFreeTextItemIndex())
{
await HandleTextQueryTriggered();
}
}
// Move focus up or down.
if (keyboardEventArgs.Code == ArrowUpKeyCode)
{
int previousItemIndex = focusedItemIndex - 1;
if (previousItemIndex >= -1) // If the index is -1, no item is focused.
{
focusedItemIndex = previousItemIndex;
}
}
else if (keyboardEventArgs.Code == ArrowDownKeyCode)
{
int nextItemIndex = focusedItemIndex + 1;
if (nextItemIndex < searchResults.Count)
{
focusedItemIndex = nextItemIndex;
}
else
{
focusedItemIndex = GetFreeTextItemIndex(); // Select the item that's used to confirm the freetext.
}
}
}
private TItem GetItemByIndex(int index)
{
if (index >= 0 && index < searchResults.Count)
{
return searchResults[index];
}
else
{
return default;
}
}
protected int GetFreeTextItemIndex()
{
return searchResults.Count;
}
private async void HandleTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// when a time interval reached, update suggestions
await InvokeAsync(async () =>
{
await UpdateSuggestionsAsync();
});
}
private void HandleInputBlur()
{
CancelDataProviderAndDebounce();
}
private void CancelDataProviderAndDebounce()
{
timer?.Stop(); // if waiting for an interval, stop it
cancellationTokenSource?.Cancel(); // if waiting for an interval, stop it
dataProviderInProgress = false; // data provider is no longer in progress
}
protected async Task HandleTextQueryTriggered()
{
if (AllowTextQuery && (TextQuery.Length >= MinimumLengthEffective || TextQuery.Length == 0))
{
CancelDataProviderAndDebounce();
await HideDropdownMenu();
await InvokeOnTextQueryTriggeredAsync(this.TextQuery);
}
}
protected async Task HandleItemSelected(TItem item)
{
await InvokeOnItemSelectedAsync(item);
await ClearInputAsync();
}
protected async Task OnDropdownMenuShown()
{
dropdownMenuActive = true;
if (!ShouldDropdownMenuBeDisplayed())
{
await HideDropdownMenu();
}
}
protected async Task ShowDropdownMenu()
{
await dropdownToggle.ShowAsync();
}
protected async Task HideDropdownMenu()
{
await dropdownToggle.HideAsync();
}
/// <summary>
/// If the <see cref="DefaultContentTemplate"/> is empty, we don't want to display anything when nothing (or below the minimum amount of characters) is typed into the input.
/// </summary>
/// <returns></returns>
protected bool ShouldDropdownMenuBeDisplayed()
{
if (textQueryHasBeenBelowMinimumLength && (TextQuery is not null && TextQuery.Length >= MinimumLengthEffective))
{
return false;
}
if (DefaultContentTemplate is null && (TextQuery is null || TextQuery.Length < MinimumLengthEffective))
{
return false;
}
return true;
}
public async ValueTask DisposeAsync()
{
await DisposeAsyncCore();
}
protected virtual async ValueTask DisposeAsyncCore()
{
timer?.Dispose();
timer = null;
cancellationTokenSource?.Dispose();
cancellationTokenSource = null;
await dropdownToggle.DisposeAsync();
}
}