From b4a2f22310a9ffdbe109fac2b4805b4c0c7a33b1 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Mon, 23 Sep 2024 13:47:05 +0200 Subject: [PATCH 01/17] Add FluentInputBase and FluentInputImmediateBase --- src/Core/Components/Base/FluentInputBase.cs | 517 ++++++++++++++++++ .../Base/FluentInputImmediateBase.cs | 64 +++ ...Base.cs => IFluentComponentElementBase.cs} | 4 +- 3 files changed, 583 insertions(+), 2 deletions(-) create mode 100644 src/Core/Components/Base/FluentInputBase.cs create mode 100644 src/Core/Components/Base/FluentInputImmediateBase.cs rename src/Core/Components/Base/{FluentComponentElementBase.cs => IFluentComponentElementBase.cs} (81%) diff --git a/src/Core/Components/Base/FluentInputBase.cs b/src/Core/Components/Base/FluentInputBase.cs new file mode 100644 index 0000000000..8d8c08a8d8 --- /dev/null +++ b/src/Core/Components/Base/FluentInputBase.cs @@ -0,0 +1,517 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Components; +using System.Linq.Expressions; +using Microsoft.FluentUI.AspNetCore.Components.Utilities; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// A base class for Fluent UI form input components. This base class automatically +/// integrates with an , which must be supplied +/// as a cascading parameter. +/// +/// The type of the value to be edited. +public abstract partial class FluentInputBase : FluentComponentBase, IDisposable +{ + private readonly EventHandler _validationStateChangedHandler; + + private bool _disposed; + private bool _hasInitializedParameters; + private bool _parsingFailed; + private string? _incomingValueBeforeParsing; + private bool _previousParsingAttemptFailed; + private ValidationMessageStore? _parsingValidationMessages; + private Type? _nullableUnderlyingType; + + /// + /// Constructs an instance of . + /// + protected FluentInputBase() + { + _validationStateChangedHandler = OnValidateStateChanged; + } + + [CascadingParameter] + private EditContext? CascadedEditContext { get; set; } + + /// + /// Gets a CSS class string that combines the `Class` 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. + /// + protected virtual string? ClassValue + { + get + { + // TODO: To check if we need to add the `cssClass` for the input element + // var cssClass = CombineClassNames(AdditionalAttributes, fieldClass); + // See https://github.com/dotnet/aspnetcore/blob/main/src/Components/Shared/src/AttributeUtilities.cs + + var fieldClass = (FieldBound && !Embedded) ? EditContext?.FieldCssClass(FieldIdentifier) : null; + + if (!string.IsNullOrEmpty(fieldClass) || !string.IsNullOrEmpty(Class)) + { + return new CssBuilder(Class) + .AddClass(fieldClass) + .Build(); + } + + return null; + } + } + + /// + /// Gets the optional in-line styles. If given, these will be included in the style attribute of the component. + /// + protected virtual string? StyleValue => new StyleBuilder(Style).Build(); + + /// + /// Determines if the element should receive document focus on page load. + /// + [Parameter] + public virtual bool Autofocus { get; set; } + /// + /// Gets or sets the text used on `aria-label` attribute. + /// + [Parameter] + public virtual string? AriaLabel { get; set; } + + /// + /// Gets or sets a value indicating whether the form control is disabled and doesn't participate in form submission. + /// + [Parameter] + public virtual bool Disabled { get; set; } + + /// + /// Gets or sets the display name for this field. + /// This value is used when generating error messages when the input value fails to parse correctly. + /// + [Parameter] + public virtual string? DisplayName { get; set; } + + /// + /// Gets or sets if the derived component is embedded in another component. + /// If true, the property will not include the 's FieldCssClass. + /// + [Parameter] + public virtual bool Embedded { get; set; } + + /// + /// Gets or sets the that identifies the bound value. + /// If set, this parameter takes precedence over . + /// + [Parameter] + public virtual FieldIdentifier? Field { get; set; } + + /// + /// Gets or sets the text to label the input. This is usually displayed just above the input. + /// + [Parameter] + public virtual string? Label { get; set; } + + /// + /// Gets or sets the content to label the input component. + /// This is usually displayed just above the input + /// + [Parameter] + public virtual RenderFragment? LabelTemplate { get; set; } + + /// + /// 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. + /// + [Parameter] + public virtual string? Name { get; set; } + + /// + /// Gets or sets whether the control will be immutable by user interaction. + /// + [Parameter] + public virtual bool ReadOnly { get; set; } + + /// + /// Gets or sets a value indicating whether the element needs to have a value. + /// + [Parameter] + public bool Required { get; set; } + + /// + /// Gets or sets the value of the input. This should be used with two-way binding. + /// + /// + /// @bind-Value="model.PropertyName" + /// + [Parameter] + public virtual TValue? Value { get; set; } + + /// + /// Gets or sets a callback that updates the bound value. + /// + [Parameter] + public virtual EventCallback ValueChanged { get; set; } + + /// + /// Gets or sets an expression that identifies the bound value. + /// + [Parameter] + public virtual Expression>? ValueExpression { get; set; } + + /// + /// Gets the associated . + /// This property is uninitialized if the input does not have a parent . + /// + protected virtual EditContext EditContext { get; set; } = default!; + + /// + /// Gets the for the bound value. + /// + protected internal virtual FieldIdentifier FieldIdentifier { get; set; } + + /// + /// Gets true when the or is set. + /// + internal virtual bool FieldBound => Field is not null || ValueExpression is not null || ValueChanged.HasDelegate; + + /// + /// Sets the value of the input, formatted as a string. + /// + /// + /// + protected virtual async Task SetCurrentValueAsync(TValue? value) + { + var hasChanged = !EqualityComparer.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) + { + // Thread Safety: Force `ValueChanged` to be re-associated with the Dispatcher, prior to invocation. + await InvokeAsync(async () => await ValueChanged.InvokeAsync(value)); + } + + if (FieldBound) + { + // Thread Safety: Force `EditContext` to be re-associated with the Dispatcher + await InvokeAsync(() => EditContext?.NotifyFieldChanged(FieldIdentifier)); + } + } + + /// + /// Gets or sets the current value of the input. + /// + protected virtual TValue? CurrentValue + { + get => Value; + set => _ = SetCurrentValueAsync(value); + } + + /// + /// Gets or sets the current value of the input, represented as a string. + /// + protected virtual 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); + + } + + /// + /// Attempts to set the current value of the input, represented as a string. + /// + /// + protected virtual 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 based on the type itself). + _parsingFailed = false; + CurrentValue = default!; + } + else if (TryParseValueFromString(value, out var 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; + } + } + + /// + /// Formats the value as a string. + /// Derived classes can override this to determine the formatting used for . + /// + /// The value to format. + /// A string representation of the value. + protected virtual string? FormatValueAsString(TValue? value) + { + return value?.ToString(); + } + + /// + /// Parses a string to create an instance of . + /// Derived classes can override this to change how interprets incoming values. + /// + /// The string value to be parsed. + /// An instance of . + /// If the value could not be parsed, provides a validation error message. + /// True if the value could be parsed; otherwise false. + protected abstract bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage); + + /// + /// Handler for the `OnChange` event. + /// + /// + /// + protected virtual async Task ChangeHandlerAsync(ChangeEventArgs e) + { + var _notifyCalled = false; + var isValid = TryParseValueFromString(e.Value?.ToString(), out var result, out var validationErrorMessage); + + if (isValid) + { + await SetCurrentValueAsync(result ?? default); + _notifyCalled = true; + } + else + { + if (FieldBound && CascadedEditContext != null) + { + _parsingValidationMessages ??= new ValidationMessageStore(CascadedEditContext); + + _parsingValidationMessages.Clear(); + _parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage ?? "Unknown parsing error"); + } + } + + if (FieldBound && !_notifyCalled) + { + CascadedEditContext?.NotifyFieldChanged(FieldIdentifier); + } + } + + /// + 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 (Field is not null) + { + FieldIdentifier = (FieldIdentifier)Field; + } + + else 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); + } + + /// + /// Update additional validations. + /// + /// + /// + private void OnValidateStateChanged(object? sender, ValidationStateChangedEventArgs eventArgs) + { + UpdateAdditionalValidationAttributes(); + _ = InvokeAsync(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"); + } + } + } + + /// + /// Returns a dictionary with the same values as the specified . + /// + /// true, if a new dictionary with copied values was created. false - otherwise. + private static bool ConvertToDictionary(IReadOnlyDictionary? source, out Dictionary result) + { + var newDictionaryCreated = true; + if (source == null) + { + result = []; + } + else if (source is Dictionary currentDictionary) + { + result = currentDictionary; + newDictionaryCreated = false; + } + else + { + result = []; + foreach (var item in source) + { + result.Add(item.Key, item.Value); + } + } + + return newDictionaryCreated; + } + + /// + /// Disposes the component. + /// + /// + protected virtual void Dispose(bool disposing) + { + if (_disposed) + { + return; + } + + if (disposing) + { + // Dispose managed state (managed objects). + // ... + + if (EditContext is not null) + { + EditContext.OnValidationStateChanged -= _validationStateChangedHandler; + } + } + + // Free unmanaged resources (unmanaged objects) and override a finalizer below. + // ... + + _disposed = true; + } + + /// + /// Disposes the component. + /// + public void Dispose() + { + Dispose(disposing: true); + + // Suppress finalization. + GC.SuppressFinalize(this); + } +} diff --git a/src/Core/Components/Base/FluentInputImmediateBase.cs b/src/Core/Components/Base/FluentInputImmediateBase.cs new file mode 100644 index 0000000000..335d7454b3 --- /dev/null +++ b/src/Core/Components/Base/FluentInputImmediateBase.cs @@ -0,0 +1,64 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using Microsoft.AspNetCore.Components; +using Microsoft.FluentUI.AspNetCore.Components.Utilities; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// A base class for Fluent UI form input components, including an immediate validation mode (using the `OnInput` event). +/// This base class automatically integrates with an , +/// which must be supplied as a cascading parameter. +/// +/// The type of the value to be edited. +public abstract partial class FluentInputImmediateBase : FluentInputBase +{ + private readonly Debounce _debounce = new(); + + /// + /// Change the content of this input field when the user write text (based on 'OnInput' HTML event). + /// + [Parameter] + public bool Immediate { get; set; } = false; + + /// + /// Gets or sets the delay, in milliseconds, before to raise the event. + /// + [Parameter] + public int ImmediateDelay { get; set; } = 0; + + /// + /// Handler for the OnInput event, with an optional delay to avoid to raise the event too often. + /// + /// + /// + protected virtual async Task InputHandlerAsync(ChangeEventArgs e) + { + if (!Immediate) + { + return; + } + + if (ImmediateDelay > 0) + { + await _debounce.RunAsync(ImmediateDelay, async () => await ChangeHandlerAsync(e)); + } + else + { + await ChangeHandlerAsync(e); + } + } + + /// + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + _debounce.Dispose(); + } + } +} diff --git a/src/Core/Components/Base/FluentComponentElementBase.cs b/src/Core/Components/Base/IFluentComponentElementBase.cs similarity index 81% rename from src/Core/Components/Base/FluentComponentElementBase.cs rename to src/Core/Components/Base/IFluentComponentElementBase.cs index eaf6a3b4b6..953c911b8e 100644 --- a/src/Core/Components/Base/FluentComponentElementBase.cs +++ b/src/Core/Components/Base/IFluentComponentElementBase.cs @@ -9,11 +9,11 @@ namespace Microsoft.FluentUI.AspNetCore.Components; /// /// Base class for FluentUI Blazor components, containing an property. /// -public abstract class FluentComponentElementBase : FluentComponentBase +public interface IFluentComponentElementBase { /// /// Gets or sets a reference to the rendered element. /// May be if accessed before the component is rendered. /// - public virtual ElementReference Element { get; protected set; } + ElementReference Element { get; protected set; } } From fb59d0add054c86e13b1d9df7bd5f7d22587dbce Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Mon, 23 Sep 2024 15:07:12 +0200 Subject: [PATCH 02/17] Add FluentTextInput --- .../TextInput/Examples/TextInputDefault.razor | 10 ++++ .../Components/TextInput/FluentTextInput.md | 8 ++++ .../TextInput/FluentTextInput.razor | 46 +++++++++++++++++++ .../TextInput/FluentTextInput.razor.cs | 26 +++++++++++ 4 files changed, 90 insertions(+) create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md create mode 100644 src/Core/Components/TextInput/FluentTextInput.razor create mode 100644 src/Core/Components/TextInput/FluentTextInput.razor.cs diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor new file mode 100644 index 0000000000..fc0bf1eb82 --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor @@ -0,0 +1,10 @@ +My Label: + +
+ Value1: @value1 +
+ +@code +{ + string value1 = "Hello World"; +} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md new file mode 100644 index 0000000000..ee3058d984 --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md @@ -0,0 +1,8 @@ +--- +title: TextInput +route: /TextInput +--- + +# TextInput + +{{ TextInputDefault }} diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor new file mode 100644 index 0000000000..b6393ed5bd --- /dev/null +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -0,0 +1,46 @@ +@namespace Microsoft.FluentUI.AspNetCore.Components +@inherits FluentInputImmediateBase + + + @ChildContent + + +@* + + + + @ChildContent + +*@ diff --git a/src/Core/Components/TextInput/FluentTextInput.razor.cs b/src/Core/Components/TextInput/FluentTextInput.razor.cs new file mode 100644 index 0000000000..b662a7ace5 --- /dev/null +++ b/src/Core/Components/TextInput/FluentTextInput.razor.cs @@ -0,0 +1,26 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Components; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +public partial class FluentTextInput +{ + /// + /// Gets or sets the content to be rendered inside the component. + /// + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// + protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out string? result, [NotNullWhen(false)] out string? validationErrorMessage) + { + result = value; + validationErrorMessage = null; + return true; + } +} From 1af4ea938595b79e65f4f95b06b45738e438ae43 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Tue, 24 Sep 2024 10:36:15 +0200 Subject: [PATCH 03/17] Refactoring FluentInputBase (removing CurrentValue) --- src/Core/Components/Base/FluentInputBase.cs | 65 ++++++++++----------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/src/Core/Components/Base/FluentInputBase.cs b/src/Core/Components/Base/FluentInputBase.cs index 8d8c08a8d8..a0ca12c58f 100644 --- a/src/Core/Components/Base/FluentInputBase.cs +++ b/src/Core/Components/Base/FluentInputBase.cs @@ -75,6 +75,7 @@ protected virtual string? ClassValue /// [Parameter] public virtual bool Autofocus { get; set; } + /// /// Gets or sets the text used on `aria-label` attribute. /// @@ -150,6 +151,19 @@ protected virtual string? ClassValue [Parameter] public virtual TValue? Value { get; set; } + /// + /// Gets or sets the value of the input, represented as a string. + /// + protected string? ValueAsString + { + // 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(Value); + set => _ = SetValueAsStringAsync(value); + } + /// /// Gets or sets a callback that updates the bound value. /// @@ -183,7 +197,7 @@ protected virtual string? ClassValue /// /// /// - protected virtual async Task SetCurrentValueAsync(TValue? value) + protected virtual async Task SetValueAsync(TValue? value) { var hasChanged = !EqualityComparer.Default.Equals(value, Value); if (!hasChanged) @@ -218,33 +232,10 @@ protected virtual async Task SetCurrentValueAsync(TValue? value) } /// - /// Gets or sets the current value of the input. - /// - protected virtual TValue? CurrentValue - { - get => Value; - set => _ = SetCurrentValueAsync(value); - } - - /// - /// Gets or sets the current value of the input, represented as a string. - /// - protected virtual 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); - - } - - /// - /// Attempts to set the current value of the input, represented as a string. + /// Attempts to set the value of the input, represented as a string. /// /// - protected virtual async Task SetCurrentValueAsStringAsync(string? value) + protected virtual async Task SetValueAsStringAsync(string? value) { _incomingValueBeforeParsing = value; _parsingValidationMessages?.Clear(); @@ -255,13 +246,15 @@ protected virtual async Task SetCurrentValueAsStringAsync(string? value) // Then all subclasses get nullable support almost automatically (they just have to // not reject Nullable based on the type itself). _parsingFailed = false; - CurrentValue = default!; + await SetValueAsync(default); } + else if (TryParseValueFromString(value, out var parsedValue, out var validationErrorMessage)) { _parsingFailed = false; - await SetCurrentValueAsync(parsedValue); + await SetValueAsync(parsedValue); } + else { _parsingFailed = true; @@ -272,7 +265,7 @@ protected virtual async Task SetCurrentValueAsStringAsync(string? value) _parsingValidationMessages ??= new ValidationMessageStore(EditContext); _parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage); - // Since we're not writing to CurrentValue, we'll need to notify about modification from here + // Since we're not writing to Value, we'll need to notify about modification from here EditContext.NotifyFieldChanged(FieldIdentifier); } } @@ -287,7 +280,6 @@ protected virtual async Task SetCurrentValueAsStringAsync(string? value) /// /// Formats the value as a string. - /// Derived classes can override this to determine the formatting used for . /// /// The value to format. /// A string representation of the value. @@ -298,7 +290,6 @@ protected virtual async Task SetCurrentValueAsStringAsync(string? value) /// /// Parses a string to create an instance of . - /// Derived classes can override this to change how interprets incoming values. /// /// The string value to be parsed. /// An instance of . @@ -318,7 +309,7 @@ protected virtual async Task ChangeHandlerAsync(ChangeEventArgs e) if (isValid) { - await SetCurrentValueAsync(result ?? default); + await SetValueAsync(result ?? default); _notifyCalled = true; } else @@ -372,6 +363,7 @@ public override Task SetParametersAsync(ParameterView parameters) _nullableUnderlyingType = Nullable.GetUnderlyingType(typeof(TValue)); _hasInitializedParameters = true; } + else if (CascadedEditContext != EditContext) { // Not the first run @@ -400,6 +392,9 @@ private void OnValidateStateChanged(object? sender, ValidationStateChangedEventA _ = InvokeAsync(StateHasChanged); } + /// + /// Updates the additional validation attributes. + /// private void UpdateAdditionalValidationAttributes() { if (EditContext is null) @@ -408,6 +403,7 @@ private void UpdateAdditionalValidationAttributes() } var hasAriaInvalidAttribute = AdditionalAttributes != null && AdditionalAttributes.ContainsKey("aria-invalid"); + if (FieldBound && EditContext.GetValidationMessages(FieldIdentifier).Any()) { if (hasAriaInvalidAttribute) @@ -430,12 +426,12 @@ private void UpdateAdditionalValidationAttributes() 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)) @@ -455,15 +451,18 @@ private void UpdateAdditionalValidationAttributes() private static bool ConvertToDictionary(IReadOnlyDictionary? source, out Dictionary result) { var newDictionaryCreated = true; + if (source == null) { result = []; } + else if (source is Dictionary currentDictionary) { result = currentDictionary; newDictionaryCreated = false; } + else { result = []; From a960949ab9e00409456b28ac5277a9ca1d6ad3c4 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Tue, 24 Sep 2024 11:39:43 +0200 Subject: [PATCH 04/17] Add Base Unit Tests --- .../TextInput/FluentTextInput.razor | 3 + .../TextInput/FluentTextInput.razor.cs | 8 +- tests/Core/Components/Base/BaseHelpers.cs | 67 +++++++++++++ .../Components/Base/ComponentBaseTests.cs | 42 ++++---- tests/Core/Components/Base/InputBaseTests.cs | 99 +++++++++++++++++++ 5 files changed, 196 insertions(+), 23 deletions(-) create mode 100644 tests/Core/Components/Base/BaseHelpers.cs create mode 100644 tests/Core/Components/Base/InputBaseTests.cs diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor index b6393ed5bd..0f3252c344 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -1,11 +1,14 @@ @namespace Microsoft.FluentUI.AspNetCore.Components @inherits FluentInputImmediateBase +@* Label *@ + + /// + /// Parses a string to create the . + /// + /// The string value to be parsed. + /// The result to inject into the Value. + /// If the value could not be parsed, provides a validation error message. + /// True if the value could be parsed; otherwise false. protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out string? result, [NotNullWhen(false)] out string? validationErrorMessage) { result = value; diff --git a/tests/Core/Components/Base/BaseHelpers.cs b/tests/Core/Components/Base/BaseHelpers.cs new file mode 100644 index 0000000000..516c38b4a1 --- /dev/null +++ b/tests/Core/Components/Base/BaseHelpers.cs @@ -0,0 +1,67 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Bunit; +using static Microsoft.FluentUI.AspNetCore.Components.Tests.Samples.Icons; + +namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Components.Base; + +internal static class BaseHelpers +{ + /// + /// Gets the derived types from the specified base type. + /// + public static IEnumerable GetDerivedTypes(IEnumerable except) => GetDerivedTypes(typeof(T), except); + + /// + /// Gets the derived types from the specified base type. + /// + public static IEnumerable GetDerivedTypes(Type baseType, IEnumerable except) + { + var assembly = typeof(AspNetCore.Components._Imports).Assembly; + + return assembly.GetTypes().Where(t => t.IsClass && !t.IsAbstract && IsSubclassOfGenericType(t, baseType) && !except.Contains(t)); + } + + public static bool ContainsAttribute(this string markup, string htmlName, object value) + { + // The pattern to match the "attribute"="value" in the markup. + var pattern = @$"\b{htmlName}\s*=\s*[""'][^""']*\b{value}\b[^""']*[""']"; + + // For boolean attributes, the value is not required. + if (value is bool && (bool)value == true) + { + pattern = @$"\b{htmlName}\b"; + } + + return Regex.IsMatch(markup, pattern); + + } + + /// + /// Check if the type is a subclass of the generic type (direct or indirect) + /// + private static bool IsSubclassOfGenericType(Type? type, Type genericType) + { + while (type != null && type != typeof(object)) + { + var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type; + if (cur == genericType) + { + return true; + } + + type = type.BaseType; + } + + return false; + } +} diff --git a/tests/Core/Components/Base/ComponentBaseTests.cs b/tests/Core/Components/Base/ComponentBaseTests.cs index 23c7f9c696..1eae58ebb3 100644 --- a/tests/Core/Components/Base/ComponentBaseTests.cs +++ b/tests/Core/Components/Base/ComponentBaseTests.cs @@ -11,6 +11,7 @@ using Microsoft.FluentUI.AspNetCore.Components; using Microsoft.JSInterop; using Xunit; +using Xunit.Abstractions; namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Components.Base; @@ -32,6 +33,17 @@ public class ComponentBaseTests : TestContext { typeof(FluentIcon<>), type => type.MakeGenericType(typeof(Samples.Icons.Samples.Info)) } }; + /// + public ComponentBaseTests(ITestOutputHelper testOutputHelper) + { + Output = testOutputHelper; + } + + /// + /// Gets the test output helper. + /// + public ITestOutputHelper Output { get; } + /// /// Test to verify that all FluentUI components implement the default properties (Id, Class, Style) /// from . @@ -46,18 +58,16 @@ public class ComponentBaseTests : TestContext [InlineData("Class", "class", "My-Specific-Class")] [InlineData("Style", "style", "My-Specific-Style")] [InlineData("extra-attribute", "extra-attribute", "My-Specific-Attribute")] // AdditionalAttributes - public void ComponentBase_DefaultProperties(string propName, string? htmlName, string value) + public void ComponentBase_DefaultProperties(string propName, string htmlName, object value) { var errors = new StringBuilder(); - foreach (var componentType in GetFluentComponents()) + foreach (var componentType in BaseHelpers.GetDerivedTypes(except: Excluded)) { // Convert to generic type if needed - var type = componentType; - if (ComponentInitializer.ContainsKey(componentType)) - { - type = ComponentInitializer[componentType](componentType); - } + var type = ComponentInitializer.ContainsKey(componentType) + ? ComponentInitializer[componentType](componentType) + : componentType; // Arrange and Act var renderedComponent = RenderComponent(parameters => @@ -70,8 +80,9 @@ public void ComponentBase_DefaultProperties(string propName, string? htmlName, s }); // Assert - var pattern = @$"\b{htmlName}\s*=\s*[""'][^""']*\b{value}\b[^""']*[""']"; - var isMatch = Regex.IsMatch(renderedComponent.Markup, pattern); + var isMatch = renderedComponent.Markup.ContainsAttribute(htmlName, value); + + Output.WriteLine($"{(isMatch ? "✅" : "❌")} {componentType.Name}"); if (!isMatch) { @@ -131,17 +142,4 @@ private class MyComponent : FluentGrid public const string JAVASCRIPT_FILENAME = "FluentGrid.razor.js"; public IJSObjectReference GetJSModule() => base.JSModule; } - - /// - /// Returns all FluentUI components, which inherit from . - /// - /// - private IEnumerable GetFluentComponents() - { - var componentBaseType = typeof(FluentComponentBase); - var assembly = typeof(AspNetCore.Components._Imports).Assembly; - - return assembly.GetTypes() - .Where(t => componentBaseType.IsAssignableFrom(t) && !t.IsAbstract && !Excluded.Contains(t)); - } } diff --git a/tests/Core/Components/Base/InputBaseTests.cs b/tests/Core/Components/Base/InputBaseTests.cs new file mode 100644 index 0000000000..52d2b43cea --- /dev/null +++ b/tests/Core/Components/Base/InputBaseTests.cs @@ -0,0 +1,99 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.FluentUI.AspNetCore.Components; +using Microsoft.JSInterop; +using Microsoft.VisualStudio.TestPlatform.Utilities; +using Xunit; +using Xunit.Abstractions; + +namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Components.Base; + +public class InputBaseTests : TestContext +{ + /// + /// List of components to exclude from the test. + /// + private static readonly Type[] Excluded = new[] + { + typeof(AspNetCore.Components._Imports) + }; + + /// + /// List of customized actions to initialize the component with a specific type. + /// + private static readonly Dictionary> ComponentInitializer = new() + { + // { typeof(FluentIcon<>), type => type.MakeGenericType(typeof(Samples.Icons.Samples.Info)) } + }; + + /// + public InputBaseTests(ITestOutputHelper testOutputHelper) + { + Output = testOutputHelper; + } + + /// + /// Gets the test output helper. + /// + public ITestOutputHelper Output { get; } + + /// + /// Test to verify that all FluentUI components implement the default properties (Label, Disabled, ReadOnly, ...) + /// from . + /// + /// ⚠️ DO NOT CHANGE THE FOLLOWING TEST. + /// + /// Blazor Component property name + /// HTML attribute name + /// Value + [Theory] + [InlineData("Name", "name", "my-name")] + [InlineData("Disabled", "disabled", true)] + [InlineData("ReadOnly", "readonly", true)] + [InlineData("AriaLabel", "aria-label", "my-aria-label")] + [InlineData("Autofocus", "autofocus", true)] + [InlineData("Required", "required", true)] + public void InputBase_DefaultProperties(string propName, string htmlName, object value) + { + var errors = new StringBuilder(); + + foreach (var componentType in BaseHelpers.GetDerivedTypes(baseType: typeof(FluentInputBase<>), except: Excluded)) + { + // Convert to generic type if needed + var type = ComponentInitializer.ContainsKey(componentType) + ? ComponentInitializer[componentType](componentType) + : componentType; + + // Arrange and Act + var renderedComponent = RenderComponent(parameters => + { + parameters.Add(p => p.Type, type); + parameters.Add(p => p.Parameters, new Dictionary + { + { propName, value } + }); + }); + + // Assert + var isMatch = renderedComponent.Markup.ContainsAttribute(htmlName, value); + + Output.WriteLine($"{(isMatch ? "✅" : "❌")} {componentType.Name}"); + + if (!isMatch) + { + var error = $"\"{componentType.Name}\" does not use the \"{propName}\" property/attribute (missing HTML attribute {htmlName}=\"{value}\")."; + errors.AppendLine(error); + } + } + + Assert.True(errors.Length == 0, errors.ToString()); + } +} From 0bd1096c1693f2e59159c1eb79a9705ccbdeddf0 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Tue, 24 Sep 2024 11:58:48 +0200 Subject: [PATCH 05/17] Add Label --- src/Core/Components/TextInput/FluentTextInput.razor | 8 ++++++++ tests/Core/Components/Base/InputBaseTests.cs | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor index 0f3252c344..398f946ac7 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -16,6 +16,14 @@ @onchange="@ChangeHandlerAsync" @oninput="@InputHandlerAsync" @attributes="AdditionalAttributes"> + @if (!string.IsNullOrEmpty(Label) || LabelTemplate != null) + { + + @Label + @LabelTemplate + + } + @ChildContent diff --git a/tests/Core/Components/Base/InputBaseTests.cs b/tests/Core/Components/Base/InputBaseTests.cs index 52d2b43cea..57611e7061 100644 --- a/tests/Core/Components/Base/InputBaseTests.cs +++ b/tests/Core/Components/Base/InputBaseTests.cs @@ -61,6 +61,7 @@ public InputBaseTests(ITestOutputHelper testOutputHelper) [InlineData("AriaLabel", "aria-label", "my-aria-label")] [InlineData("Autofocus", "autofocus", true)] [InlineData("Required", "required", true)] + [InlineData("Label", "", "my-label")] public void InputBase_DefaultProperties(string propName, string htmlName, object value) { var errors = new StringBuilder(); @@ -83,7 +84,9 @@ public void InputBase_DefaultProperties(string propName, string htmlName, object }); // Assert - var isMatch = renderedComponent.Markup.ContainsAttribute(htmlName, value); + var isMatch = string.IsNullOrEmpty(htmlName) + ? renderedComponent.Markup.Contains(value.ToString() ?? "") + : renderedComponent.Markup.ContainsAttribute(htmlName, value); Output.WriteLine($"{(isMatch ? "✅" : "❌")} {componentType.Name}"); From 340c43bd67b595319c38e93ead588d64f2a6d3e6 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Tue, 24 Sep 2024 12:44:15 +0200 Subject: [PATCH 06/17] Add Appearance and sample --- .../Examples/TextInputAppearances.razor | 11 ++++++ .../TextInput/Examples/TextInputDefault.razor | 10 ----- .../Components/TextInput/FluentTextInput.md | 6 ++- .../TextInput/FluentTextInput.razor | 12 +++--- .../TextInput/FluentTextInput.razor.cs | 12 ++++++ src/Core/Enums/ButtonAppearance.cs | 2 +- src/Core/Enums/TextInputAppearance.cs | 37 +++++++++++++++++++ src/Core/Migration/AppearanceExtensions.cs | 4 +- src/Core/Migration/FluentInputAppearance.cs | 18 +++++++++ .../FluentInputAppearanceExtensions.cs | 26 +++++++++++++ 10 files changed, 117 insertions(+), 21 deletions(-) create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor delete mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor create mode 100644 src/Core/Enums/TextInputAppearance.cs create mode 100644 src/Core/Migration/FluentInputAppearance.cs create mode 100644 src/Core/Migration/FluentInputAppearanceExtensions.cs diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor new file mode 100644 index 0000000000..612e6e893f --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor @@ -0,0 +1,11 @@ +
+ + + + +
+ +@code +{ + string value = ""; +} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor deleted file mode 100644 index fc0bf1eb82..0000000000 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputDefault.razor +++ /dev/null @@ -1,10 +0,0 @@ -My Label: - -
- Value1: @value1 -
- -@code -{ - string value1 = "Hello World"; -} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md index ee3058d984..bb259a0540 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md @@ -5,4 +5,8 @@ route: /TextInput # TextInput -{{ TextInputDefault }} +Input allows the user to enter and edit text. + +## Appearance + +{{ TextInputAppearances }} diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor index 398f946ac7..5c32aedda7 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -1,12 +1,13 @@ @namespace Microsoft.FluentUI.AspNetCore.Components +@using Microsoft.FluentUI.AspNetCore.Components.Extensions @inherits FluentInputImmediateBase -@* Label *@ - diff --git a/src/Core/Components/TextInput/FluentTextInput.razor.cs b/src/Core/Components/TextInput/FluentTextInput.razor.cs index 787b413e42..67a1c21ca6 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor.cs +++ b/src/Core/Components/TextInput/FluentTextInput.razor.cs @@ -10,6 +10,18 @@ namespace Microsoft.FluentUI.AspNetCore.Components; /// public partial class FluentTextInput { + /// + /// Gets or sets the visual appearance. + /// + [Parameter] + public TextInputAppearance Appearance { get; set; } = TextInputAppearance.Outline; + + /// + /// Gets or sets the short hint displayed in the input before the user enters a value. + /// + [Parameter] + public string? Placeholder { get; set; } + /// /// Gets or sets the content to be rendered inside the component. /// diff --git a/src/Core/Enums/ButtonAppearance.cs b/src/Core/Enums/ButtonAppearance.cs index ec5cc9de72..bd81c69f59 100644 --- a/src/Core/Enums/ButtonAppearance.cs +++ b/src/Core/Enums/ButtonAppearance.cs @@ -5,7 +5,7 @@ namespace Microsoft.FluentUI.AspNetCore.Components; /// -/// The visual appearance of the FluentButton. +/// The visual appearance of the . /// public enum ButtonAppearance { diff --git a/src/Core/Enums/TextInputAppearance.cs b/src/Core/Enums/TextInputAppearance.cs new file mode 100644 index 0000000000..85c233f308 --- /dev/null +++ b/src/Core/Enums/TextInputAppearance.cs @@ -0,0 +1,37 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.ComponentModel; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// The visual appearance of the . +/// +public enum TextInputAppearance +{ + /// + /// The default appearance. + /// + [Description("outline")] + Outline, + + /// + /// The appearance where a single line is drawn under the text. + /// + [Description("underline")] + Underline, + + /// + /// The appearance where the borders are filled with a lighter color. + /// + [Description("filled-lighter")] + FilledLighter, + + /// + /// The appearance where the borders are filled with a darker color. + /// + [Description("filled-darker")] + FilledDarker, +} diff --git a/src/Core/Migration/AppearanceExtensions.cs b/src/Core/Migration/AppearanceExtensions.cs index d545561234..75ffec96c1 100644 --- a/src/Core/Migration/AppearanceExtensions.cs +++ b/src/Core/Migration/AppearanceExtensions.cs @@ -4,9 +4,7 @@ namespace Microsoft.FluentUI.AspNetCore.Components.Migration; -/// -/// -/// +/// public static class AppearanceExtensions { /// diff --git a/src/Core/Migration/FluentInputAppearance.cs b/src/Core/Migration/FluentInputAppearance.cs new file mode 100644 index 0000000000..a6e3bfa4a1 --- /dev/null +++ b/src/Core/Migration/FluentInputAppearance.cs @@ -0,0 +1,18 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// The visual appearance of an input component. +/// +public enum FluentInputAppearance + +{ + /// + Filled, + + /// + Outline, +} diff --git a/src/Core/Migration/FluentInputAppearanceExtensions.cs b/src/Core/Migration/FluentInputAppearanceExtensions.cs new file mode 100644 index 0000000000..f882267ada --- /dev/null +++ b/src/Core/Migration/FluentInputAppearanceExtensions.cs @@ -0,0 +1,26 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +namespace Microsoft.FluentUI.AspNetCore.Components.Migration; + +/// +public static class FluentInputAppearanceExtensions +{ + /// + /// Converts an obsolete enum value to a . + /// + /// + /// + public static TextInputAppearance ToTextInputAppearance(this FluentInputAppearance appearance) + { +#pragma warning disable CS0618 // Type or member is obsolete + return appearance switch + { + FluentInputAppearance.Outline => TextInputAppearance.Outline, + FluentInputAppearance.Filled => TextInputAppearance.FilledDarker, + _ => TextInputAppearance.Outline + }; +#pragma warning restore CS0618 // Type or member is obsolete + } +} From 3a93b20a5b9e444949a9ea6918c0ae72504ff362 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Thu, 24 Oct 2024 18:48:15 +0200 Subject: [PATCH 07/17] Add Immediate examples --- .../TextInput/Examples/TextInputAppearances.razor | 15 ++++++++++----- .../TextInput/Examples/TextInputImmediate.razor | 10 ++++++++++ .../Components/TextInput/FluentTextInput.md | 4 ++++ .../InternalDebounce/DispatcherTimerExtensions.cs | 2 +- 4 files changed, 25 insertions(+), 6 deletions(-) create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor index 612e6e893f..b9de6415d7 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor @@ -1,11 +1,16 @@ 
- - - - + + + + +
+ + +
+ Value = @Value
@code { - string value = ""; + string Value = ""; } diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor new file mode 100644 index 0000000000..676fe3c125 --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor @@ -0,0 +1,10 @@ + + +
+ Value = @Value +
+ +@code +{ + string Value = ""; +} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md index bb259a0540..d7e01abc2e 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md @@ -10,3 +10,7 @@ Input allows the user to enter and edit text. ## Appearance {{ TextInputAppearances }} + +## Binding with ImmediateDelay + +{{ TextInputImmediate }} diff --git a/src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs b/src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs index 87dcc25068..fd0b0e4ba6 100644 --- a/src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs +++ b/src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs @@ -90,7 +90,7 @@ private static void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs { item.Status.SetResult(); } - }, TaskScheduler.Default); + }, TaskScheduler.Current); } } } From 4ebe05c148d98370be0901bb0ad89b5dad542395 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Fri, 25 Oct 2024 12:07:03 +0200 Subject: [PATCH 08/17] Add missing properties --- .../Examples/TextInputAppearances.razor | 15 ++-- .../Examples/TextInputImmediate.razor | 8 +- .../Examples/TextInputPrefixSuffix.razor | 16 ++++ .../TextInput/Examples/TextInputState.razor | 14 ++++ .../Components/TextInput/FluentTextInput.md | 44 ++++++++++- .../Demo/FluentUI.Demo/Components/App.razor | 3 +- spelling.dic | 1 + .../TextInput/FluentTextInput.razor | 66 +++++++--------- .../TextInput/FluentTextInput.razor.cs | 79 ++++++++++++++++++- src/Core/Enums/TextInputMode.cs | 62 +++++++++++++++ src/Core/Enums/TextInputSize.cs | 31 ++++++++ src/Core/Enums/TextInputType.cs | 43 ++++++++++ 12 files changed, 334 insertions(+), 48 deletions(-) create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputState.razor create mode 100644 src/Core/Enums/TextInputMode.cs create mode 100644 src/Core/Enums/TextInputSize.cs create mode 100644 src/Core/Enums/TextInputType.cs diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor index b9de6415d7..cb94144ec7 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor @@ -1,10 +1,15 @@ -
- - - - +
+ + + +
+
+ + + +
Value = @Value diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor index 676fe3c125..45a52469a8 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor @@ -1,4 +1,10 @@ - +
+ +
Value = @Value diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor new file mode 100644 index 0000000000..7e56d52416 --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor @@ -0,0 +1,16 @@ +
+ + + https:// + + + .com + + + + + + + + +
diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputState.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputState.razor new file mode 100644 index 0000000000..885bdf7beb --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputState.razor @@ -0,0 +1,14 @@ +
+ + + +
+ +
+ Value = @Value +
+ +@code +{ + string Value = ""; +} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md index d7e01abc2e..f5206e17fe 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md @@ -5,12 +5,54 @@ route: /TextInput # TextInput -Input allows the user to enter and edit text. +A **FluentTextInput** component enables a user to enter text into an app. +It's typically used to capture a single line of text. +The text displays on the screen in a simple, uniform format. ## Appearance +The apparent style of a text input can be changed by setting the `Appearance` property, but also by setting the `Size` property. + +You can also add a label to the text input by setting the `Label` property and a placeholder by setting the `Placeholder` property. +The label will be automatically positioned above the text input, and the placeholder will be displayed inside the text input. + +We recommand to use a spacing of 24px between text fields and other components. + {{ TextInputAppearances }} +Although not recommended by FluentUI, an input can be rendered inline with text using a style attribute. + +``` +
+ Name: + +
+``` + ## Binding with ImmediateDelay +In some cases, you may want to bind the value of the text input to a property of a model +and update the model immediately after the user types a character. But you may also want to delay the update. +This can be achieved by setting the `Immediate` and the optional `ImmediateDelay` properties. + {{ TextInputImmediate }} + +## States + +A text input can be in different states, such as `Disabled`, `ReadOnly`, and `Required`. + +{{ TextInputState }} + +## Prefix and Suffix + +You can use the `StartTemplate` and `EndTemplate` properties to add a prefix or a suffix to the text input +as `https://` and `.com` or an icon. + +These templates are automatically positioned with a small margin between the text entered and the prefix/suffix. +You cannot therefore fill the entire background of these templates, with a colour for example. + +{{ TextInputPrefixSuffix }} + +## API FluentTextInput + +{{ API Type=FluentTextInput }} diff --git a/examples/Demo/FluentUI.Demo/Components/App.razor b/examples/Demo/FluentUI.Demo/Components/App.razor index c4714d9c46..c65e12b27a 100644 --- a/examples/Demo/FluentUI.Demo/Components/App.razor +++ b/examples/Demo/FluentUI.Demo/Components/App.razor @@ -1,7 +1,8 @@  @{ - var DemoRenderMode = new InteractiveWebAssemblyRenderMode(false); + //var DemoRenderMode = new InteractiveWebAssemblyRenderMode(false); + var DemoRenderMode = new InteractiveServerRenderMode(false); } diff --git a/spelling.dic b/spelling.dic index e43a36698c..72e65a71f2 100644 --- a/spelling.dic +++ b/spelling.dic @@ -3,6 +3,7 @@ appsettings blazor cref csproj +datalist elementreference evenodd microsoft diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor index 5c32aedda7..605f02378c 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -2,56 +2,50 @@ @using Microsoft.FluentUI.AspNetCore.Components.Extensions @inherits FluentInputImmediateBase - @if (!string.IsNullOrEmpty(Label) || LabelTemplate != null) { - + @Label @LabelTemplate } - @ChildContent - + @if (StartTemplate != null) + { +
+ @StartTemplate +
+ } -@* - + @if (EndTemplate != null) + { +
+ @EndTemplate +
+ } - - @ChildContent - -*@ + diff --git a/src/Core/Components/TextInput/FluentTextInput.razor.cs b/src/Core/Components/TextInput/FluentTextInput.razor.cs index 67a1c21ca6..0d407716a5 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor.cs +++ b/src/Core/Components/TextInput/FluentTextInput.razor.cs @@ -7,8 +7,10 @@ namespace Microsoft.FluentUI.AspNetCore.Components; -/// -public partial class FluentTextInput +/// +/// A text input component that allows users to enter and edit a single line of text. +/// +public partial class FluentTextInput : FluentInputImmediateBase { /// /// Gets or sets the visual appearance. @@ -22,11 +24,80 @@ public partial class FluentTextInput [Parameter] public string? Placeholder { get; set; } + ///// + ///// Gets or sets the content to be rendered inside the component. + ///// + //[Parameter] + //public RenderFragment? ChildContent { get; set; } + + /// + /// Gets or sets the content to prefix the input component. + /// + [Parameter] + public virtual RenderFragment? StartTemplate { get; set; } + + /// + /// Gets or sets the content to suffix the input component. + /// + [Parameter] + public virtual RenderFragment? EndTemplate { get; set; } + + /// + /// Gets or sets the id of a datalist element that provides a list of suggested values. + /// datalist. + /// + [Parameter] + public string? DataList { get; set; } + + /// + /// Gets or sets the maximum number of characters allowed in the input + /// + [Parameter] + public int? MaxLength { get; set; } + + /// + /// Gets or sets the minimum number of characters allowed in the input + /// + [Parameter] + public int? MinLength { get; set; } + + /// + /// Gets or sets a regular expression that the value must match to pass validation. + /// + [Parameter] + public string? Pattern { get; set; } + + /// + /// Specifies whether a form or an input field should have autocomplete "on" or "off" or another value. + /// An Id value must be set to use this property. + /// + [Parameter] + public string? AutoComplete { get; set; } + + /// + /// Gets or sets the text filed type. See + /// + [Parameter] + public TextInputType? TextFieldType { get; set; } + + /// + /// Gets or sets the size of the input. See + /// + [Parameter] + public TextInputSize? Size { get; set; } + + /// + /// Gets or sets a value indicating whether spellcheck should be used. + /// + [Parameter] + public bool? Spellcheck { get; set; } // TODO: To verify if this is supported by the component + /// - /// Gets or sets the content to be rendered inside the component. + /// Gets or sets the type of data that can be entered by the user when editing the element or its content. + /// This allows a browser to display an appropriate virtual keyboard. Not supported by Safari. /// [Parameter] - public RenderFragment? ChildContent { get; set; } + public TextInputMode? InputMode { get; set; } // TODO: To verify if this is supported by the component /// /// Parses a string to create the . diff --git a/src/Core/Enums/TextInputMode.cs b/src/Core/Enums/TextInputMode.cs new file mode 100644 index 0000000000..95b4821919 --- /dev/null +++ b/src/Core/Enums/TextInputMode.cs @@ -0,0 +1,62 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.ComponentModel; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// Global attribute is an enumerated attribute that hints at the type of data that might be entered by the user while editing the element or its contents. +/// This allows a browser to display an appropriate virtual keyboard. +/// +public enum TextInputMode +{ + /// + /// No virtual keyboard. For when the page implements its own keyboard input control. + /// + [Description("none")] + None, + + /// + /// Standard input keyboard for the user's current locale. (default value) + /// + [Description("text")] + Text, + + /// + /// Fractional numeric input keyboard containing the digits and decimal separator for the user's locale (typically . or ,). Devices may or may not show a minus key (-). + /// + [Description("decimal")] + Decimal, + + /// + /// Numeric input keyboard, but only requires the digits 0–9. Devices may or may not show a minus key. + /// + [Description("numeric")] + Numeric, + + /// + /// A telephone keypad input, including the digits 0–9, the asterisk (*), and the pound (#) key. + /// + [Description("tel")] + Telephone, + + /// + /// A virtual keyboard optimized for search input. For instance, the return/submit key may be labeled "Search", along with possible other optimizations. + /// + [Description("search")] + Search, + + /// + /// A virtual keyboard optimized for entering email addresses. Typically includes the @character as well as other optimizations. + /// + [Description("email")] + Email, + + /// + /// A keypad optimized for entering URLs. This may have the / key more prominent, for example. Enhanced features could include history access and so on. + /// + [Description("url")] + Url +} diff --git a/src/Core/Enums/TextInputSize.cs b/src/Core/Enums/TextInputSize.cs new file mode 100644 index 0000000000..9b5033b553 --- /dev/null +++ b/src/Core/Enums/TextInputSize.cs @@ -0,0 +1,31 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.ComponentModel; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// Indicates the size of the . +/// +public enum TextInputSize +{ + /// + /// Small size. + /// + [Description("small")] + Small, + + /// + /// Medium size. + /// + [Description("medium")] + Medium, + + /// + /// Large size. + /// + [Description("large")] + Large, +} diff --git a/src/Core/Enums/TextInputType.cs b/src/Core/Enums/TextInputType.cs new file mode 100644 index 0000000000..54c2be969e --- /dev/null +++ b/src/Core/Enums/TextInputType.cs @@ -0,0 +1,43 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.ComponentModel; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// Describes the type of input of a . +/// +public enum TextInputType +{ + /// + /// The default type of text field + /// + [Description("text")] + Text, + + /// + /// A text field that is used for email address input. + /// + [Description("email")] + Email, + + /// + /// A text field that is used for password input. + /// + [Description("password")] + Password, + + /// + /// A text field that is used for telephone number input. + /// + [Description("tel")] + Telephone, + + /// + /// A text field that is used for URL input. + /// + [Description("url")] + Url +} From bfad851835ee3fedeb81187e8373ff66261c1728 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Wed, 13 Nov 2024 15:06:50 +0100 Subject: [PATCH 09/17] Add ObserveAttributeChanges to detect and apply the Value attribute --- .../Examples/TextInputImmediate.razor | 1 + .../Components/Button/FluentButton.razor.ts | 12 -------- .../TextInput/FluentTextInput.razor | 3 +- .../TextInput/FluentTextInput.razor.cs | 29 ++++++++++++++----- .../TextInput/FluentTextInput.razor.ts | 24 +++++++++++++++ 5 files changed, 49 insertions(+), 20 deletions(-) delete mode 100644 src/Core/Components/Button/FluentButton.razor.ts create mode 100644 src/Core/Components/TextInput/FluentTextInput.razor.ts diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor index 45a52469a8..c7aa76906a 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor @@ -2,6 +2,7 @@
diff --git a/src/Core/Components/Button/FluentButton.razor.ts b/src/Core/Components/Button/FluentButton.razor.ts deleted file mode 100644 index 88e497a3f8..0000000000 --- a/src/Core/Components/Button/FluentButton.razor.ts +++ /dev/null @@ -1,12 +0,0 @@ -export namespace Microsoft.FluentUI.Blazor { - - /** - * Sample function to test the library - * See V5-CHANGES.md for more information - * @returns - */ - export function MyFunction() { - return "Hello World"; - } - -} diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor index 605f02378c..e92ce2d5d6 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -2,7 +2,8 @@ @using Microsoft.FluentUI.AspNetCore.Components.Extensions @inherits FluentInputImmediateBase - /// A text input component that allows users to enter and edit a single line of text. ///
-public partial class FluentTextInput : FluentInputImmediateBase +public partial class FluentTextInput : FluentInputImmediateBase, IFluentComponentElementBase { + private const string JAVASCRIPT_FILE = JAVASCRIPT_ROOT + "TextInput/FluentTextInput.razor.js"; + + /// + [Parameter] + public ElementReference Element { get; set; } + /// /// Gets or sets the visual appearance. /// @@ -24,12 +31,6 @@ public partial class FluentTextInput : FluentInputImmediateBase [Parameter] public string? Placeholder { get; set; } - ///// - ///// Gets or sets the content to be rendered inside the component. - ///// - //[Parameter] - //public RenderFragment? ChildContent { get; set; } - /// /// Gets or sets the content to prefix the input component. /// @@ -99,6 +100,20 @@ public partial class FluentTextInput : FluentInputImmediateBase [Parameter] public TextInputMode? InputMode { get; set; } // TODO: To verify if this is supported by the component + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + { + // Import the JavaScript module + var jsModule = await ImportJavaScriptModuleAsync(JAVASCRIPT_FILE); + + // Call a function from the JavaScript module + // Wait for this PR to delete the code: https://github.com/microsoft/fluentui/pull/33144 + await jsModule.InvokeVoidAsync("Microsoft.FluentUI.Blazor.TextInput.ObserveAttributeChanges", Element); + } + } + /// /// Parses a string to create the . /// diff --git a/src/Core/Components/TextInput/FluentTextInput.razor.ts b/src/Core/Components/TextInput/FluentTextInput.razor.ts new file mode 100644 index 0000000000..ebaf529fed --- /dev/null +++ b/src/Core/Components/TextInput/FluentTextInput.razor.ts @@ -0,0 +1,24 @@ +export namespace Microsoft.FluentUI.Blazor.TextInput { + + /** + * Observe the changes in the ‘value’ attribute to update the element's ‘value’ property. + * Wait for this PR to delete the code. + * https://github.com/microsoft/fluentui/pull/33144 + */ + export function ObserveAttributeChanges(element: HTMLElement): void { + const observer = new MutationObserver((mutationsList) => { + for (let mutation of mutationsList) { + if (mutation.type === "attributes" && mutation.attributeName === "value") { + const newValue = element.getAttribute("value"); + const field = element as any; + if (newValue !== field.value) { + field.value = newValue; + } + } + } + }); + + observer.observe(element, { attributes: true }); + } + +} From 0cd7b8b855aaf73b2e63469f9d71c4ef4b20653a Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Wed, 13 Nov 2024 16:20:36 +0100 Subject: [PATCH 10/17] Fix the API comments --- .../Components/MarkdownViewer.razor.css | 2 +- .../Tools/FluentUI.Demo.Generators/CodeCommentsGenerator.cs | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/Tools/FluentUI.Demo.DocViewer/Components/MarkdownViewer.razor.css b/examples/Tools/FluentUI.Demo.DocViewer/Components/MarkdownViewer.razor.css index cfae3357f1..6e545edcf8 100644 --- a/examples/Tools/FluentUI.Demo.DocViewer/Components/MarkdownViewer.razor.css +++ b/examples/Tools/FluentUI.Demo.DocViewer/Components/MarkdownViewer.razor.css @@ -141,7 +141,7 @@ } .doc-viewer ::deep .api-table td code { - font-weight: 500; + font-weight: 600; background-color: rgb(243, 243, 243); } diff --git a/examples/Tools/FluentUI.Demo.Generators/CodeCommentsGenerator.cs b/examples/Tools/FluentUI.Demo.Generators/CodeCommentsGenerator.cs index bc6234d9ae..bf2542c844 100644 --- a/examples/Tools/FluentUI.Demo.Generators/CodeCommentsGenerator.cs +++ b/examples/Tools/FluentUI.Demo.Generators/CodeCommentsGenerator.cs @@ -19,8 +19,10 @@ public class CodeCommentsGenerator : IIncrementalGenerator { private static readonly string[] REGEX_CLEANUP = [ - "Microsoft\\.FluentUI\\.AspNetCore\\.Components\\.", - "FluentUI\\.Demo\\.Client\\." + @"Microsoft\.FluentUI\.AspNetCore\.Components\.", + @"FluentUI\.Demo\.Client\.", + @"\[\[.*?\]\]", + @"\[.*?\]" ]; public void Initialize(IncrementalGeneratorInitializationContext context) From 6d3c1df0eddcfb958d89076f4d5ad4635c720759 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Wed, 13 Nov 2024 16:23:44 +0100 Subject: [PATCH 11/17] Fix Global Unit Tests --- tests/Core/Components/Base/ComponentBaseTests.cs | 2 ++ tests/Core/Components/Base/InputBaseTests.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/tests/Core/Components/Base/ComponentBaseTests.cs b/tests/Core/Components/Base/ComponentBaseTests.cs index 1eae58ebb3..174b707047 100644 --- a/tests/Core/Components/Base/ComponentBaseTests.cs +++ b/tests/Core/Components/Base/ComponentBaseTests.cs @@ -62,6 +62,8 @@ public void ComponentBase_DefaultProperties(string propName, string htmlName, ob { var errors = new StringBuilder(); + JSInterop.Mode = JSRuntimeMode.Loose; + foreach (var componentType in BaseHelpers.GetDerivedTypes(except: Excluded)) { // Convert to generic type if needed diff --git a/tests/Core/Components/Base/InputBaseTests.cs b/tests/Core/Components/Base/InputBaseTests.cs index 57611e7061..cbd715fc02 100644 --- a/tests/Core/Components/Base/InputBaseTests.cs +++ b/tests/Core/Components/Base/InputBaseTests.cs @@ -66,6 +66,8 @@ public void InputBase_DefaultProperties(string propName, string htmlName, object { var errors = new StringBuilder(); + JSInterop.Mode = JSRuntimeMode.Loose; + foreach (var componentType in BaseHelpers.GetDerivedTypes(baseType: typeof(FluentInputBase<>), except: Excluded)) { // Convert to generic type if needed From f05464cc030e8db55d88cea00d2ce81dfb1e4641 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Wed, 13 Nov 2024 17:27:36 +0100 Subject: [PATCH 12/17] Add new tests --- .../TextInput/FluentTextInput.razor | 4 +- ...luentInputText_Default.verified.razor.html | 5 + ...nputText_LabelTemplate.verified.razor.html | 6 + ...tText_StartEndTemplate.verified.razor.html | 5 + .../TextInput/FluentTextInputTests.razor | 157 ++++++++++++++++++ 5 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_Default.verified.razor.html create mode 100644 tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_LabelTemplate.verified.razor.html create mode 100644 tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_StartEndTemplate.verified.razor.html create mode 100644 tests/Core/Components/TextInput/FluentTextInputTests.razor diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor index e92ce2d5d6..0427cc9dd5 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -4,13 +4,13 @@ + My Label + + \ No newline at end of file diff --git a/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_LabelTemplate.verified.razor.html b/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_LabelTemplate.verified.razor.html new file mode 100644 index 0000000000..660df642b3 --- /dev/null +++ b/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_LabelTemplate.verified.razor.html @@ -0,0 +1,6 @@ + + + +
My label
+
+
diff --git a/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_StartEndTemplate.verified.razor.html b/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_StartEndTemplate.verified.razor.html new file mode 100644 index 0000000000..1a15849800 --- /dev/null +++ b/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_StartEndTemplate.verified.razor.html @@ -0,0 +1,5 @@ + + +
Start
+
End
+
diff --git a/tests/Core/Components/TextInput/FluentTextInputTests.razor b/tests/Core/Components/TextInput/FluentTextInputTests.razor new file mode 100644 index 0000000000..90e95a953c --- /dev/null +++ b/tests/Core/Components/TextInput/FluentTextInputTests.razor @@ -0,0 +1,157 @@ +@using Microsoft.FluentUI.AspNetCore.Components.Extensions +@using Microsoft.FluentUI.AspNetCore.Components.Tests.Extensions +@using Microsoft.FluentUI.AspNetCore.Components.Utilities +@using Xunit; +@inherits TestContext + +@code +{ + public FluentTextInputTests() + { + JSInterop.Mode = JSRuntimeMode.Loose; + Services.AddSingleton(); + } + + [Fact] + public void FluentInputText_Default() + { + // Arrange && Act + var cut = Render(@); + + // Assert + cut.Verify(); + } + + [Theory] + [InlineData(TextInputAppearance.Outline, "outline")] + [InlineData(TextInputAppearance.Underline, "underline")] + [InlineData(TextInputAppearance.FilledLighter, "filled-lighter")] + [InlineData(TextInputAppearance.FilledDarker, "filled-darker")] + public void FluentInputText_Appearance(TextInputAppearance appearance, string expectedAttribute) + { + // Arrange && Act + var cut = Render(@); + + // Assert + cut.MarkupMatches($""); + } + + [Theory] + [InlineData(TextInputMode.None, "none")] + [InlineData(TextInputMode.Text, "text")] + [InlineData(TextInputMode.Decimal, "decimal")] + [InlineData(TextInputMode.Numeric, "numeric")] + [InlineData(TextInputMode.Telephone, "tel")] + [InlineData(TextInputMode.Search, "search")] + [InlineData(TextInputMode.Email, "email")] + [InlineData(TextInputMode.Url, "url")] + public void FluentInputText_InputMode(TextInputMode inputMode, string expectedAttribute) + { + // Arrange && Act + var cut = Render(@); + + // Assert + cut.MarkupMatches($""); + } + + [Theory] + [InlineData(TextInputType.Text, "text")] + [InlineData(TextInputType.Email, "email")] + [InlineData(TextInputType.Password, "password")] + [InlineData(TextInputType.Telephone, "tel")] + [InlineData(TextInputType.Url, "url")] + public void FluentInputText_TextFieldType(TextInputType type, string expectedAttribute) + { + // Arrange && Act + var cut = Render(@); + + // Assert + cut.MarkupMatches($""); + } + + [Theory] + [InlineData(TextInputSize.Small, "small")] + [InlineData(TextInputSize.Medium, "medium")] + [InlineData(TextInputSize.Large, "large")] + public void FluentInputText_Size(TextInputSize size, string expectedAttribute) + { + // Arrange && Act + var cut = Render(@); + + // Assert + cut.MarkupMatches($""); + } + + [Fact] + public void FluentInputText_LabelTemplate() + { + // Arrange && Act + var cut = Render( + @ +
My label
+
+ ); + + // Assert + cut.Verify(); + } + + [Fact] + public void FluentInputText_StartEndTemplate() + { + // Arrange && Act + var cut = Render( + @ + Start + End + + ); + + // Assert + cut.Verify(); + } + + [Fact] + public void FluentInputText_OnChange() + { + // Arrange + var value = "init"; + var cut = Render(@); + + // Act + cut.Find("fluent-text-input").Change("new value"); + + // Assert + Assert.Equal("new value", value); + cut.MarkupMatches(""); + } + + [Theory] + [InlineData(false, 0, "init", "init")] // No Immediate + [InlineData(true, 0, "new value", "new value")] // With Immediate and Delay = 0 ms + [InlineData(true, 100, "init", "new value")] // With Immediate and Delay = 100 ms + public async Task FluentInputText_OnInput(bool immediate, int immediateDelay, string expectedImmediateValue, string expectedDelayedValue) + { + // Arrange + var value = "init"; + var cut = Render(@); + + // Act + cut.Find("fluent-text-input").Input("new value"); + + // Assert: Immediate + Assert.Equal(expectedImmediateValue, value); + cut.MarkupMatches($""); + + // Assert: After a small delay + await Task.Delay(200); + Assert.Equal(expectedDelayedValue, value); + cut.MarkupMatches($""); + } +} From d3ca2dc530e57d49ec530dc9a3412d1b2ce85e68 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Wed, 13 Nov 2024 18:51:51 +0100 Subject: [PATCH 13/17] Fix Unit Tests --- src/Core/Components/Base/FluentInputBase.cs | 2 ++ src/Core/Components/Base/FluentInputImmediateBase.cs | 2 ++ tests/Core/Components/TextInput/FluentTextInputTests.razor | 4 +++- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Core/Components/Base/FluentInputBase.cs b/src/Core/Components/Base/FluentInputBase.cs index a0ca12c58f..8af77b2435 100644 --- a/src/Core/Components/Base/FluentInputBase.cs +++ b/src/Core/Components/Base/FluentInputBase.cs @@ -479,6 +479,7 @@ private static bool ConvertToDictionary(IReadOnlyDictionary? sou /// Disposes the component. ///
/// + [ExcludeFromCodeCoverage()] protected virtual void Dispose(bool disposing) { if (_disposed) @@ -506,6 +507,7 @@ protected virtual void Dispose(bool disposing) /// /// Disposes the component. /// + [ExcludeFromCodeCoverage()] public void Dispose() { Dispose(disposing: true); diff --git a/src/Core/Components/Base/FluentInputImmediateBase.cs b/src/Core/Components/Base/FluentInputImmediateBase.cs index 335d7454b3..4ed18faf4c 100644 --- a/src/Core/Components/Base/FluentInputImmediateBase.cs +++ b/src/Core/Components/Base/FluentInputImmediateBase.cs @@ -2,6 +2,7 @@ // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------------------ +using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Components; using Microsoft.FluentUI.AspNetCore.Components.Utilities; @@ -52,6 +53,7 @@ protected virtual async Task InputHandlerAsync(ChangeEventArgs e) } /// + [ExcludeFromCodeCoverage()] protected override void Dispose(bool disposing) { base.Dispose(disposing); diff --git a/tests/Core/Components/TextInput/FluentTextInputTests.razor b/tests/Core/Components/TextInput/FluentTextInputTests.razor index 90e95a953c..a187d1bfcc 100644 --- a/tests/Core/Components/TextInput/FluentTextInputTests.razor +++ b/tests/Core/Components/TextInput/FluentTextInputTests.razor @@ -1,6 +1,7 @@ @using Microsoft.FluentUI.AspNetCore.Components.Extensions @using Microsoft.FluentUI.AspNetCore.Components.Tests.Extensions @using Microsoft.FluentUI.AspNetCore.Components.Utilities +@using System.ComponentModel.DataAnnotations @using Xunit; @inherits TestContext @@ -22,7 +23,8 @@ Label="My Label" Name="MyName" Placeholder="My help" - Value="My Value" />); + Value="My Value" /> + ); // Assert cut.Verify(); From 01088d21c26513799bf229aa9b4aa912215525b2 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Wed, 13 Nov 2024 18:56:20 +0100 Subject: [PATCH 14/17] Add Unit Tests for Extension methods --- .../Components/TextInput/FluentTextInputTests.razor | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/Core/Components/TextInput/FluentTextInputTests.razor b/tests/Core/Components/TextInput/FluentTextInputTests.razor index a187d1bfcc..5f555c3116 100644 --- a/tests/Core/Components/TextInput/FluentTextInputTests.razor +++ b/tests/Core/Components/TextInput/FluentTextInputTests.razor @@ -156,4 +156,14 @@ Assert.Equal(expectedDelayedValue, value); cut.MarkupMatches($""); } + + [Theory] + [InlineData(FluentInputAppearance.Filled, TextInputAppearance.FilledDarker)] + [InlineData(FluentInputAppearance.Outline, TextInputAppearance.Outline)] + public void FluentInputText_ToTextInputAppearance(FluentInputAppearance appearance, TextInputAppearance expected) + { + var value = AspNetCore.Components.Migration.FluentInputAppearanceExtensions.ToTextInputAppearance(appearance); + + Assert.Equal(expected, value); + } } From 00bb8535fac567ad32e7fdb2486318af0f6e2756 Mon Sep 17 00:00:00 2001 From: "Denis Voituron (MSFT)" <105595161+dvoituron-msft@users.noreply.github.com> Date: Fri, 15 Nov 2024 09:03:02 +0100 Subject: [PATCH 15/17] [dev-v5] Use standard `InputBase` class (#2933) * Add FluentJSModule * Update the doc * Replace FluentInputBase with inheritance * - Fix runtime error (caused by using only Value) - Add 'Lab' page to do quick experiments - Exlude YT video because of constant script error - Adapt CopySources to use net9.0 TFM --------- Co-authored-by: Denis Voituron Co-authored-by: Vincent Baaij --- .../Components/Lab/Examples/Test.razor | 9 + .../Components/Lab/Experiments.md | 10 + .../Examples/TextInputPrefixSuffix.razor | 9 +- .../GetStarted/Migration/MigrationGeneral.md | 2 +- .../Documentation/Home.md | 6 +- .../FluentUI.Demo.Client.csproj | 2 +- .../Components/Base/FluentComponentBase.cs | 81 +--- src/Core/Components/Base/FluentInputBase.cs | 458 ++---------------- .../Base/FluentInputImmediateBase.cs | 3 +- src/Core/Components/Base/FluentJSModule.cs | 96 ++++ .../Components/Base/IFluentComponentBase.cs | 21 +- src/Core/Components/Grid/FluentGrid.razor.cs | 4 +- .../TextInput/FluentTextInput.razor | 2 +- .../TextInput/FluentTextInput.razor.cs | 6 +- .../Components/Base/ComponentBaseTests.cs | 2 +- 15 files changed, 207 insertions(+), 504 deletions(-) create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor create mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md create mode 100644 src/Core/Components/Base/FluentJSModule.cs diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor new file mode 100644 index 0000000000..10b08e6690 --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor @@ -0,0 +1,9 @@ +

Test

+ + + + + +@code { + public string test { get; set; } = "test"; +} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md new file mode 100644 index 0000000000..aac05cc43e --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md @@ -0,0 +1,10 @@ +--- +title: Lab +route: /Lab +--- + +# Lab +Just a simple page to do some experimenting + + +{{ Test }} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor index 7e56d52416..200dffb81c 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor @@ -1,5 +1,5 @@ 
- + https:// @@ -8,9 +8,14 @@ - +
+ +@code { + private string _sometext1 = "microsoft"; + private string _sometext2 = "fluentui-blazor@microsoft.com"; +} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/GetStarted/Migration/MigrationGeneral.md b/examples/Demo/FluentUI.Demo.Client/Documentation/GetStarted/Migration/MigrationGeneral.md index 055e6fee08..5187ae1117 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/GetStarted/Migration/MigrationGeneral.md +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/GetStarted/Migration/MigrationGeneral.md @@ -62,7 +62,7 @@ hidden: true if (firstRender) { // Import the JavaScript module - var jsModule = await ImportJavaScriptModuleAsync(JAVASCRIPT_FILE); + var jsModule = await JSModule.ImportJavaScriptModuleAsync(JAVASCRIPT_FILE); // Call a function from the JavaScript module await jsModule.InvokeAsync("Microsoft.FluentUI.Blazor.Button.MyFunction"); diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Home.md b/examples/Demo/FluentUI.Demo.Client/Documentation/Home.md index b952e3b9b0..829d77edf3 100644 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Home.md +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Home.md @@ -18,9 +18,13 @@ see the **"Getting Started"** section below. ## Introduction and getting started video - + ## Getting Started By far the easiest way to get started is by using our templates. Setting them up is quick and easy. See the [templates](/Templates) page for instructions and usage. + diff --git a/examples/Demo/FluentUI.Demo.Client/FluentUI.Demo.Client.csproj b/examples/Demo/FluentUI.Demo.Client/FluentUI.Demo.Client.csproj index 708fa0a1ed..7be038c2f9 100644 --- a/examples/Demo/FluentUI.Demo.Client/FluentUI.Demo.Client.csproj +++ b/examples/Demo/FluentUI.Demo.Client/FluentUI.Demo.Client.csproj @@ -41,7 +41,7 @@ - + diff --git a/src/Core/Components/Base/FluentComponentBase.cs b/src/Core/Components/Base/FluentComponentBase.cs index 456a1d2d99..38f08101e1 100644 --- a/src/Core/Components/Base/FluentComponentBase.cs +++ b/src/Core/Components/Base/FluentComponentBase.cs @@ -11,67 +11,37 @@ namespace Microsoft.FluentUI.AspNetCore.Components; /// /// Base class for FluentUI Blazor components. /// -public abstract class FluentComponentBase : ComponentBase, IAsyncDisposable +public abstract class FluentComponentBase : ComponentBase, IAsyncDisposable, IFluentComponentBase { - private IJSObjectReference? _jsModule; + private FluentJSModule? _jsModule; - /// - /// Gets the root path for the JavaScript files. - /// - protected const string JAVASCRIPT_ROOT = "./_content/Microsoft.FluentUI.AspNetCore.Components/Components/"; - - /// - /// Gets or sets a reference to the JavaScript runtime. - /// This property is injected by the Blazor framework. - /// + /// [Inject] - protected virtual IJSRuntime JSRuntime { get; set; } = default!; + private IJSRuntime JSRuntime { get; set; } = default!; /// - /// Gets the JavaScript module imported with the method. + /// Gets the JavaScript module imported with the method. /// You need to call this method (in the `OnAfterRenderAsync` method) before using the module. /// - protected virtual IJSObjectReference JSModule => _jsModule ?? throw new InvalidOperationException("You must call `ImportJavaScriptModuleAsync` method before accessing the JSModule property."); + internal FluentJSModule JSModule => _jsModule ??= new FluentJSModule(JSRuntime); - /// - /// Invoke the JavaScript runtime to import the JavaScript module. - /// - /// Name of the JavaScript file to import (e.g. JAVASCRIPT_ROOT + "Button/FluentButton.razor.js"). - /// - protected virtual async Task ImportJavaScriptModuleAsync(string file) - { - _jsModule ??= await JSRuntime.InvokeAsync("import", file); // TO ADD: .FormatCollocatedUrl(LibraryConfiguration) - return _jsModule; - } - - /// - /// Gets or sets the unique identifier. - /// The value will be used as the HTML global id attribute. - /// + /// [Parameter] public virtual string? Id { get; set; } - /// - /// Gets or sets the CSS class names. If given, these will be included in the class attribute of the component. - /// + /// [Parameter] public virtual string? Class { get; set; } - /// - /// Gets or sets the in-line styles. If given, these will be included in the style attribute of the component. - /// + /// [Parameter] public virtual string? Style { get; set; } - /// - /// Gets or sets custom data, to attach any user data object to the component. - /// + /// [Parameter] public virtual object? Data { get; set; } - /// - /// Gets or sets a collection of additional attributes that will be applied to the created element. - /// + /// [Parameter(CaptureUnmatchedValues = true)] public virtual IReadOnlyDictionary? AdditionalAttributes { get; set; } @@ -81,34 +51,19 @@ protected virtual async Task ImportJavaScriptModuleAsync(str /// /// [ExcludeFromCodeCoverage] - public async ValueTask DisposeAsync() + public virtual async ValueTask DisposeAsync() { - await DisposeAsync(_jsModule); - - if (_jsModule != null) - { - try - { - await _jsModule.DisposeAsync(); - } - catch (Exception ex) when (ex is JSDisconnectedException || - ex is OperationCanceledException) - { - // The JSRuntime side may routinely be gone already if the reason we're disposing is that - // the client disconnected. This is not an error. - } - } - - GC.SuppressFinalize(this); + await JSModule.DisposeAsync(); } /// - /// Dispose the object. + /// Dispose the object. /// + /// /// - /// - protected virtual ValueTask DisposeAsync(IJSObjectReference? jsModule) + [ExcludeFromCodeCoverage] + protected virtual async ValueTask DisposeAsync(IJSObjectReference? jsModule) { - return ValueTask.CompletedTask; + await JSModule.DisposeAsync(jsModule); } } diff --git a/src/Core/Components/Base/FluentInputBase.cs b/src/Core/Components/Base/FluentInputBase.cs index 8af77b2435..32daba9ec3 100644 --- a/src/Core/Components/Base/FluentInputBase.cs +++ b/src/Core/Components/Base/FluentInputBase.cs @@ -2,68 +2,61 @@ // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------------------ -using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components; -using System.Linq.Expressions; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.JSInterop; using Microsoft.FluentUI.AspNetCore.Components.Utilities; -using System.Diagnostics.CodeAnalysis; namespace Microsoft.FluentUI.AspNetCore.Components; /// /// A base class for Fluent UI form input components. This base class automatically -/// integrates with an , which must be supplied +/// integrates with an , which must be supplied /// as a cascading parameter. /// /// The type of the value to be edited. -public abstract partial class FluentInputBase : FluentComponentBase, IDisposable +public abstract partial class FluentInputBase : InputBase, IFluentComponentBase { - private readonly EventHandler _validationStateChangedHandler; + private FluentJSModule? _jsModule; - private bool _disposed; - private bool _hasInitializedParameters; - private bool _parsingFailed; - private string? _incomingValueBeforeParsing; - private bool _previousParsingAttemptFailed; - private ValidationMessageStore? _parsingValidationMessages; - private Type? _nullableUnderlyingType; + /// + [Inject] + private IJSRuntime JSRuntime { get; set; } = default!; /// - /// Constructs an instance of . + /// Gets the JavaScript module imported with the method. + /// You need to call this method (in the `OnAfterRenderAsync` method) before using the module. /// - protected FluentInputBase() - { - _validationStateChangedHandler = OnValidateStateChanged; - } + internal FluentJSModule JSModule => _jsModule ??= new FluentJSModule(JSRuntime); + + #region IFluentComponentBase + + /// + [Parameter] + public virtual string? Id { get; set; } + + /// + [Parameter] + public virtual string? Class { get; set; } + + /// + [Parameter] + public virtual string? Style { get; set; } + + /// + [Parameter] + public virtual object? Data { get; set; } + + #endregion - [CascadingParameter] - private EditContext? CascadedEditContext { get; set; } + #region FluentInputBase /// /// Gets a CSS class string that combines the `Class` 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. /// - protected virtual string? ClassValue - { - get - { - // TODO: To check if we need to add the `cssClass` for the input element - // var cssClass = CombineClassNames(AdditionalAttributes, fieldClass); - // See https://github.com/dotnet/aspnetcore/blob/main/src/Components/Shared/src/AttributeUtilities.cs - - var fieldClass = (FieldBound && !Embedded) ? EditContext?.FieldCssClass(FieldIdentifier) : null; - - if (!string.IsNullOrEmpty(fieldClass) || !string.IsNullOrEmpty(Class)) - { - return new CssBuilder(Class) - .AddClass(fieldClass) - .Build(); - } - - return null; - } - } + protected virtual string? ClassValue => new CssBuilder(Class).AddClass(base.CssClass).Build(); /// /// Gets the optional in-line styles. If given, these will be included in the style attribute of the component. @@ -88,27 +81,6 @@ protected virtual string? ClassValue [Parameter] public virtual bool Disabled { get; set; } - /// - /// Gets or sets the display name for this field. - /// This value is used when generating error messages when the input value fails to parse correctly. - /// - [Parameter] - public virtual string? DisplayName { get; set; } - - /// - /// Gets or sets if the derived component is embedded in another component. - /// If true, the property will not include the 's FieldCssClass. - /// - [Parameter] - public virtual bool Embedded { get; set; } - - /// - /// Gets or sets the that identifies the bound value. - /// If set, this parameter takes precedence over . - /// - [Parameter] - public virtual FieldIdentifier? Field { get; set; } - /// /// Gets or sets the text to label the input. This is usually displayed just above the input. /// @@ -143,376 +115,26 @@ protected virtual string? ClassValue public bool Required { get; set; } /// - /// Gets or sets the value of the input. This should be used with two-way binding. - /// - /// - /// @bind-Value="model.PropertyName" - /// - [Parameter] - public virtual TValue? Value { get; set; } - - /// - /// Gets or sets the value of the input, represented as a string. - /// - protected string? ValueAsString - { - // 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(Value); - set => _ = SetValueAsStringAsync(value); - } - - /// - /// Gets or sets a callback that updates the bound value. - /// - [Parameter] - public virtual EventCallback ValueChanged { get; set; } - - /// - /// Gets or sets an expression that identifies the bound value. - /// - [Parameter] - public virtual Expression>? ValueExpression { get; set; } - - /// - /// Gets the associated . - /// This property is uninitialized if the input does not have a parent . - /// - protected virtual EditContext EditContext { get; set; } = default!; - - /// - /// Gets the for the bound value. - /// - protected internal virtual FieldIdentifier FieldIdentifier { get; set; } - - /// - /// Gets true when the or is set. - /// - internal virtual bool FieldBound => Field is not null || ValueExpression is not null || ValueChanged.HasDelegate; - - /// - /// Sets the value of the input, formatted as a string. - /// - /// - /// - protected virtual async Task SetValueAsync(TValue? value) - { - var hasChanged = !EqualityComparer.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) - { - // Thread Safety: Force `ValueChanged` to be re-associated with the Dispatcher, prior to invocation. - await InvokeAsync(async () => await ValueChanged.InvokeAsync(value)); - } - - if (FieldBound) - { - // Thread Safety: Force `EditContext` to be re-associated with the Dispatcher - await InvokeAsync(() => EditContext?.NotifyFieldChanged(FieldIdentifier)); - } - } - - /// - /// Attempts to set the value of the input, represented as a string. - /// - /// - protected virtual async Task SetValueAsStringAsync(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 based on the type itself). - _parsingFailed = false; - await SetValueAsync(default); - } - - else if (TryParseValueFromString(value, out var parsedValue, out var validationErrorMessage)) - { - _parsingFailed = false; - await SetValueAsync(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 Value, 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; - } - } - - /// - /// Formats the value as a string. - /// - /// The value to format. - /// A string representation of the value. - protected virtual string? FormatValueAsString(TValue? value) - { - return value?.ToString(); - } - - /// - /// Parses a string to create an instance of . - /// - /// The string value to be parsed. - /// An instance of . - /// If the value could not be parsed, provides a validation error message. - /// True if the value could be parsed; otherwise false. - protected abstract bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage); - - /// - /// Handler for the `OnChange` event. + /// /// /// /// - protected virtual async Task ChangeHandlerAsync(ChangeEventArgs e) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "TODO")] + protected virtual Task ChangeHandlerAsync(ChangeEventArgs e) { - var _notifyCalled = false; var isValid = TryParseValueFromString(e.Value?.ToString(), out var result, out var validationErrorMessage); if (isValid) { - await SetValueAsync(result ?? default); - _notifyCalled = true; + Value = result; } else { - if (FieldBound && CascadedEditContext != null) - { - _parsingValidationMessages ??= new ValidationMessageStore(CascadedEditContext); - - _parsingValidationMessages.Clear(); - _parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage ?? "Unknown parsing error"); - } + // TODO } - if (FieldBound && !_notifyCalled) - { - CascadedEditContext?.NotifyFieldChanged(FieldIdentifier); - } + return Task.CompletedTask; } - /// - 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 (Field is not null) - { - FieldIdentifier = (FieldIdentifier)Field; - } - - else 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); - } - - /// - /// Update additional validations. - /// - /// - /// - private void OnValidateStateChanged(object? sender, ValidationStateChangedEventArgs eventArgs) - { - UpdateAdditionalValidationAttributes(); - _ = InvokeAsync(StateHasChanged); - } - - /// - /// Updates the additional validation attributes. - /// - 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"); - } - } - } - - /// - /// Returns a dictionary with the same values as the specified . - /// - /// true, if a new dictionary with copied values was created. false - otherwise. - private static bool ConvertToDictionary(IReadOnlyDictionary? source, out Dictionary result) - { - var newDictionaryCreated = true; - - if (source == null) - { - result = []; - } - - else if (source is Dictionary currentDictionary) - { - result = currentDictionary; - newDictionaryCreated = false; - } - - else - { - result = []; - foreach (var item in source) - { - result.Add(item.Key, item.Value); - } - } - - return newDictionaryCreated; - } - - /// - /// Disposes the component. - /// - /// - [ExcludeFromCodeCoverage()] - protected virtual void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - if (disposing) - { - // Dispose managed state (managed objects). - // ... - - if (EditContext is not null) - { - EditContext.OnValidationStateChanged -= _validationStateChangedHandler; - } - } - - // Free unmanaged resources (unmanaged objects) and override a finalizer below. - // ... - - _disposed = true; - } - - /// - /// Disposes the component. - /// - [ExcludeFromCodeCoverage()] - public void Dispose() - { - Dispose(disposing: true); - - // Suppress finalization. - GC.SuppressFinalize(this); - } + #endregion } diff --git a/src/Core/Components/Base/FluentInputImmediateBase.cs b/src/Core/Components/Base/FluentInputImmediateBase.cs index 4ed18faf4c..02213de2ad 100644 --- a/src/Core/Components/Base/FluentInputImmediateBase.cs +++ b/src/Core/Components/Base/FluentInputImmediateBase.cs @@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; using Microsoft.FluentUI.AspNetCore.Components.Utilities; namespace Microsoft.FluentUI.AspNetCore.Components; @@ -31,7 +32,7 @@ public abstract partial class FluentInputImmediateBase : FluentInputBase public int ImmediateDelay { get; set; } = 0; /// - /// Handler for the OnInput event, with an optional delay to avoid to raise the event too often. + /// Handler for the OnInput event, with an optional delay to avoid to raise the event too often. /// /// /// diff --git a/src/Core/Components/Base/FluentJSModule.cs b/src/Core/Components/Base/FluentJSModule.cs new file mode 100644 index 0000000000..9d451dc7c1 --- /dev/null +++ b/src/Core/Components/Base/FluentJSModule.cs @@ -0,0 +1,96 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using Microsoft.JSInterop; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +#pragma warning disable MA0004 // Use Task.ConfigureAwait + +/// +/// Base class to manage the JavaScript function from the FluentUI Blazor components. +/// +internal class FluentJSModule : IAsyncDisposable +{ + private IJSObjectReference? _jsModule; + + /// + /// Gets the root path for the JavaScript files. + /// + public const string JAVASCRIPT_ROOT = "./_content/Microsoft.FluentUI.AspNetCore.Components/Components/"; + + /// + /// Initializes a new instance of the class. + /// + /// + public FluentJSModule(IJSRuntime jsRuntime) + { + JSRuntime = jsRuntime; + } + + /// + /// Gets or sets a reference to the JavaScript runtime. + /// This property is injected by the Blazor framework. + /// + protected virtual IJSRuntime JSRuntime { get; set; } = default!; + + /// + /// Gets the JavaScript module imported with the method. + /// You need to call this method (in the `OnAfterRenderAsync` method) before using the module. + /// + public IJSObjectReference ObjectReference => _jsModule ?? throw new InvalidOperationException("You must call `ImportJavaScriptModuleAsync` method before accessing the JSModule property."); + + /// + /// Invoke the JavaScript runtime to import the JavaScript module. + /// + /// Name of the JavaScript file to import (e.g. JAVASCRIPT_ROOT + "Button/FluentButton.razor.js"). + /// + public async Task ImportJavaScriptModuleAsync(string file) + { + _jsModule ??= await JSRuntime.InvokeAsync("import", file); // TO ADD: .FormatCollocatedUrl(LibraryConfiguration) + return _jsModule; + } + + /// + /// Dispose the object. + /// + /// + /// + [ExcludeFromCodeCoverage] + public virtual async ValueTask DisposeAsync() + { + + await DisposeAsync(_jsModule); + + if (_jsModule != null) + { + try + { + await _jsModule.DisposeAsync(); + } + catch (Exception ex) when (ex is JSDisconnectedException || + ex is OperationCanceledException) + { + // The JSRuntime side may routinely be gone already if the reason we're disposing is that + // the client disconnected. This is not an error. + } + } + + GC.SuppressFinalize(this); + } + + /// + /// Dispose the object. + /// + /// + /// + [ExcludeFromCodeCoverage] + internal virtual ValueTask DisposeAsync(IJSObjectReference? jsModule) + { + return ValueTask.CompletedTask; + } +} + +#pragma warning restore MA0004 // Use Task.ConfigureAwait diff --git a/src/Core/Components/Base/IFluentComponentBase.cs b/src/Core/Components/Base/IFluentComponentBase.cs index 35124a8f1d..99a27c4c75 100644 --- a/src/Core/Components/Base/IFluentComponentBase.cs +++ b/src/Core/Components/Base/IFluentComponentBase.cs @@ -1,17 +1,19 @@ // ------------------------------------------------------------------------ // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------------------ + namespace Microsoft.FluentUI.AspNetCore.Components; /// -/// Base interface for Fluent UI Blazor components. +/// Base interface for FluentUI Blazor components. /// public interface IFluentComponentBase { /// - /// Gets or sets a collection of additional attributes that will be applied to the created element. + /// Gets or sets the unique identifier. + /// The value will be used as the HTML global id attribute. /// - IReadOnlyDictionary? AdditionalAttributes { get; set; } + string? Id { get; set; } /// /// Gets or sets the CSS class names. If given, these will be included in the class attribute of the component. @@ -19,18 +21,17 @@ public interface IFluentComponentBase string? Class { get; set; } /// - /// Gets or sets custom data. Used to attach any custom data object to the component. + /// Gets or sets the in-line styles. If given, these will be included in the style attribute of the component. /// - object? Data { get; set; } + string? Style { get; set; } /// - /// Gets or sets the unique identifier. - /// The value will be used as the HTML global id attribute. + /// Gets or sets custom data, to attach any user data object to the component. /// - string? Id { get; set; } + object? Data { get; set; } /// - /// Gets or sets the in-line styles. If given, these will be included in the style attribute of the component. + /// Gets or sets a collection of additional attributes that will be applied to the created element. /// - string? Style { get; set; } + IReadOnlyDictionary? AdditionalAttributes { get; set; } } diff --git a/src/Core/Components/Grid/FluentGrid.razor.cs b/src/Core/Components/Grid/FluentGrid.razor.cs index 129a3bc25f..88afe8299c 100644 --- a/src/Core/Components/Grid/FluentGrid.razor.cs +++ b/src/Core/Components/Grid/FluentGrid.razor.cs @@ -15,7 +15,7 @@ namespace Microsoft.FluentUI.AspNetCore.Components; /// public partial class FluentGrid : FluentComponentBase { - private const string JAVASCRIPT_FILE = JAVASCRIPT_ROOT + "Grid/FluentGrid.razor.js"; + private const string JAVASCRIPT_FILE = FluentJSModule.JAVASCRIPT_ROOT + "Grid/FluentGrid.razor.js"; /// /// Initializes a new instance of the class. @@ -74,7 +74,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender) if (firstRender && OnBreakpointEnter.HasDelegate) { // Import the JavaScript module - var jsModule = await ImportJavaScriptModuleAsync(JAVASCRIPT_FILE); + var jsModule = await JSModule.ImportJavaScriptModuleAsync(JAVASCRIPT_FILE); // Call a function from the JavaScript module var dotNetHelper = DotNetObjectReference.Create(this); diff --git a/src/Core/Components/TextInput/FluentTextInput.razor b/src/Core/Components/TextInput/FluentTextInput.razor index 0427cc9dd5..bba5363565 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -23,7 +23,7 @@ control-size="@Size.ToAttributeValue()" style="@StyleValue" type="@TextFieldType.ToAttributeValue()" - value="@Value" + value="@CurrentValueAsString" @onchange="@ChangeHandlerAsync" @oninput="@InputHandlerAsync" @attributes="AdditionalAttributes"> diff --git a/src/Core/Components/TextInput/FluentTextInput.razor.cs b/src/Core/Components/TextInput/FluentTextInput.razor.cs index f35876c590..d0947fefa3 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor.cs +++ b/src/Core/Components/TextInput/FluentTextInput.razor.cs @@ -13,7 +13,7 @@ namespace Microsoft.FluentUI.AspNetCore.Components; /// public partial class FluentTextInput : FluentInputImmediateBase, IFluentComponentElementBase { - private const string JAVASCRIPT_FILE = JAVASCRIPT_ROOT + "TextInput/FluentTextInput.razor.js"; + private const string JAVASCRIPT_FILE = FluentJSModule.JAVASCRIPT_ROOT + "TextInput/FluentTextInput.razor.js"; /// [Parameter] @@ -106,7 +106,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender) if (firstRender) { // Import the JavaScript module - var jsModule = await ImportJavaScriptModuleAsync(JAVASCRIPT_FILE); + var jsModule = await JSModule.ImportJavaScriptModuleAsync(JAVASCRIPT_FILE); // Call a function from the JavaScript module // Wait for this PR to delete the code: https://github.com/microsoft/fluentui/pull/33144 @@ -115,7 +115,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender) } /// - /// Parses a string to create the . + /// Parses a string to create the . /// /// The string value to be parsed. /// The result to inject into the Value. diff --git a/tests/Core/Components/Base/ComponentBaseTests.cs b/tests/Core/Components/Base/ComponentBaseTests.cs index 174b707047..cd158a3cad 100644 --- a/tests/Core/Components/Base/ComponentBaseTests.cs +++ b/tests/Core/Components/Base/ComponentBaseTests.cs @@ -142,6 +142,6 @@ public void ComponentBase_JsModule_Undefined() private class MyComponent : FluentGrid { public const string JAVASCRIPT_FILENAME = "FluentGrid.razor.js"; - public IJSObjectReference GetJSModule() => base.JSModule; + public IJSObjectReference GetJSModule() => base.JSModule.ObjectReference; } } From 26531c4433620c2b8409fcf4b62cb086364746da Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Fri, 15 Nov 2024 10:25:35 +0100 Subject: [PATCH 16/17] Refactoring --- .../DebugPages/EditFormPage.razor | 12 ++++++++++++ .../Documentation/Components/Lab/Examples/Test.razor | 9 --------- .../Documentation/Components/Lab/Experiments.md | 10 ---------- .../Microsoft.FluentUI.AspNetCore.Components.csproj | 8 ++++---- 4 files changed, 16 insertions(+), 23 deletions(-) create mode 100644 examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor delete mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor delete mode 100644 examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md diff --git a/examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor b/examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor new file mode 100644 index 0000000000..9c98579338 --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor @@ -0,0 +1,12 @@ +@page "/Debug/EditForm" + +

Just a simple page to do some experimenting

+ + + + +MyValue: @MyValue + +@code { + public string MyValue { get; set; } = "Test"; +} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor deleted file mode 100644 index 10b08e6690..0000000000 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Examples/Test.razor +++ /dev/null @@ -1,9 +0,0 @@ -

Test

- - - - - -@code { - public string test { get; set; } = "test"; -} diff --git a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md deleted file mode 100644 index aac05cc43e..0000000000 --- a/examples/Demo/FluentUI.Demo.Client/Documentation/Components/Lab/Experiments.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Lab -route: /Lab ---- - -# Lab -Just a simple page to do some experimenting - - -{{ Test }} diff --git a/src/Core/Microsoft.FluentUI.AspNetCore.Components.csproj b/src/Core/Microsoft.FluentUI.AspNetCore.Components.csproj index b1c2351628..bf3fd5328d 100644 --- a/src/Core/Microsoft.FluentUI.AspNetCore.Components.csproj +++ b/src/Core/Microsoft.FluentUI.AspNetCore.Components.csproj @@ -4,7 +4,7 @@ Microsoft.FluentUI.AspNetCore.Components A set of Blazor components wrapping Microsoft’s official Fluent UI Web Components. They implement the latest state of the Fluent design language, are built on FAST and work in every major browser. - Fluent UI, Blazor, Web Components, .NET8 + Fluent UI, Blazor, Web Components, .NET9 Microsoft Fluent UI Web Components for Blazor A set of Blazor components wrapping Microsoft’s official Fluent UI Web Components. They implement the latest state of the Fluent design language, are built on FAST and work in every major browser. README.md @@ -24,7 +24,7 @@ embedded $(SolutionDir)artifacts - + true false @@ -70,7 +70,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -89,7 +89,7 @@ - + From e86c92bb3db92a7cfad0c8291f7402ac2637dc00 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Fri, 15 Nov 2024 12:21:27 +0100 Subject: [PATCH 17/17] Add default ValueExpression --- .../FluentUI.Demo.Client/DebugPages/EditFormPage.razor | 2 +- src/Core/Components/Base/FluentInputBase.cs | 2 +- src/Core/Components/TextInput/FluentTextInput.razor.cs | 8 ++++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor b/examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor index 9c98579338..f8d9baa385 100644 --- a/examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor +++ b/examples/Demo/FluentUI.Demo.Client/DebugPages/EditFormPage.razor @@ -3,7 +3,7 @@

Just a simple page to do some experimenting

- + MyValue: @MyValue diff --git a/src/Core/Components/Base/FluentInputBase.cs b/src/Core/Components/Base/FluentInputBase.cs index 32daba9ec3..8bab2925fb 100644 --- a/src/Core/Components/Base/FluentInputBase.cs +++ b/src/Core/Components/Base/FluentInputBase.cs @@ -126,7 +126,7 @@ protected virtual Task ChangeHandlerAsync(ChangeEventArgs e) if (isValid) { - Value = result; + CurrentValue = result; } else { diff --git a/src/Core/Components/TextInput/FluentTextInput.razor.cs b/src/Core/Components/TextInput/FluentTextInput.razor.cs index d0947fefa3..28c4b08f4d 100644 --- a/src/Core/Components/TextInput/FluentTextInput.razor.cs +++ b/src/Core/Components/TextInput/FluentTextInput.razor.cs @@ -15,6 +15,14 @@ public partial class FluentTextInput : FluentInputImmediateBase, IFluen { private const string JAVASCRIPT_FILE = FluentJSModule.JAVASCRIPT_ROOT + "TextInput/FluentTextInput.razor.js"; + /// + /// Initializes a new instance of the class. + /// + public FluentTextInput() + { + ValueExpression = () => Value; + } + /// [Parameter] public ElementReference Element { get; set; }