-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathNimbleInputBase.cs
338 lines (291 loc) · 12.3 KB
/
NimbleInputBase.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
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
namespace NimbleBlazor;
public abstract class NimbleInputBase<TValue> : ComponentBase, IDisposable
{
private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
private bool _previousParsingAttemptFailed;
private ValidationMessageStore? _parsingValidationMessages;
private Type? _nullableUnderlyingType;
[CascadingParameter] private EditContext? CascadedEditContext { get; set; }
/// <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="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; }
/// <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)
{
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
{
get => FormatValueAsString(CurrentValue);
set
{
_parsingValidationMessages?.Clear();
bool parsingFailed;
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 NimbleInputBase()
{
_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 virtual bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage)
{
if (BindConverter.TryConvertTo(value, CultureInfo.InvariantCulture, out result))
{
validationErrorMessage = null;
return true;
}
else
{
validationErrorMessage = string.Format(CultureInfo.InvariantCulture, $"Could not convert {value} to type {typeof(TValue)}.");
return false;
}
}
/// <summary>
/// Gets a CSS class string that combines the <c>class</c> attribute 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) ?? string.Empty;
return CombineClassNames(AdditionalAttributes, fieldClass);
}
}
/// <inheritdoc />
public override Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (EditContext != null || CascadedEditContext != null)
{
// 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;
}
_nullableUnderlyingType = Nullable.GetUnderlyingType(typeof(TValue));
}
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);
}
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 (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
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 dictrionary with copied values was created. false - otherwise.</returns>
private 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;
}
protected virtual void Dispose(bool disposing)
{
// When initialization in the SetParametersAsync method fails, the EditContext property can remain equal to null
if (EditContext is not null)
{
EditContext.OnValidationStateChanged -= _validationStateChangedHandler;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
public 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}";
}
}