/
InputBase.cs
379 lines (327 loc) · 14.7 KB
/
InputBase.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Components.Forms.Mapping;
namespace Microsoft.AspNetCore.Components.Forms;
/// <summary>
/// A base class for form input components. This base class automatically
/// integrates with an <see cref="Forms.EditContext"/>, which must be supplied
/// as a cascading parameter.
/// </summary>
public abstract class InputBase<TValue> : ComponentBase, IDisposable
{
private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
private bool _hasInitializedParameters;
private bool _parsingFailed;
private string? _incomingValueBeforeParsing;
private string? _formattedValueExpression;
private bool _previousParsingAttemptFailed;
private ValidationMessageStore? _parsingValidationMessages;
private Type? _nullableUnderlyingType;
private bool _shouldGenerateFieldNames;
[CascadingParameter] private EditContext? CascadedEditContext { get; set; }
[CascadingParameter] private HtmlFieldPrefix FieldPrefix { get; set; } = default!;
/// <summary>
/// Gets or sets a collection of additional attributes that will be applied to the created element.
/// </summary>
[Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object>? AdditionalAttributes { 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 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>
/// Gets the associated <see cref="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; }
/// <summary>
/// Gets or sets the current value of the input.
/// </summary>
protected TValue? CurrentValue
{
get => Value;
set
{
var hasChanged = !EqualityComparer<TValue>.Default.Equals(value, Value);
if (hasChanged)
{
_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;
_ = ValueChanged.InvokeAsync(Value);
EditContext?.NotifyFieldChanged(FieldIdentifier);
}
}
}
/// <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
{
_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 var parsedValue, out var validationErrorMessage))
{
_parsingFailed = false;
CurrentValue = parsedValue!;
}
else
{
_parsingFailed = true;
// EditContext may be null if the input is not a child component of EditForm.
if (EditContext is not null)
{
_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 InputBase()
{
_validationStateChangedHandler = OnValidateStateChanged;
}
/// <summary>
/// Formats the value as a string. Derived classes can override this to determine the formatting 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's 'class' attribute.
/// </summary>
protected string CssClass
{
get
{
var fieldClass = EditContext?.FieldCssClass(FieldIdentifier);
return AttributeUtilities.CombineClassNames(AdditionalAttributes, fieldClass) ?? string.Empty;
}
}
/// <summary>
/// Gets the value to be used for the input's "name" attribute.
/// </summary>
protected string NameAttributeValue
{
get
{
if (AdditionalAttributes?.TryGetValue("name", out var nameAttributeValue) ?? false)
{
return Convert.ToString(nameAttributeValue, CultureInfo.InvariantCulture) ?? string.Empty;
}
if (_shouldGenerateFieldNames)
{
if (_formattedValueExpression is null && ValueExpression is not null)
{
_formattedValueExpression = FieldPrefix != null ? FieldPrefix.GetFieldName(ValueExpression) :
ExpressionFormatter.FormatLambda(ValueExpression);
}
return _formattedValueExpression ?? string.Empty;
}
return string.Empty;
}
}
/// <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 == null)
{
throw new InvalidOperationException($"{GetType()} requires a value for the 'ValueExpression' " +
$"parameter. Normally this is provided automatically when using 'bind-Value'.");
}
FieldIdentifier = FieldIdentifier.Create(ValueExpression);
if (CascadedEditContext != null)
{
EditContext = CascadedEditContext;
EditContext.OnValidationStateChanged += _validationStateChangedHandler;
_shouldGenerateFieldNames = EditContext.ShouldUseFieldIdentifiers;
}
else
{
// Ideally we'd know if we were in an SSR context but we don't
_shouldGenerateFieldNames = !OperatingSystem.IsBrowser();
}
_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(Forms.EditContext)} dynamically.");
}
UpdateAdditionalValidationAttributes();
// For derived components, retain the usual lifecycle with OnInit/OnParametersSet/etc.
return base.SetParametersAsync(ParameterView.Empty);
}
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 (EditContext.GetValidationMessages(FieldIdentifier).Any())
{
// If this input is associated with an incoming value from an HTTP form post (via model binding),
// retain the attempted value even if it's unparseable
var attemptedValue = EditContext.GetAttemptedValue(NameAttributeValue);
if (attemptedValue != null)
{
_parsingFailed = true;
_incomingValueBeforeParsing = attemptedValue;
}
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 = new Dictionary<string, object>();
}
else if (source is Dictionary<string, object> currentDictionary)
{
result = currentDictionary;
newDictionaryCreated = false;
}
else
{
result = new Dictionary<string, object>();
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;
}
Dispose(disposing: true);
}
}