-
Notifications
You must be signed in to change notification settings - Fork 377
/
FluentInputBase.cs
479 lines (408 loc) · 17.5 KB
/
FluentInputBase.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
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.FluentUI.AspNetCore.Components.Utilities;
namespace Microsoft.FluentUI.AspNetCore.Components;
/// <summary>
/// A base class for fluent ui form input components. This base class automatically
/// integrates with an <see cref="Microsoft.AspNetCore.Components.Forms.EditContext"/>, which must be supplied
/// as a cascading parameter.
/// </summary>
public abstract partial class FluentInputBase<TValue> : FluentComponentBase, IDisposable
{
internal readonly string UnknownBoundField = "(unknown)";
private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
private bool _hasInitializedParameters;
private bool _parsingFailed;
private string? _incomingValueBeforeParsing;
private bool _previousParsingAttemptFailed;
private ValidationMessageStore? _parsingValidationMessages;
private Type? _nullableUnderlyingType;
[CascadingParameter]
private EditContext? CascadedEditContext { get; set; }
/// <summary>
/// When true, the control will be immutable by user interaction. <see href="https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly">readonly</see> HTML attribute for more information.
/// </summary>
[Parameter]
public bool ReadOnly { get; set; }
/// <summary>
/// Disables the form control, ensuring it doesn't participate in form submission.
/// </summary>
[Parameter]
public bool Disabled { get; set; }
/// <summary>
/// Gets or sets the name of the element.
/// Allows access by name from the associated form.
/// ⚠️ This value needs to be set manually for SSR scenarios to work correctly.
/// </summary>
[Parameter]
public string? Name { get; set; }
/// <summary>
/// Gets or sets the text to label the input.
/// This is usually displayed just above the input
/// </summary>
[Parameter]
public string? Label { get; set; }
/// <summary>
/// Gets or sets the content to label the input component.
/// This is usually displayed just above the input
/// </summary>
[Parameter]
public RenderFragment? LabelTemplate { get; set; }
/// <summary>
/// Gets or sets the text used on aria-label attribute.
/// </summary>
[Parameter]
public virtual string? AriaLabel { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the element needs to have a value.
/// </summary>
[Parameter]
public bool Required { get; set; }
/// <summary>
/// Gets or sets the value of the input. This should be used with two-way binding.
/// </summary>
/// <example>
/// @bind-Value="model.PropertyName"
/// </example>
[Parameter]
public virtual TValue? Value { get; set; }
/// <summary>
/// Gets or sets a callback that updates the bound value.
/// </summary>
[Parameter]
public EventCallback<TValue> ValueChanged { get; set; }
/// <summary>
/// Gets or sets an expression that identifies the bound value.
/// </summary>
[Parameter]
public Expression<Func<TValue>>? ValueExpression { get; set; }
/// <summary>
/// Gets or sets the display name for this field.
/// <para>This value is used when generating error messages when the input value fails to parse correctly.</para>
/// </summary>
[Parameter]
public string? DisplayName { get; set; }
/// <summary>
/// Determines if the element should receive document focus on page load.
/// </summary>
[Parameter]
public virtual bool Autofocus { get; set; } = false;
/// <summary>
/// Gets or sets the short hint displayed in the input before the user enters a value.
/// </summary>
[Parameter]
public virtual string? Placeholder { get; set; }
/// <summary>
/// Gets or sets if the derived component is embedded in another component.
/// If true, the ClassValue property will not include the EditContext's FieldCssClass.
/// </summary>
[Parameter]
public virtual bool Embedded { get; set; } = false;
/// <summary>
/// Gets the associated <see cref="Microsoft.AspNetCore.Components.Forms.EditContext"/>.
/// This property is uninitialized if the input does not have a parent <see cref="EditForm"/>.
/// </summary>
protected EditContext EditContext { get; set; } = default!;
/// <summary>
/// Gets the <see cref="FieldIdentifier"/> for the bound value.
/// </summary>
protected internal FieldIdentifier FieldIdentifier { get; set; }
internal bool FieldBound => ValueExpression != null || ValueChanged.HasDelegate;
protected async Task SetCurrentValueAsync(TValue? value)
{
var hasChanged = !EqualityComparer<TValue>.Default.Equals(value, Value);
if (!hasChanged)
{
return;
}
_parsingFailed = false;
// If we don't do this, then when the user edits from A to B, we'd:
// - Do a render that changes back to A
// - Then send the updated value to the parent, which sends the B back to this component
// - Do another render that changes it to B again
// The unnecessary reversion from B to A can cause selection to be lost while typing
// A better solution would be somehow forcing the parent component's render to occur first,
// but that would involve a complex change in the renderer to keep the render queue sorted
// by component depth or similar.
Value = value;
if (ValueChanged.HasDelegate)
{
await ValueChanged.InvokeAsync(value);
}
if (FieldBound)
{
EditContext?.NotifyFieldChanged(FieldIdentifier);
}
}
/// <summary>
/// Gets or sets the current value of the input.
/// </summary>
protected TValue? CurrentValue
{
get => Value;
set => _ = SetCurrentValueAsync(value);
}
/// <summary>
/// Gets or sets the current value of the input, represented as a string.
/// </summary>
protected string? CurrentValueAsString
{
// InputBase-derived components can hold invalid states (e.g., an InputNumber being blank even when bound
// to an int value). So, if parsing fails, we keep the rejected string in the UI even though it doesn't
// match what's on the .NET model. This avoids interfering with typing, but still notifies the EditContext
// about the validation error message.
get => _parsingFailed ? _incomingValueBeforeParsing : FormatValueAsString(CurrentValue);
set => _ = SetCurrentValueAsStringAsync(value);
}
/// <summary>
/// Attempts to set the current value of the input, represented as a string.
/// </summary>
/// <param name="value"></param>
protected async Task SetCurrentValueAsStringAsync(string? value)
{
_incomingValueBeforeParsing = value;
_parsingValidationMessages?.Clear();
if (_nullableUnderlyingType != null && string.IsNullOrEmpty(value))
{
// Assume if it's a nullable type, null/empty inputs should correspond to default(T)
// Then all subclasses get nullable support almost automatically (they just have to
// not reject Nullable<T> based on the type itself).
_parsingFailed = false;
CurrentValue = default!;
}
else if (TryParseValueFromString(value, out TValue? parsedValue, out var validationErrorMessage))
{
_parsingFailed = false;
await SetCurrentValueAsync(parsedValue);
}
else
{
_parsingFailed = true;
// EditContext may be null if the input is not a child component of EditForm.
if (EditContext is not null && FieldBound)
{
_parsingValidationMessages ??= new ValidationMessageStore(EditContext);
_parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage);
// Since we're not writing to CurrentValue, we'll need to notify about modification from here
EditContext.NotifyFieldChanged(FieldIdentifier);
}
}
// We can skip the validation notification if we were previously valid and still are
if (_parsingFailed || _previousParsingAttemptFailed)
{
EditContext?.NotifyValidationStateChanged();
_previousParsingAttemptFailed = _parsingFailed;
}
}
/// <summary>
/// Constructs an instance of <see cref="InputBase{TValue}"/>.
/// </summary>
protected FluentInputBase()
{
Id = Identifier.NewId();
_validationStateChangedHandler = OnValidateStateChanged;
}
/// <summary>
/// Formats the value as a string. Derived classes can override this to determine the formating used for <see cref="CurrentValueAsString"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <returns>A string representation of the value.</returns>
protected virtual string? FormatValueAsString(TValue? value)
=> value?.ToString();
/// <summary>
/// Parses a string to create an instance of <typeparamref name="TValue"/>. Derived classes can override this to change how
/// <see cref="CurrentValueAsString"/> interprets incoming values.
/// </summary>
/// <param name="value">The string value to be parsed.</param>
/// <param name="result">An instance of <typeparamref name="TValue"/>.</param>
/// <param name="validationErrorMessage">If the value could not be parsed, provides a validation error message.</param>
/// <returns>True if the value could be parsed; otherwise false.</returns>
protected abstract bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage);
/// <summary>
/// Gets a CSS class string that combines the <c>class</c> attribute and and a string indicating
/// the status of the field being edited (a combination of "modified", "valid", and "invalid").
/// Derived components should typically use this value for the primary HTML element class attribute.
/// </summary>
protected virtual string? ClassValue
{
get
{
var fieldClass = (FieldBound && !Embedded) ? EditContext?.FieldCssClass(FieldIdentifier) : null;
var cssClass = CombineClassNames(AdditionalAttributes, fieldClass);
if (!string.IsNullOrEmpty(cssClass) || !string.IsNullOrEmpty(Class))
{
return new CssBuilder(Class)
.AddClass(cssClass)
.Build();
}
return null;
}
}
/// <summary />
protected virtual string? StyleValue => new StyleBuilder(Style).Build();
/// <inheritdoc />
public override Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (!_hasInitializedParameters)
{
// This is the first run
// Could put this logic in OnInit, but its nice to avoid forcing people who override OnInit to call base.OnInit()
if (ValueExpression is not null)
{
FieldIdentifier = FieldIdentifier.Create(ValueExpression);
}
else if (ValueChanged.HasDelegate)
{
FieldIdentifier = FieldIdentifier.Create(() => Value);
}
if (CascadedEditContext != null)
{
EditContext = CascadedEditContext;
EditContext.OnValidationStateChanged += _validationStateChangedHandler;
}
_nullableUnderlyingType = Nullable.GetUnderlyingType(typeof(TValue));
_hasInitializedParameters = true;
}
else if (CascadedEditContext != EditContext)
{
// Not the first run
// We don't support changing EditContext because it's messy to be clearing up state and event
// handlers for the previous one, and there's no strong use case. If a strong use case
// emerges, we can consider changing this.
throw new InvalidOperationException($"{GetType()} does not support changing the " +
$"{nameof(Microsoft.AspNetCore.Components.Forms.EditContext)} dynamically.");
}
UpdateAdditionalValidationAttributes();
// For derived components, retain the usual lifecycle with OnInit/OnParametersSet/etc.
return base.SetParametersAsync(ParameterView.Empty);
}
// TODO: #vNext: Make it proper async Task
/// <summary>
/// Exposes the elements FocusAsync() method.
/// </summary>
[SuppressMessage("Style", "VSTHRD200:Use `Async` suffix for async methods", Justification = "#vNext: To update in the next version")]
public async void FocusAsync()
{
await Element!.FocusAsync();
}
// TODO: #vNext: Make it proper async Task
/// <summary>
/// Exposes the elements FocusAsync(bool preventScroll) method.
/// </summary>
/// <param name="preventScroll">A Boolean value indicating whether or not the browser should scroll
/// the document to bring the newly-focused element into view. A value of false for preventScroll (the default)
/// means that the browser will scroll the element into view after focusing it.
/// If preventScroll is set to true, no scrolling will occur.</param>
[SuppressMessage("Style", "VSTHRD200:Use `Async` suffix for async methods", Justification = "#vNext: To update in the next version")]
public async void FocusAsync(bool preventScroll)
{
await Element!.FocusAsync(preventScroll);
}
private void OnValidateStateChanged(object? sender, ValidationStateChangedEventArgs eventArgs)
{
UpdateAdditionalValidationAttributes();
StateHasChanged();
}
private void UpdateAdditionalValidationAttributes()
{
if (EditContext is null)
{
return;
}
var hasAriaInvalidAttribute = AdditionalAttributes != null && AdditionalAttributes.ContainsKey("aria-invalid");
if (FieldBound && EditContext.GetValidationMessages(FieldIdentifier).Any())
{
if (hasAriaInvalidAttribute)
{
// Do not overwrite the attribute value
return;
}
if (ConvertToDictionary(AdditionalAttributes, out var additionalAttributes))
{
AdditionalAttributes = additionalAttributes;
}
// To make the `Input` components accessible by default
// we will automatically render the `aria-invalid` attribute when the validation fails
// value must be "true" see https://www.w3.org/TR/wai-aria-1.1/#aria-invalid
additionalAttributes["aria-invalid"] = "true";
}
else if (hasAriaInvalidAttribute)
{
// No validation errors. Need to remove `aria-invalid` if it was rendered already
if (AdditionalAttributes!.Count == 1)
{
// Only aria-invalid argument is present which we don't need any more
AdditionalAttributes = null;
}
else
{
if (ConvertToDictionary(AdditionalAttributes, out var additionalAttributes))
{
AdditionalAttributes = additionalAttributes;
}
additionalAttributes.Remove("aria-invalid");
}
}
}
/// <summary>
/// Returns a dictionary with the same values as the specified <paramref name="source"/>.
/// </summary>
/// <returns>true, if a new dictionary with copied values was created. false - otherwise.</returns>
private static bool ConvertToDictionary(IReadOnlyDictionary<string, object>? source, out Dictionary<string, object> result)
{
var newDictionaryCreated = true;
if (source == null)
{
result = [];
}
else if (source is Dictionary<string, object> currentDictionary)
{
result = currentDictionary;
newDictionaryCreated = false;
}
else
{
result = [];
foreach (var item in source)
{
result.Add(item.Key, item.Value);
}
}
return newDictionaryCreated;
}
/// <inheritdoc />
protected virtual void Dispose(bool disposing)
{
}
void IDisposable.Dispose()
{
// When initialization in the SetParametersAsync method fails, the EditContext property can remain equal to null
if (EditContext is not null)
{
EditContext.OnValidationStateChanged -= _validationStateChangedHandler;
}
_timerCancellationTokenSource.Dispose();
Dispose(disposing: true);
}
public static string? CombineClassNames(IReadOnlyDictionary<string, object>? additionalAttributes, string? classNames)
{
if (additionalAttributes is null || !additionalAttributes.TryGetValue("class", out var @class))
{
return classNames;
}
var classAttributeValue = Convert.ToString(@class, CultureInfo.InvariantCulture);
if (string.IsNullOrEmpty(classAttributeValue))
{
return classNames;
}
if (string.IsNullOrEmpty(classNames))
{
return classAttributeValue;
}
return $"{classAttributeValue} {classNames}";
}
}