-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
HxAutosuggestInternal.razor.cs
507 lines (425 loc) · 13.9 KB
/
HxAutosuggestInternal.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
496
497
498
499
500
501
502
503
504
505
506
507
using System.Threading;
using Havit.Diagnostics.Contracts;
using Microsoft.JSInterop;
namespace Havit.Blazor.Components.Web.Bootstrap.Internal
{
public partial class HxAutosuggestInternal<TItem, TValue> : IAsyncDisposable
{
[Parameter] public TValue Value { get; set; }
[Parameter] public EventCallback<TValue> ValueChanged { get; set; }
[Parameter] public AutosuggestDataProviderDelegate<TItem> DataProvider { get; set; }
/// <summary>
/// Selects value from item.
/// Not required when TValue is same as TItemTime.
/// </summary>
[Parameter] public Func<TItem, TValue> ValueSelector { get; set; }
/// <summary>
/// Selects text to display from item.
/// When not set ToString() is used.
/// </summary>
[Parameter] public Func<TItem, string> TextSelector { get; set; }
/// <summary>
/// Template to display item.
/// </summary>
[Parameter] public RenderFragment<TItem> ItemTemplate { get; set; }
/// <summary>
/// Template to display when items collection is empty
/// </summary>
[Parameter] public RenderFragment EmptyTemplate { get; set; }
/// <summary>
/// Gets item from <see cref="Value"/>.
/// </summary>
[Parameter] public Func<TValue, Task<TItem>> ItemFromValueResolver { get; set; }
/// <summary>
/// Minimal number of characters to start suggesting. Default is <c>2</c>.
/// </summary>
[Parameter] public int MinimumLengthEffective { get; set; } = 2;
/// <summary>
/// Short hint displayed in the input field before the user enters a value.
/// </summary>
[Parameter] public string Placeholder { get; set; }
/// <summary>
/// Debounce delay in miliseconds. Default is <c>300 ms</c>.
/// </summary>
[Parameter] public int DelayEffective { get; set; } = 300;
[Parameter] public string InputCssClass { get; set; }
[Parameter] public string InputId { get; set; }
[Parameter] public IconBase SearchIconEffective { get; set; }
[Parameter] public IconBase ClearIconEffective { get; set; }
[Parameter] public bool EnabledEffective { get; set; } = true;
[Parameter] public LabelType LabelTypeEffective { get; set; }
[Parameter] public IFormValueComponent FormValueComponent { get; set; }
/// <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>
/// Custom CSS class to render with input-group span.
/// </summary>
[Parameter] public string InputGroupCssClass { get; set; }
/// <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.
/// </summary>
[Parameter] public string InputGroupEndText { get; set; }
/// <summary>
/// Input-group at the end of the input.
/// </summary>
[Parameter] public RenderFragment InputGroupEndTemplate { get; set; }
/// <summary>
/// If true, the first suggestion is highlighted until another is chosen by the user.
/// </summary>
[Parameter] public bool HighlightFirstSuggestionEffective { get; set; }
/// <summary>
/// Additional attributes to be splatted onto an underlying HTML element.
/// </summary>
[Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object> AdditionalAttributes { get; set; }
[Inject] protected IJSRuntime JSRuntime { get; set; }
protected bool HasInputGroupsEffective => !String.IsNullOrWhiteSpace(InputGroupStartText) || !String.IsNullOrWhiteSpace(InputGroupEndText) || (InputGroupStartTemplate is not null) || (InputGroupEndTemplate is not null);
protected bool HasAnyInputGroupEnd => !String.IsNullOrWhiteSpace(InputGroupEndText) || (InputGroupEndTemplate is not null);
private string dropdownId = "hx" + Guid.NewGuid().ToString("N");
private System.Timers.Timer timer;
private string userInput = String.Empty;
private CancellationTokenSource cancellationTokenSource;
private List<TItem> suggestions;
private bool userInputModified;
private bool isDropdownOpened = false;
private bool blurInProgress;
private bool currentlyFocused;
private bool disposed;
private IJSObjectReference jsModule;
private HxAutosuggestInput autosuggestInput;
private TValue lastKnownValue;
private bool dataProviderInProgress;
private DotNetObjectReference<HxAutosuggestInternal<TItem, TValue>> dotnetObjectReference;
internal string ChipValue => userInput;
public HxAutosuggestInternal()
{
dotnetObjectReference = DotNetObjectReference.Create(this);
}
private async Task SetValueItemWithEventCallback(TItem selectedItem)
{
TValue value = SelectorHelpers.GetValue<TItem, TValue>(ValueSelector, selectedItem);
if (!EqualityComparer<TValue>.Default.Equals(Value, value))
{
Value = value;
lastKnownValue = Value;
await ValueChanged.InvokeAsync(Value);
}
}
protected override async Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
Contract.Requires<InvalidOperationException>(DataProvider != null, $"{GetType()} requires a {nameof(DataProvider)} parameter.");
if (!EqualityComparer<TValue>.Default.Equals(Value, default))
{
// we do not want to re-resolve the Text (userInput) if the Value did not change
if (!EqualityComparer<TValue>.Default.Equals(Value, lastKnownValue))
{
if ((ItemFromValueResolver == null) && (typeof(TValue) == typeof(TItem)))
{
userInput = TextSelectorEffective((TItem)(object)Value);
}
else
{
Contract.Requires<InvalidOperationException>(ItemFromValueResolver is not null, $"{GetType()} requires a {nameof(ItemFromValueResolver)} parameter.");
userInput = TextSelectorEffective(await ItemFromValueResolver(Value));
}
}
}
else
{
userInput = TextSelectorEffective(default);
}
userInputModified = false;
lastKnownValue = Value;
}
public async ValueTask FocusAsync()
{
await autosuggestInput.FocusAsync();
}
private async Task HandleInputInput(string newUserInput)
{
Contract.Requires<InvalidOperationException>(EnabledEffective, $"The {GetType().Name} component is in a disabled state.");
// user changes an input
userInput = newUserInput;
userInputModified = true;
timer?.Stop(); // if waiting for an interval, stop it
cancellationTokenSource?.Cancel(); // if already loading data, cancel it
dataProviderInProgress = false; // data provider is no more in progress
// start new time interval
if (userInput.Length >= MinimumLengthEffective)
{
if (DelayEffective == 0)
{
await UpdateSuggestionsAsync();
}
else
{
if (timer == null)
{
timer = new System.Timers.Timer();
timer.AutoReset = false; // just once
timer.Elapsed += HandleTimerElapsed;
}
timer.Interval = DelayEffective;
timer.Start();
}
}
else
{
// or close a dropdown
suggestions = null;
await DestroyDropdownAsync();
}
}
private async void HandleTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// when a time interval reached, update suggestions
await InvokeAsync(async () =>
{
await UpdateSuggestionsAsync();
});
}
private async Task HandleInputFocus()
{
if (!EnabledEffective)
{
return;
}
// when an input gets focus, close a dropdown
currentlyFocused = true;
if (string.IsNullOrEmpty(userInput) && MinimumLengthEffective <= 0)
{
await UpdateSuggestionsAsync();
return;
}
}
// Due to HTML update and Bootstrap Dropdown collision we are not allowed to re-render HTML in InputBlur!
private void HandleInputBlur()
{
if (!EnabledEffective)
{
return;
}
currentlyFocused = false;
// when user clicks back button in browser this method can be called after it is disposed!
blurInProgress = true;
timer?.Stop(); // if waiting for an interval, stop it
cancellationTokenSource?.Cancel(); // if waiting for an interval, stop it
dataProviderInProgress = false; // data provider is no more in progress
}
private async Task UpdateSuggestionsAsync()
{
// Cancelation is performed in HandleInputInput method
cancellationTokenSource?.Dispose();
cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
dataProviderInProgress = true;
StateHasChanged();
AutosuggestDataProviderRequest request = new AutosuggestDataProviderRequest
{
UserInput = userInput,
CancellationToken = cancellationToken
};
AutosuggestDataProviderResult<TItem> result;
try
{
result = await DataProvider.Invoke(request);
}
catch (OperationCanceledException) // gRPC stack does not set the operationFailedException.CancellationToken, do not check in when-clause
{
return;
}
if (cancellationToken.IsCancellationRequested)
{
return;
}
dataProviderInProgress = false;
// KeyboardNavigation
if (HighlightFirstSuggestionEffective)
{
focusedItemIndex = 0; // First item in the searchResults collection.
}
else
{
focusedItemIndex = InputKeyboardNavigationIndex;
}
suggestions = result.Data?.ToList();
if ((suggestions?.Any() ?? false) || EmptyTemplate != null)
{
await OpenDropdownAsync();
}
else
{
await DestroyDropdownAsync();
}
StateHasChanged();
}
#region KeyboardNavigation
private int focusedItemIndex = -1;
private const string ArrowUpKeyCode = "ArrowUp";
private const string ArrowDownKeyCode = "ArrowDown";
private const string EnterKeyCode = "Enter";
private const string NumpadEnterKeyCode = "NumpadEnter";
/// <summary>
/// Input's index for the keyboard navigation. If this is the current index, then no item is selected.
/// </summary>
private const int InputKeyboardNavigationIndex = -1;
private TItem GetFocusedItem()
{
if (focusedItemIndex > InputKeyboardNavigationIndex)
{
TItem focusedItem = GetItemByIndex(focusedItemIndex);
if ((focusedItem is not null) && (!focusedItem.Equals(default)))
{
return focusedItem;
}
}
return default;
}
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 DestroyDropdownAsync();
await HandleItemSelected(focusedItem);
}
}
// Move focus up or down.
if (keyboardEventArgs.Code == ArrowUpKeyCode)
{
int previousItemIndex = focusedItemIndex - 1;
if (previousItemIndex >= InputKeyboardNavigationIndex) // If the index equals InputKeyboardNavigationIndex, no item is focused.
{
focusedItemIndex = previousItemIndex;
}
}
else if (keyboardEventArgs.Code == ArrowDownKeyCode)
{
int nextItemIndex = focusedItemIndex + 1;
if (nextItemIndex < suggestions.Count)
{
focusedItemIndex = nextItemIndex;
}
}
}
private TItem GetItemByIndex(int index)
{
if (index >= 0 && index < suggestions?.Count)
{
return suggestions[index];
}
else
{
return default;
}
}
#endregion KeyboardNavigation
private async Task HandleItemSelected(TItem item)
{
// user selected an item in the "dropdown".
await SetValueItemWithEventCallback(item);
userInput = TextSelectorEffective(item);
userInputModified = false;
}
private async Task HandleCrossClick()
{
// user clicked on a cross button (x)
await SetValueItemWithEventCallback(default);
userInput = TextSelectorEffective(default);
userInputModified = false;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (blurInProgress)
{
blurInProgress = false;
if (userInputModified && !isDropdownOpened)
{
await SetValueItemWithEventCallback(default);
userInput = TextSelectorEffective(default);
userInputModified = false;
StateHasChanged();
}
}
}
#region OpenDropdownAsync, DestroyDropdownAsync, EnsureJsModuleAsync
private async Task OpenDropdownAsync()
{
if (!isDropdownOpened)
{
await EnsureJsModuleAsync();
if (disposed)
{
return;
}
await jsModule.InvokeVoidAsync("open", autosuggestInput.InputElement, dotnetObjectReference);
isDropdownOpened = true;
}
}
private async Task DestroyDropdownAsync()
{
if (isDropdownOpened)
{
await EnsureJsModuleAsync();
await jsModule.InvokeVoidAsync("destroy", autosuggestInput.InputElement);
isDropdownOpened = false;
}
}
private async Task EnsureJsModuleAsync()
{
jsModule ??= await JSRuntime.ImportHavitBlazorBootstrapModuleAsync(nameof(HxAutosuggest));
}
[JSInvokable("HxAutosuggestInternal_HandleDropdownHidden")]
public async Task HandleDropdownHidden()
{
if (userInputModified && !currentlyFocused)
{
await SetValueItemWithEventCallback(default);
userInput = TextSelectorEffective(default);
userInputModified = false;
StateHasChanged();
}
await DestroyDropdownAsync();
}
#endregion
private string TextSelectorEffective(TItem item)
{
return (item == null)
? String.Empty
: SelectorHelpers.GetText(TextSelector, item);
}
public async ValueTask DisposeAsync()
{
await DisposeAsyncCore();
//Dispose(disposing: false);
}
protected virtual async ValueTask DisposeAsyncCore()
{
disposed = true;
timer?.Dispose();
timer = null;
cancellationTokenSource?.Dispose();
cancellationTokenSource = null;
if (jsModule != null)
{
await jsModule.DisposeAsync();
}
dotnetObjectReference?.Dispose();
}
}
}