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..f8d9baa385 --- /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/TextInput/Examples/TextInputAppearances.razor b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor new file mode 100644 index 0000000000..cb94144ec7 --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputAppearances.razor @@ -0,0 +1,21 @@ +
+ + + + +
+ +
+ + + +
+ +
+ Value = @Value +
+ +@code +{ + 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..c7aa76906a --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputImmediate.razor @@ -0,0 +1,17 @@ +
+ +
+ +
+ Value = @Value +
+ +@code +{ + string 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..200dffb81c --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/Examples/TextInputPrefixSuffix.razor @@ -0,0 +1,21 @@ +
+ + + https:// + + + .com + + + + + + + + +
+ +@code { + private string _sometext1 = "microsoft"; + private string _sometext2 = "fluentui-blazor@microsoft.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 new file mode 100644 index 0000000000..f5206e17fe --- /dev/null +++ b/examples/Demo/FluentUI.Demo.Client/Documentation/Components/TextInput/FluentTextInput.md @@ -0,0 +1,58 @@ +--- +title: TextInput +route: /TextInput +--- + +# TextInput + +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.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/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/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) 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/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 new file mode 100644 index 0000000000..8bab2925fb --- /dev/null +++ b/src/Core/Components/Base/FluentInputBase.cs @@ -0,0 +1,140 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.JSInterop; +using Microsoft.FluentUI.AspNetCore.Components.Utilities; + +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 : InputBase, IFluentComponentBase +{ + private FluentJSModule? _jsModule; + + /// + [Inject] + private 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. + /// + 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 + + #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 => 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. + /// + 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 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; } + + /// + /// + /// + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "TODO")] + protected virtual Task ChangeHandlerAsync(ChangeEventArgs e) + { + var isValid = TryParseValueFromString(e.Value?.ToString(), out var result, out var validationErrorMessage); + + if (isValid) + { + CurrentValue = result; + } + else + { + // TODO + } + + return Task.CompletedTask; + } + + #endregion +} diff --git a/src/Core/Components/Base/FluentInputImmediateBase.cs b/src/Core/Components/Base/FluentInputImmediateBase.cs new file mode 100644 index 0000000000..02213de2ad --- /dev/null +++ b/src/Core/Components/Base/FluentInputImmediateBase.cs @@ -0,0 +1,67 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; +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); + } + } + + /// + [ExcludeFromCodeCoverage()] + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + _debounce.Dispose(); + } + } +} 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/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; } } 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/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 new file mode 100644 index 0000000000..bba5363565 --- /dev/null +++ b/src/Core/Components/TextInput/FluentTextInput.razor @@ -0,0 +1,52 @@ +@namespace Microsoft.FluentUI.AspNetCore.Components +@using Microsoft.FluentUI.AspNetCore.Components.Extensions +@inherits FluentInputImmediateBase + + + @if (!string.IsNullOrEmpty(Label) || LabelTemplate != null) + { + + @Label + @LabelTemplate + + } + + @if (StartTemplate != null) + { +
+ @StartTemplate +
+ } + + @if (EndTemplate != null) + { +
+ @EndTemplate +
+ } + +
diff --git a/src/Core/Components/TextInput/FluentTextInput.razor.cs b/src/Core/Components/TextInput/FluentTextInput.razor.cs new file mode 100644 index 0000000000..28c4b08f4d --- /dev/null +++ b/src/Core/Components/TextInput/FluentTextInput.razor.cs @@ -0,0 +1,138 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Components; +using Microsoft.JSInterop; + +namespace Microsoft.FluentUI.AspNetCore.Components; + +/// +/// A text input component that allows users to enter and edit a single line of text. +/// +public partial class FluentTextInput : FluentInputImmediateBase, IFluentComponentElementBase +{ + 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; } + + /// + /// 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 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 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 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 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 + await jsModule.InvokeVoidAsync("Microsoft.FluentUI.Blazor.TextInput.ObserveAttributeChanges", Element); + } + } + + /// + /// 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; + validationErrorMessage = null; + return true; + } +} 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 }); + } + +} 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/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 +} 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 @@ - + 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 + } +} 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); } } } 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..cd158a3cad 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,18 @@ 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()) + JSInterop.Mode = JSRuntimeMode.Loose; + + 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 +82,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) { @@ -129,19 +142,6 @@ public void ComponentBase_JsModule_Undefined() 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)); + public IJSObjectReference GetJSModule() => base.JSModule.ObjectReference; } } diff --git a/tests/Core/Components/Base/InputBaseTests.cs b/tests/Core/Components/Base/InputBaseTests.cs new file mode 100644 index 0000000000..cbd715fc02 --- /dev/null +++ b/tests/Core/Components/Base/InputBaseTests.cs @@ -0,0 +1,104 @@ +// ------------------------------------------------------------------------ +// 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)] + [InlineData("Label", "", "my-label")] + public void InputBase_DefaultProperties(string propName, string htmlName, object value) + { + 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 + 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 = string.IsNullOrEmpty(htmlName) + ? renderedComponent.Markup.Contains(value.ToString() ?? "") + : 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()); + } +} diff --git a/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_Default.verified.razor.html b/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_Default.verified.razor.html new file mode 100644 index 0000000000..c8fac4b080 --- /dev/null +++ b/tests/Core/Components/TextInput/FluentTextInputTests.FluentInputText_Default.verified.razor.html @@ -0,0 +1,5 @@ + + + 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..5f555c3116 --- /dev/null +++ b/tests/Core/Components/TextInput/FluentTextInputTests.razor @@ -0,0 +1,169 @@ +@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 + +@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($""); + } + + [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); + } +}