diff --git a/docs/guides/static-edit-form.md b/docs/guides/static-edit-form.md new file mode 100644 index 0000000..f938554 --- /dev/null +++ b/docs/guides/static-edit-form.md @@ -0,0 +1,59 @@ +# Submit and validate a native Blazor form + +The gallery's `form-post` page uses the library controls in one named `EditForm`. It is an in-memory draft, not a settings endpoint. Run the gallery from the repository root: + +```powershell +dotnet run --project gallery/Gallery --no-launch-profile --urls http://127.0.0.1:0 +``` + +Open the printed address at `/static/form-post`; the same form is available at `/server/form-post` and `/wasm/form-post`. The fixture uses the field, text input, text area, number, select, checkbox, radio group, switch, segmented, date and time controls. + +## The form and its names + +1. Give `EditForm` a `FormName` and register the same name on the model's `[SupplyParameterFromForm]`. Leave Blazor's antiforgery protection enabled. A named `EditForm` renders its token; a plain host form needs its own `AntiforgeryToken`. +2. Keep the **posted** model through validation. Seed initial sample values only when no model was supplied, then construct the `EditContext`. `ShouldUseFieldIdentifiers = true` opts this form into framework-derived names in both server and WASM renderers. +3. Use `DataAnnotationsValidator` and the host's data rules. The controls bind through `InputBase`; they do not supply a validator. + +| In the fixture | Native wire name | What the host receives | +| --- | --- | --- | +| Draft title | `Model.Title` | Top-level string. | +| City | `Model.Address.City` | Value on the nested address. | +| Two tags | `Model.Tags[0]`, `Model.Tags[1]` | Two distinct array slots. | +| Support alias | `support_alias` | Host override backed by `[SupplyParameterFromForm(FormName = "integration-draft", Name = "support_alias")]`. | +| Segmented review mode | `Model.ReviewMode` | One selected native radio value. The disabled middle option is skipped by native arrow navigation and is not submitted. | +| Audience radio group | `Model.Audience` | One choice, independent of the segmented review mode. | +| Checked notification checkbox | `Model.NotifyOwners=true` | One Boolean value. | +| Unchecked digest switch and disabled notice checkbox | No entries | Neither `Model.DailyDigest` nor `Model.LockedNotice` is posted. There is no hidden value to substitute for an unchecked or disabled control. | +| Delivery window | `Model.Start`, `Model.End` | Two native date fields, not one range value. | +| Empty quiet time | `Model.QuietTime=` | An empty wire string, mapped to `null` for `TimeOnly?`. | +| Disabled reference | No entry | An absent key, not an empty string. A disabled control is not a security boundary; enforce access in the host. | + +An explicit `name` wins, including from an attribute dictionary. Keep the receiving property in sync with it. For normal binding use `@bind-Value`; if you supply `Value` and `ValueChanged` separately, also supply the expression the framework uses for field identity: + +```razor + + +@code { + [SupplyParameterFromForm(FormName = "integration-draft", Name = "support_alias")] + private string? Alias { get; set; } + + private void SetAlias(string? value) => Alias = value; +} +``` + +## Verify the browser and the server separately + +- Disable JavaScript in the browser, enter 18 seats, and choose an end date earlier than the start date. Tab from Language into the selected **Personal** review mode and press Right Arrow to skip disabled **Owners only** and choose **Shared**. Tab to **Authors** in the separate audience group and press Right Arrow to reach **Everyone**. Check **Notify owners** and turn **Daily digest** off. **Save draft** sends one value per radio group and one checked Boolean value. `18` is a valid number within the browser's range of 1–100, but the host rejects it with the rule allowing 1–12. The date group owns its error once, before its help and external description. The inputs keep their edits and selections. Correct the two errors and save again; the result lists what the handler received. +- A malformed number is a different case. A native number input can reject or clear the text before any request. The focused bUnit test submits malformed text to the real component binder and checks the framework's parsing message and unchanged bound value. It is not evidence that a malformed number reached the server in a browser POST. +- Clear the title and use **Check on server** to bypass native required validation and see the host's top-level error. Clear only City and save: the default submit validator does not recursively validate the address. **Include the city in submit validation** opens a fresh draft in JavaScript-disabled static rendering. In Server and WASM, the link changes the rule without discarding the draft; **Use default validation** removes the message owned by the optional city check. The opt-in uses the same `RequiredAttribute` rule and an `EditContext` message store for that one field, not a new library validator or a generic object walker. +- In Server and WASM, edit the start, leave it, and check that the draft dates show the new start and the old end. Then edit and leave the end. The date readout comes from the bound model; the change indicator comes from `EditContext.OnFieldChanged`. Save with the reversed dates to see the group error, then correct the end. The save handler reads the existing model, so a disabled field can retain an in-memory value even though a native POST would omit it. The first interactive render preserves the routing and field wiring, but the sample does not promise to retain focus or an uncommitted edit across takeover. + +**Windows Playwright WebKit limitation.** This build shows these date and time inputs as text fields. In interactive modes, .NET 10 Blazor sees the declared temporal type but cannot serialize the change for the effective `text` type (`Invalid element type 'text'.`). The edit stays visible without reaching the bound model; the framework's own `InputDate` has the same behavior on this build. JavaScript-disabled document POSTs still send the entered strings. The fixture keeps the real binding path with no script workaround. This build is not Safari; see [ADR 0003](../decisions/0003-script-policy.md#what-could-not-be-checked). + +```powershell +dotnet test --project tests/FluentCMS.Components.Tests --filter-class '*FormPostBoundaryTests' +dotnet test --project tests/FluentCMS.Components.Browser --filter-class 'FluentCMS.Components.Browser.Forms.FormPost*' +``` + +The first command checks the parsing boundary; the second drives the actual gallery, including a JavaScript-disabled document POST with antiforgery. See [ADR 0004](../decisions/0004-forms-model.md) for the library's binding contract. diff --git a/gallery/Gallery.Client/GalleryPages.cs b/gallery/Gallery.Client/GalleryPages.cs index 569f2e0..37a779b 100644 --- a/gallery/Gallery.Client/GalleryPages.cs +++ b/gallery/Gallery.Client/GalleryPages.cs @@ -22,6 +22,7 @@ public static class GalleryPages new("choices", "Checkbox, radio and switch"), new("segmented", "Segmented"), new("date-time", "Date and time"), + new("form-post", "Form submission"), new("tokens", "Tokens"), new("theme-provider", "Theme provider"), new("patterns", "Patterns"), diff --git a/gallery/Gallery.Client/Pages/FormPost.razor b/gallery/Gallery.Client/Pages/FormPost.razor new file mode 100644 index 0000000..7601c93 --- /dev/null +++ b/gallery/Gallery.Client/Pages/FormPost.razor @@ -0,0 +1,255 @@ +@page "/form-post" +@implements IDisposable +@using System.ComponentModel.DataAnnotations +@using System.Globalization +@using FluentCMS.Components +@using Microsoft.AspNetCore.Components.Forms + + + Save a draft with the browser's form submission or with interactive Blazor. This example keeps only in-memory sample data. + +
+

Save posts this named form. The sample allows up to 12 seats even though the number input accepts up to 100. If the host rejects a value, correct it and save again without re-entering the other fields.

+

@(CheckCity ? "The host also validates the nested city on submit." : "The default submit validator checks the top-level draft, not the nested city.") + @(CheckCity ? "Use default validation" : "Include the city in submit validation")

+ @if (_saved is not null) + { + +
+ @foreach (var value in _saved) + { +
@value.Label
@value.Text
+ } +
+ } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+

Dates are local to the workspace.

+ + + + + + + + + +

Changes: @_changes. Latest field: @_lastChanged.

+

Draft dates: @DateText(Model!.Start) to @DateText(Model.End). + Quiet time: @TimeText(Model.QuietTime).

+
+ Save draft + Check on server +
+
+
+

The review mode and audience each submit one choice. A checked checkbox submits true; unchecked or disabled toggles are omitted.

+
+ +
+

@@bind-Value supplies the expression for you. If you set Value and ValueChanged yourself, you must also give ValueExpression. The form receiver must use the same name as an explicit name override.

+ +
+
+ +@code { + private const string CityRequired = "Enter a city to use the nested check."; + private static readonly FlSelectOption[] Languages = [new("en", "English"), new("fr", "French")]; + private static readonly FlSegmentedOption[] ReviewModes = [new("personal", "Personal"), new("owners", "Owners only") { Disabled = true }, new("shared", "Shared")]; + private static readonly FlRadioOption[] Audiences = [new("authors", "Authors"), new("owners", "Owners only") { Disabled = true }, new("everyone", "Everyone")]; + private static readonly IReadOnlyDictionary AliasAttributes = new Dictionary { ["id"] = "integration-alias", ["NAME"] = "support_alias" }; + private static readonly RequiredAttribute CityRule = new(); + + [CascadingParameter] private GalleryContext Context { get; set; } = default!; + [SupplyParameterFromQuery(Name = "validate-city")] private bool CheckCity { get; set; } + [SupplyParameterFromForm(FormName = "integration-draft")] + private DraftSettings? Model { get; set; } + [SupplyParameterFromForm(FormName = "integration-draft", Name = "support_alias")] + private string? Alias { get; set; } + + private EditContext _editContext = default!; + private ValidationMessageStore _cityMessages = default!; + private (string Key, string Label, string Text)[]? _saved; + private int _changes; + private string _lastChanged = "(none)"; + + private string CityValidationHref => CheckCity ? Context.Href("form-post", "form") + : Context.Href("form-post") + (Context.Settings.Query.Length == 0 ? "?" : "&") + "validate-city=true#form"; + private FieldIdentifier CityField => new(Model!.Address, nameof(AddressDraft.City)); + + protected override void OnInitialized() + { + if (Model is null) + { + Model = new DraftSettings + { + Title = "Workspace handbook", Address = new AddressDraft { City = "Harbor" }, Tags = ["guide", "draft"], + Notes = "A short draft.", Seats = 6, Language = "en", ReviewMode = "personal", Start = new DateOnly(2026, 11, 24), + End = new DateOnly(2026, 11, 25), QuietTime = new TimeOnly(9, 15, 30), LockedReference = "Managed by the host", + Audience = "authors", DailyDigest = true, LockedNotice = true, + }; + Alias = "settings-help"; + } + if (Model.Tags.Length < 2) + { + // Both slots remain editable even when a submitted form omits an index. + string?[] tags = Model.Tags; + Array.Resize(ref tags, 2); + Model.Tags = tags; + } + _editContext = new EditContext(Model) { ShouldUseFieldIdentifiers = true }; + _cityMessages = new ValidationMessageStore(_editContext); + _editContext.OnFieldChanged += OnFieldChanged; + _editContext.OnValidationRequested += ValidateCity; + } + + protected override void OnParametersSet() + { + // A query-only link can keep this page and its EditContext alive. + if (!CheckCity && _cityMessages[CityField].Any()) + { + _cityMessages.Clear(); + _editContext.NotifyValidationStateChanged(); + } + } + + private void SetAlias(string? value) => Alias = value; + + private void OnFieldChanged(object? sender, FieldChangedEventArgs args) + { + _changes++; + _lastChanged = args.FieldIdentifier.FieldName; + StateHasChanged(); + } + + private void ValidateCity(object? sender, ValidationRequestedEventArgs args) + { + _cityMessages.Clear(); + if (CheckCity && !CityRule.IsValid(Model!.Address.City)) + { + _cityMessages.Add(CityField, CityRequired); + } + } + + private void Save() + { + DraftSettings result = Model!; + _saved = + [ + ("title", "Draft title", Display(result.Title)), ("city", "City", Display(result.Address.City)), + ("tag-zero", "First tag", Display(result.Tags[0])), ("tag-one", "Second tag", Display(result.Tags[1])), + ("notes", "Draft notes", Display(result.Notes)), ("seats", "Seats", result.Seats.ToString(CultureInfo.InvariantCulture)), + ("language", "Language", Display(result.Language)), ("review", "Review mode", Display(result.ReviewMode)), + ("audience", "Audience", Display(result.Audience)), ("notify", "Notify owners", OnOff(result.NotifyOwners)), + ("digest", "Daily digest", OnOff(result.DailyDigest)), ("locked-notice", "Required notice", OnOff(result.LockedNotice)), + ("alias", "Support alias", Display(Alias)), + ("start", "Start date", DateText(result.Start)), ("end", "End date", DateText(result.End)), + ("quiet", "Quiet time", TimeText(result.QuietTime)), + ("locked", "Locked reference", result.LockedReference ?? "(not sent)"), + ]; + } + + private void NotSaved() => _saved = null; + + private static string Display(string? text) => string.IsNullOrEmpty(text) ? "(empty)" : text; + + private static string DateText(DateOnly? date) => Display(date?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); + + private static string TimeText(TimeOnly? time) => Display(time?.ToString("HH:mm:ss", CultureInfo.InvariantCulture)); + + private static string OnOff(bool value) => value ? "on" : "off"; + + public void Dispose() + { + _editContext.OnFieldChanged -= OnFieldChanged; + _editContext.OnValidationRequested -= ValidateCity; + } + + private sealed class AddressDraft + { + [Required(ErrorMessage = CityRequired)] + public string? City { get; set; } + } + + private sealed class DraftSettings : IValidatableObject + { + [Required(ErrorMessage = "Enter a draft title.")] + public string? Title { get; set; } + public AddressDraft Address { get; set; } = new(); + public string?[] Tags { get; set; } = []; + public string? Notes { get; set; } + public int Seats { get; set; } + public string? Language { get; set; } + public string? ReviewMode { get; set; } + public string? Audience { get; set; } + public bool NotifyOwners { get; set; } + public bool DailyDigest { get; set; } + public bool LockedNotice { get; set; } + public DateOnly? Start { get; set; } + public DateOnly? End { get; set; } + public TimeOnly? QuietTime { get; set; } + public string? LockedReference { get; set; } + + public IEnumerable Validate(ValidationContext validationContext) + { + if (Seats is < 1 or > 12) + { + yield return new ValidationResult("Choose between 1 and 12 seats for this draft.", [nameof(Seats)]); + } + if (End < Start) + { + yield return new ValidationResult("Choose an end date on or after the start date.", [nameof(Start), nameof(End)]); + } + } + } + + private const string ManualCode = """ + + + @code { + [SupplyParameterFromForm(FormName = "integration-draft", Name = "support_alias")] + private string? Alias { get; set; } + + private void SetAlias(string? value) => Alias = value; + } + """; +} diff --git a/src/FluentCMS.Components/Forms/FlField.razor b/src/FluentCMS.Components/Forms/FlField.razor index 2545d57..0a6fc50 100644 --- a/src/FluentCMS.Components/Forms/FlField.razor +++ b/src/FluentCMS.Components/Forms/FlField.razor @@ -1,5 +1,8 @@ @namespace FluentCMS.Components +@{ + _renderedError = _context.ErrorText; +}
@if (_context.IsGroup) @@ -11,7 +14,7 @@ } @ChildContent - @if (_context.ErrorText is { } error) + @if (_renderedError is { } error) {

@error

} diff --git a/src/FluentCMS.Components/Forms/FlField.razor.cs b/src/FluentCMS.Components/Forms/FlField.razor.cs index fe2fd7a..b73ba84 100644 --- a/src/FluentCMS.Components/Forms/FlField.razor.cs +++ b/src/FluentCMS.Components/Forms/FlField.razor.cs @@ -25,6 +25,7 @@ public sealed partial class FlField : IDisposable private readonly FlFieldContext _context; private EditContext? _subscribed; private string _rendered = ""; + private string? _renderedError; private bool _disposed; public FlField() => _context = new FlFieldContext(this); @@ -97,7 +98,14 @@ internal void Refresh() private string Snapshot() => string.Join("|", _context.Controls.Select(control => $"{control.Id}:{control.GroupRole}:{control.MaxLength}:{control.Length}:{control.GroupRequired}:{control.GroupDescription}")); - private void OnValidationStateChanged(object? sender, ValidationStateChangedEventArgs e) => StateHasChanged(); + private void OnValidationStateChanged(object? sender, ValidationStateChangedEventArgs e) + { + // The inputs update their own validation state. An unchanged field error need not replay the child content. + if (!_disposed && !string.Equals(_renderedError, _context.ErrorText, StringComparison.Ordinal)) + { + StateHasChanged(); + } + } void IDisposable.Dispose() { diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs new file mode 100644 index 0000000..3bc0d8d --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs @@ -0,0 +1,98 @@ +using FluentCMS.Components.Browser.Harness; +using Microsoft.Playwright; +using static Microsoft.Playwright.Assertions; + +namespace FluentCMS.Components.Browser.Forms; + +public sealed class FormPostPrerenderTests(GalleryFixture gallery) +{ + [Theory] + [ModeData(RenderMode.Server, RenderMode.Wasm)] + public async Task FirstInteractiveFormKeepsComponentOwnedFieldsAndNames(RenderMode mode) + { + await using GalleryPage sample = await gallery.OpenBlankAsync(""); + IPage page = sample.Page; + var intercepted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var resume = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await page.RouteAsync("**/_framework/blazor.web*.js", async route => + { + intercepted.TrySetResult(); + await resume.Task; + await route.ContinueAsync(); + }); + + string[] before; + ILocator main = page.Locator($"main[data-render-mode='{mode.Segment()}']"); + try + { + var address = new Uri(gallery.BaseAddress, $"{mode.Segment()}/form-post?theme=dark&density=compact&dir=rtl"); + Assert.True((await page.GotoAsync(address.AbsoluteUri, new() { WaitUntil = WaitUntilState.Commit }))?.Ok); + await intercepted.Task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken); + await Expect(main).ToHaveAttributeAsync("data-interactive", "false"); + await Expect(page.Locator("#integration-locked")).ToBeAttachedAsync(); + await FieldIdentity.AssertAsync(page); + before = await main.EvaluateAsync(""" + main => { + const fields = root => [...root.querySelectorAll('#integration-form :is(.fl-field, .fl-checkbox, .fl-switch)')]; + const capture = root => fields(root).map(el => { + const copy = el.cloneNode(true); + const walker = document.createTreeWalker(copy, NodeFilter.SHOW_COMMENT); + const comments = []; + while (walker.nextNode()) if (walker.currentNode.data === '!') comments.push(walker.currentNode); + comments.forEach(node => node.remove()); + const originals = [...el.querySelectorAll('input, textarea, select')]; + [...copy.querySelectorAll('input, textarea, select')].forEach((input, i) => { + input.removeAttribute('value'); + input.setAttribute('data-live-value', originals[i].value); + if (input.type === 'radio' || input.type === 'checkbox') { + input.removeAttribute('checked'); + input.setAttribute('data-live-checked', originals[i].checked); + } + // Form controls expose value as a property; textarea's prerendered text is only its serialization. + if (input.localName === 'textarea') input.textContent = ''; + // The framework captures InputNumber.Element with an interactive-only reference marker. + if (input.type === 'number') { + for (const attr of [...input.attributes]) if (attr.name.startsWith('_bl_')) input.removeAttribute(attr.name); + } + }); + for (const node of [copy, ...copy.querySelectorAll('*')]) { + const attributes = [...node.attributes].map(a => [a.name, a.value]).sort(); + for (const [name] of attributes) node.removeAttribute(name); + for (const [name, value] of attributes) node.setAttribute(name, value); + } + return copy.outerHTML; + }); + const originals = fields(main).flatMap(el => [el, ...el.querySelectorAll('*')]); + window.firstInteractiveFormPost = new Promise(resolve => { + const observer = new MutationObserver(() => { + const interactive = document.querySelector('main[data-interactive="true"]'); + if (!interactive) return; + observer.disconnect(); + resolve({replaced: originals.every(el => !el.isConnected), markup: capture(interactive)}); + }); + observer.observe(document.body, {subtree: true, childList: true, attributes: true}); + }); + return capture(main); + } + """); + } + finally + { + resume.TrySetResult(); + } + + Assert.Equal(16, before.Length); + await Expect(main).ToHaveAttributeAsync("data-interactive", "true", new() { Timeout = 30000 }); + Assert.True(await page.EvaluateAsync("async () => (await window.firstInteractiveFormPost).replaced")); + Assert.Equal(before, await page.EvaluateAsync("async () => (await window.firstInteractiveFormPost).markup")); + await Expect(page.Locator("#integration-tag-one")).ToHaveAttributeAsync("name", "Model.Tags[1]"); + await Expect(page.Locator("#integration-alias")).ToHaveAttributeAsync("name", "support_alias"); + await Expect(page.Locator("#integration-review input[name='Model.ReviewMode']")).ToHaveCountAsync(3); + await Expect(page.Locator("#integration-review input[value=personal]")).ToBeCheckedAsync(); + await Expect(page.Locator("#integration-audience input[name='Model.Audience']")).ToHaveCountAsync(3); + await Expect(page.Locator("#integration-audience input[value=authors]")).ToBeCheckedAsync(); + await Expect(page.Locator("#integration-notify")).ToHaveAttributeAsync("name", "Model.NotifyOwners"); + await Expect(page.Locator("#integration-digest")).ToBeCheckedAsync(); + await FieldIdentity.AssertAsync(page); + } +} diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs new file mode 100644 index 0000000..39e5ae1 --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -0,0 +1,474 @@ +using System.Collections.Specialized; +using System.Globalization; +using System.Web; +using FluentCMS.Components.Browser.Harness; +using Microsoft.Playwright; +using static Microsoft.Playwright.Assertions; + +namespace FluentCMS.Components.Browser.Forms; + +public sealed class FormPostTests(GalleryFixture gallery) +{ + private const string Path = "form-post"; + private const string FormName = "integration-draft"; + private const string EditedStart = "2026-12-03"; + private const string EditedEnd = "2026-12-01"; + private const string CorrectedEnd = "2026-12-04"; + private static readonly (string Id, string Name, string Value)[] DraftEdits = + [ + ("title", "Model.Title", "Team handbook"), + ("city", "Model.Address.City", "Riverside"), + ("tag-zero", "Model.Tags[0]", "team guide"), + ("tag-one", "Model.Tags[1]", "release notes"), + ("notes", "Model.Notes", "Review & publish"), + ("seats", "Model.Seats", "18"), + ("language", "Model.Language", "fr"), + ("start", "Model.Start", EditedStart), + ("end", "Model.End", EditedEnd), + ("quiet", "Model.QuietTime", ""), + ("alias", "support_alias", "draft-help"), + ]; + + [Theory] + [ModeData(RenderMode.Static)] + public async Task NativePostPreservesValuesAfterValidationAndSavesCorrected(RenderMode mode) + { + await using IBrowserContext context = await gallery.Browser.NewContextAsync(new() { JavaScriptEnabled = false }); + IPage page = await OpenStaticAsync(context, mode); + await EditDraftAsync(page, mode); + await EditInitialDatesAsync(page, mode); + await Expect(page.Locator("#integration-locked")).ToBeDisabledAsync(); + Assert.True(await page.Locator("#integration-seats").EvaluateAsync("el => el.validity.valid"), + "The numeric value must be valid in the browser so that this test reaches host validation."); + + NameValueCollection first = await PostAsync(page, "#integration-save"); + AssertWire(first); + await AssertInvalidDraftAsync(page); + await AssertReturnedControlsAsync(page); + await AssertSharedReviewModeAsync(page); + await AssertNativeChoicesAsync(page); + + await CorrectDraftAsync(page, mode); + NameValueCollection corrected = await PostAsync(page, "#integration-save"); + AssertWire(corrected, successful: true); + await AssertSavedDraftAsync(page, mode); + await AssertReturnedControlsAsync(page, successful: true); + await AssertSharedReviewModeAsync(page); + await AssertNativeChoicesAsync(page); + await FieldIdentity.AssertAsync(page); + } + + [Theory] + [ModeData(RenderMode.Static)] + public async Task TopLevelValidationDoesNotImplyNestedValidation(RenderMode mode) + { + await using IBrowserContext context = await gallery.Browser.NewContextAsync(new() { JavaScriptEnabled = false }); + IPage page = await OpenStaticAsync(context, mode); + await page.Locator("#integration-title").FillAsync(""); + await page.Locator("#integration-city").FillAsync(""); + var empty = await PostAsync(page, "#integration-check"); + AssertWireValue(empty, "Model.Title", ""); + AssertWireValue(empty, "Model.Address.City", ""); + await Expect(page.Locator("#integration-title__error")).ToHaveTextAsync("Enter a draft title."); + await Expect(page.Locator("#integration-city__error")).ToHaveCountAsync(0); + + await page.Locator("#integration-title").FillAsync("Guide without a city"); + await PostAsync(page, "#integration-save"); + await Expect(page.Locator("#integration-result-city")).ToHaveTextAsync("(empty)"); + await Expect(page.Locator("#integration-saved")).ToBeVisibleAsync(); + + page = await OpenStaticAsync(context, mode, "?validate-city=true"); + await page.Locator("#integration-city").FillAsync(""); + var nested = await PostAsync(page, "#integration-save"); + AssertWireValue(nested, "Model.Address.City", ""); + await Expect(page.Locator("#integration-city__error")).ToHaveTextAsync("Enter a city to use the nested check."); + Assert.Contains("validate-city=true", page.Url, StringComparison.Ordinal); + await Expect(page.Locator("#integration-city")).ToHaveAttributeAsync("aria-describedby", "integration-city__error integration-city__help"); + await Expect(page.Locator("#integration-saved")).ToHaveCountAsync(0); + await page.Locator("#integration-city").FillAsync("Riverside"); + await PostAsync(page, "#integration-save"); + await Expect(page.Locator("#integration-result-city")).ToHaveTextAsync("Riverside"); + await FieldIdentity.AssertAsync(page); + } + + [Theory] + [ModeData(RenderMode.Server, RenderMode.Wasm)] + public async Task NestedCityValidationFollowsInteractiveLinksWithoutResettingTheDraft(RenderMode mode) + { + const string title = "Retain this edited draft title"; + const string cityError = "Enter a city to use the nested check."; + const string include = "Include the city in submit validation"; + const string exclude = "Use default validation"; + await using GalleryPage sample = await gallery.OpenAsync(mode, Path); + IPage page = sample.Page; + ILocator city = page.Locator("#integration-city"); + ILocator error = page.Locator("#integration-city__error"); + ILocator changes = page.Locator("#integration-change-count"); + int edits = 0; + + async Task EditAsync(string id, string field, string value) + { + ILocator input = page.Locator($"#integration-{id}"); + await input.FillAsync(value); + await input.PressAsync("Tab"); + await Expect(changes).ToHaveTextAsync((++edits).ToString(CultureInfo.InvariantCulture)); + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync(field); + } + + async Task ToggleAsync(string link, string nextLink, string address) + { + await page.GetByRole(AriaRole.Link, new() { Name = link, Exact = true }).ClickAsync(); + await Expect(page.GetByRole(AriaRole.Link, new() { Name = nextLink, Exact = true })).ToBeVisibleAsync(); + await Expect(page).ToHaveURLAsync(new Uri(gallery.BaseAddress, $"{mode.Segment()}/{Path}{address}").AbsoluteUri); + await Expect(page.Locator("#integration-title")).ToHaveValueAsync(title); + await Expect(city).ToHaveValueAsync(""); + await Expect(changes).ToHaveTextAsync(edits.ToString(CultureInfo.InvariantCulture)); + } + + await EditAsync("title", "Title", title); + await EditAsync("city", "City", ""); + await ToggleAsync(include, exclude, "?validate-city=true#form"); + await EditAsync("seats", "Seats", "18"); + await ClickSaveAsync(page); + // Seats is valid in HTML. Its fresh host error proves this Save ran validation, not just field-edit validation. + ILocator seatsError = page.Locator("#integration-seats__error"); + await Expect(seatsError).ToHaveTextAsync("Choose between 1 and 12 seats for this draft."); + await Expect(error).ToHaveTextAsync(cityError); + await Expect(city).ToHaveAttributeAsync("aria-describedby", "integration-city__error integration-city__help"); + await Expect(page.Locator("#integration-saved")).ToHaveCountAsync(0); + + await ToggleAsync(exclude, include, "#form"); + await Expect(error).ToHaveCountAsync(0); + await Expect(city).ToHaveAttributeAsync("aria-describedby", "integration-city__help"); + Assert.Null(await city.GetAttributeAsync("aria-invalid")); + await Expect(seatsError).ToHaveTextAsync("Choose between 1 and 12 seats for this draft."); + await EditAsync("seats", "Seats", "8"); + await ClickSaveAsync(page); + await Expect(page.Locator("#integration-result-city")).ToHaveTextAsync("(empty)"); + await Expect(page.Locator("#integration-result-title")).ToHaveTextAsync(title); + await Expect(page.Locator("#integration-result-seats")).ToHaveTextAsync("8"); + + await ToggleAsync(include, exclude, "?validate-city=true#form"); + await ClickSaveAsync(page); + await Expect(error).ToHaveCountAsync(1); + await Expect(error).ToHaveTextAsync(cityError); + await Expect(page.Locator("#integration-saved")).ToHaveCountAsync(0); + await EditAsync("city", "City", "Riverside"); + await ClickSaveAsync(page); + await Expect(page.Locator("#integration-result-city")).ToHaveTextAsync("Riverside"); + await Expect(page.Locator("#integration-result-title")).ToHaveTextAsync(title); + await Expect(error).ToHaveCountAsync(0); + await FieldIdentity.AssertAsync(page); + } + + [Theory] + [ModeData(RenderMode.Server, RenderMode.Wasm)] + public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(RenderMode mode) + { + await using GalleryPage sample = await gallery.OpenAsync(mode, Path); + IPage page = sample.Page; + await page.Locator("#integration-title").FillAsync("Team handbook"); + await page.Locator("#integration-title").PressAsync("Tab"); + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("Title"); + await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("1"); + await page.Locator("#integration-language").SelectOptionAsync("fr"); + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("Language"); + await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("2"); + + await EditDraftAsync(page, mode); + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("Audience"); + await EditInitialDatesAsync(page, mode); + var address = new Uri(page.Url); + await ClickSaveAsync(page); + await AssertInvalidDraftAsync(page); + await AssertReturnedControlsAsync(page); + await AssertSharedReviewModeAsync(page); + await AssertNativeChoicesAsync(page); + await CorrectDraftAsync(page, mode); + await ClickSaveAsync(page); + await AssertSavedDraftAsync(page, mode); + await AssertReturnedControlsAsync(page, successful: true); + await AssertSharedReviewModeAsync(page); + await AssertNativeChoicesAsync(page); + await Expect(page).ToHaveURLAsync(address.AbsoluteUri); + Assert.True(int.Parse(await page.Locator("#integration-change-count").InnerTextAsync(), CultureInfo.InvariantCulture) > 2); + await FieldIdentity.AssertAsync(page); + } + + [Theory] + [ModeData] + public Task GalleryPassesAxe(RenderMode mode) => Accessibility.AssertNoViolationsAsync(gallery, mode, Path); + + [Theory] + [ModeData] + public async Task BothDensitiesKeepTargetsAndReflow(RenderMode mode) + { + foreach (string density in new[] { "comfortable", "compact" }) + { + await using GalleryPage sample = await gallery.OpenAsync(mode, Path, new() { Width = 320, Density = density, Theme = "dark", Direction = "rtl" }); + await Wcag.AssertTargetSizesAsync(sample.Page); + await Wcag.AssertNoHorizontalScrollAsync(sample.Page); + await FieldIdentity.AssertAsync(sample.Page); + } + } + + private async Task OpenStaticAsync(IBrowserContext context, RenderMode mode, string query = "") + { + IPage page = await context.NewPageAsync(); + var address = new Uri(gallery.BaseAddress, $"{mode.Segment()}/{Path}{query}"); + Assert.True((await page.GotoAsync(address.AbsoluteUri))?.Ok); + Assert.True(await page.EvaluateAsync("matchMedia('(scripting: none)').matches")); + return page; + } + + private static async Task EditDraftAsync(IPage page, RenderMode mode) + { + foreach (var (id, _, value) in DraftEdits) + { + if (id is "start" or "end" or "quiet") + { + continue; + } + ILocator input = page.Locator($"#integration-{id}"); + if (id == "language") + { + await input.SelectOptionAsync(value); + } + else + { + await input.FillAsync(value); + } + } + + ILocator notify = page.GetByRole(AriaRole.Checkbox, new() { Name = "Notify owners" }); + ILocator digest = page.GetByRole(AriaRole.Switch, new() { Name = "Daily digest" }); + ILocator locked = page.GetByRole(AriaRole.Checkbox, new() { Name = "Required notice" }); + await Expect(notify).Not.ToBeCheckedAsync(); + await Expect(digest).ToBeCheckedAsync(); + await Expect(locked).ToBeCheckedAsync(); + await Expect(locked).ToBeDisabledAsync(); + await notify.CheckAsync(); + if (mode.IsInteractive()) + { + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("NotifyOwners"); + } + await digest.UncheckAsync(); + if (mode.IsInteractive()) + { + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("DailyDigest"); + } + + var group = page.GetByRole(AriaRole.Radiogroup, new() { Name = "Review mode", Exact = true }); + await Expect(group).ToHaveCountAsync(1); + await Expect(group.GetByRole(AriaRole.Radio, new() { Name = "Owners only" })).ToBeDisabledAsync(); + // Tab enters the selected native radio. The arrow must skip the disabled middle option. + await page.Locator("#integration-language").FocusAsync(); + await page.Keyboard.PressAsync("Tab"); + await Expect(group.GetByRole(AriaRole.Radio, new() { Name = "Personal" })).ToBeFocusedAsync(); + await page.Keyboard.PressAsync("ArrowRight"); + await Expect(group.GetByRole(AriaRole.Radio, new() { Name = "Shared" })).ToBeFocusedAsync(); + await AssertSharedReviewModeAsync(page); + if (mode.IsInteractive()) + { + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); + } + + var audience = page.GetByRole(AriaRole.Radiogroup, new() { Name = "Who can see the draft", Exact = true }); + await Expect(audience.GetByRole(AriaRole.Radio, new() { Name = "Owners only" })).ToBeDisabledAsync(); + await page.Keyboard.PressAsync("Tab"); + await Expect(audience.GetByRole(AriaRole.Radio, new() { Name = "Authors" })).ToBeFocusedAsync(); + await page.Keyboard.PressAsync("ArrowRight"); + await Expect(audience.GetByRole(AriaRole.Radio, new() { Name = "Everyone" })).ToBeFocusedAsync(); + await AssertNativeChoicesAsync(page); + } + + private static async Task AssertSharedReviewModeAsync(IPage page) + { + var group = page.GetByRole(AriaRole.Radiogroup, new() { Name = "Review mode", Exact = true }); + await Expect(group).ToHaveCountAsync(1); + ILocator radios = group.Locator("input[type=radio]"); + await Expect(radios).ToHaveCountAsync(3); + Assert.All(await radios.EvaluateAllAsync("els => els.map(el => el.name)"), name => Assert.Equal("Model.ReviewMode", name)); + await Expect(group.Locator("input:checked")).ToHaveCountAsync(1); + await Expect(group.GetByRole(AriaRole.Radio, new() { Name = "Shared" })).ToBeCheckedAsync(); + ILocator disabled = group.GetByRole(AriaRole.Radio, new() { Name = "Owners only" }); + await Expect(disabled).ToBeDisabledAsync(); + await Expect(disabled).Not.ToBeCheckedAsync(); + } + + private static async Task AssertNativeChoicesAsync(IPage page) + { + await Expect(page.GetByRole(AriaRole.Checkbox, new() { Name = "Notify owners" })).ToBeCheckedAsync(); + await Expect(page.GetByRole(AriaRole.Switch, new() { Name = "Daily digest" })).Not.ToBeCheckedAsync(); + await Expect(page.GetByRole(AriaRole.Checkbox, new() { Name = "Required notice" })).ToBeDisabledAsync(); + var group = page.GetByRole(AriaRole.Radiogroup, new() { Name = "Who can see the draft", Exact = true }); + await Expect(group).ToHaveCountAsync(1); + ILocator radios = group.Locator("input[type=radio]"); + await Expect(radios).ToHaveCountAsync(3); + Assert.All(await radios.EvaluateAllAsync("els => els.map(el => el.name)"), name => Assert.Equal("Model.Audience", name)); + await Expect(group.Locator("input:checked")).ToHaveCountAsync(1); + await Expect(group.GetByRole(AriaRole.Radio, new() { Name = "Everyone" })).ToBeCheckedAsync(); + ILocator disabled = group.GetByRole(AriaRole.Radio, new() { Name = "Owners only" }); + await Expect(disabled).ToBeDisabledAsync(); + await Expect(disabled).Not.ToBeCheckedAsync(); + } + + private static async Task EditInitialDatesAsync(IPage page, RenderMode mode) + { + await AssertDeliveryModelAsync(page, "2026-11-24", "2026-11-25", "09:15:30"); + await EditTemporalAsync(page, mode, "start", "Start", "date", EditedStart); + await Expect(page.Locator("#integration-end")).ToHaveValueAsync("2026-11-25"); + if (mode.IsInteractive()) + { + await AssertDeliveryModelAsync(page, EditedStart, "2026-11-25", "09:15:30"); + } + await EditTemporalAsync(page, mode, "end", "End", "date", EditedEnd); + await Expect(page.Locator("#integration-start")).ToHaveValueAsync(EditedStart); + if (mode.IsInteractive()) + { + await AssertDeliveryModelAsync(page, EditedStart, EditedEnd, "09:15:30"); + } + await EditTemporalAsync(page, mode, "quiet", "QuietTime", "time", ""); + } + + private static async Task EditTemporalAsync(IPage page, RenderMode mode, string id, string field, string type, string value) + { + ILocator input = page.Locator($"#integration-{id}"); + await Expect(input).ToHaveAttributeAsync("type", type); + if (value.Length == 0) + { + await TemporalInput.ClearOptionalAsync(page, $"integration-{id}"); + } + else + { + await input.FillAsync(value); + await Expect(input).ToHaveValueAsync(value); + // Move focus out so a text-like input commits its native change before the next edit. + await page.Locator("#integration-save").FocusAsync(); + await Expect(input).Not.ToBeFocusedAsync(); + } + if (mode.IsInteractive()) + { + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync(field); + await Expect(page.Locator($"#integration-model-{id}")).ToHaveTextAsync(value.Length == 0 ? "(empty)" : value); + } + } + + private static async Task CorrectDraftAsync(IPage page, RenderMode mode) + { + await page.Locator("#integration-seats").FillAsync("8"); + await page.Locator("#integration-save").FocusAsync(); + if (mode.IsInteractive()) + { + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("Seats"); + } + await EditTemporalAsync(page, mode, "end", "End", "date", CorrectedEnd); + } + + private static async Task AssertDeliveryModelAsync(IPage page, string start, string end, string quiet) + { + await Expect(page.Locator("#integration-model-start")).ToHaveTextAsync(start); + await Expect(page.Locator("#integration-model-end")).ToHaveTextAsync(end); + await Expect(page.Locator("#integration-model-quiet")).ToHaveTextAsync(quiet); + } + + private static async Task PostAsync(IPage page, string submitter) + { + IResponse response = await page.RunAndWaitForResponseAsync( + () => submitter == "#integration-save" ? ClickSaveAsync(page) : page.Locator(submitter).ClickAsync(), + r => r.Request.Method == "POST" && new Uri(r.Url).AbsolutePath.EndsWith("/static/form-post", StringComparison.Ordinal)); + Assert.True(response.Request.IsNavigationRequest); + Assert.Equal(200, response.Status); + await Expect(page.Locator("main[data-render-mode=static] #integration-form")).ToBeVisibleAsync(); + var form = HttpUtility.ParseQueryString(response.Request.PostData ?? ""); + Assert.Equal(FormName, form["_handler"]); + Assert.False(string.IsNullOrWhiteSpace(form["__RequestVerificationToken"]), "The browser POST must carry an antiforgery token."); + return form; + } + + private static async Task ClickSaveAsync(IPage page) + { + ILocator save = page.Locator("#integration-save"); + Assert.True(await save.EvaluateAsync("el => !el.form.noValidate && !el.formNoValidate"), + "Save must use the browser's normal constraint validation."); + string[] blockers = await save.EvaluateAsync(""" + save => [...save.form.elements] + .filter(el => el.willValidate && (!el.validity.valid || el.matches(':invalid'))) + .map(el => `${el.id} (${el.type}), value='${el.value}', valid=${el.validity.valid}, badInput=${el.validity.badInput}, :invalid=${el.matches(':invalid')}: ${el.validationMessage}`) + """); + Assert.Empty(blockers); + await save.ClickAsync(); + } + + private static void AssertWire(NameValueCollection form, bool successful = false) + { + foreach (var (id, name, value) in DraftEdits) + { + AssertWireValue(form, name, Expected(id, value, successful)); + } + AssertWireValue(form, "Model.ReviewMode", "shared"); + AssertWireValue(form, "Model.NotifyOwners", "true"); + AssertWireValue(form, "Model.Audience", "everyone"); + Assert.Null(form["Model.DailyDigest"]); + Assert.Null(form["Model.LockedNotice"]); + Assert.Null(form["Model.LockedReference"]); + Assert.Null(form["Alias"]); + } + + private static void AssertWireValue(NameValueCollection form, string name, string expected) + { + string[] actual = form.GetValues(name) ?? []; + Assert.True(actual.Length == 1, $"Expected exactly one submitted value for {name}; received {actual.Length}."); + Assert.Equal(expected, actual[0]); + } + + private static string Expected(string id, string value, bool successful) => (successful, id) switch + { + (true, "seats") => "8", + (true, "end") => CorrectedEnd, + _ => value, + }; + + private static async Task AssertReturnedControlsAsync(IPage page, bool successful = false) + { + foreach (var (id, _, value) in DraftEdits) + { + await Expect(page.Locator($"#integration-{id}")).ToHaveValueAsync(Expected(id, value, successful)); + } + } + + private static async Task AssertInvalidDraftAsync(IPage page) + { + await Expect(page.Locator("#integration-saved")).ToHaveCountAsync(0); + await Expect(page.Locator("#integration-seats__error")).ToHaveTextAsync("Choose between 1 and 12 seats for this draft."); + await Expect(page.Locator("#integration-seats")).ToHaveAttributeAsync("aria-invalid", "true"); + var group = page.GetByRole(AriaRole.Group, new() { Name = "Delivery window", Exact = true }); + await Expect(group).ToHaveCountAsync(1); + await Expect(group.Locator(".fl-field__error")).ToHaveCountAsync(1); + await Expect(group.Locator(".fl-field__error")).ToHaveTextAsync("Choose an end date on or after the start date."); + await Expect(group).ToHaveAttributeAsync("aria-describedby", + "integration-start__error integration-start__help integration-window-policy", new() { Timeout = 3000 }); + await Expect(group.Locator("input[aria-describedby*='__error']")).ToHaveCountAsync(0); + await AssertDeliveryModelAsync(page, EditedStart, EditedEnd, "(empty)"); + await FieldIdentity.AssertAsync(page); + } + + private static async Task AssertSavedDraftAsync(IPage page, RenderMode mode) + { + await Expect(page.Locator("#integration-saved")).ToHaveTextAsync("Saved. Values received:"); + foreach (var (id, _, value) in DraftEdits) + { + string expected = Expected(id, value, successful: true); + await Expect(page.Locator($"#integration-result-{id}")).ToHaveTextAsync(expected.Length == 0 ? "(empty)" : expected); + } + // An interactive submit uses the existing EditContext model, not a reconstruction from form data. + await Expect(page.Locator("#integration-result-locked")).ToHaveTextAsync(mode.IsInteractive() ? "Managed by the host" : "(not sent)"); + await Expect(page.Locator("#integration-result-review")).ToHaveTextAsync("shared"); + await Expect(page.Locator("#integration-result-audience")).ToHaveTextAsync("everyone"); + await Expect(page.Locator("#integration-result-notify")).ToHaveTextAsync("on"); + await Expect(page.Locator("#integration-result-digest")).ToHaveTextAsync("off"); + await Expect(page.Locator("#integration-result-locked-notice")).ToHaveTextAsync(mode.IsInteractive() ? "on" : "off"); + await Expect(page.Locator("#integration-window")).ToHaveAttributeAsync("aria-describedby", "integration-start__help integration-window-policy"); + await AssertDeliveryModelAsync(page, EditedStart, CorrectedEnd, "(empty)"); + } +} diff --git a/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs b/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs index e22170d..a10656e 100644 --- a/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs @@ -65,8 +65,8 @@ await Expect(page.Locator("#temporal-saved")).ToHaveTextAsync( "Saved. Start: 2026-12-02. End: 2026-12-05. Local: 2026-12-02T18:35:00 (Unspecified). Time: 09:30:15. Audit: 2026-11-26."); await FieldIdentity.AssertAsync(page); - await ClearOptionalTemporalAsync(page, "temporal-end"); - await ClearOptionalTemporalAsync(page, "temporal-quiet"); + await TemporalInput.ClearOptionalAsync(page, "temporal-end"); + await TemporalInput.ClearOptionalAsync(page, "temporal-quiet"); ILocator save = page.Locator("#temporal-save"); if (!await save.EvaluateAsync("el => el === document.activeElement")) { @@ -230,38 +230,6 @@ internal static Task ApplyStrictPolicyAsync(IPage page, Uri address) => page.Rou await route.FulfillAsync(new() { Response = response, Headers = headers }); }); - private static async Task ClearOptionalTemporalAsync(IPage page, string id) - { - ILocator input = page.Locator($"#{id}"); - await page.Locator($"label[for='{id}']").ClickAsync(); - await page.Keyboard.PressAsync("Escape"); - await Expect(input).ToBeFocusedAsync(); - if (await input.EvaluateAsync("el => el.type === 'text'")) - { - await page.Keyboard.PressAsync("ControlOrMeta+A"); - await page.Keyboard.PressAsync("Backspace"); - } - else - { - // A partial date or time may look empty through .value. Clear every visible segment. - for (int i = 0; i < 4; i++) - { - await page.Keyboard.PressAsync("Backspace"); - if (i < 3) - { - await page.Keyboard.PressAsync("ArrowRight"); - } - } - } - for (int i = 0; i < 8 && await input.EvaluateAsync("el => el === document.activeElement"); i++) - { - await page.Keyboard.PressAsync("Tab"); - } - await Expect(input).Not.ToBeFocusedAsync(); - await Expect(input).ToHaveValueAsync(""); - Assert.True(await input.EvaluateAsync("el => el.validity.valid"), $"{id} must be empty and valid before native submit."); - } - private static async Task PostAsync(IPage page, string submitter, bool keyboard = false) { IResponse response = await page.RunAndWaitForResponseAsync( diff --git a/tests/FluentCMS.Components.Browser/Harness/TemporalInput.cs b/tests/FluentCMS.Components.Browser/Harness/TemporalInput.cs new file mode 100644 index 0000000..0ecdacb --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Harness/TemporalInput.cs @@ -0,0 +1,39 @@ +using Microsoft.Playwright; +using static Microsoft.Playwright.Assertions; + +namespace FluentCMS.Components.Browser.Harness; + +internal static class TemporalInput +{ + internal static async Task ClearOptionalAsync(IPage page, string id) + { + ILocator input = page.Locator($"#{id}"); + await page.Locator($"label[for='{id}']").ClickAsync(); + await page.Keyboard.PressAsync("Escape"); + await Expect(input).ToBeFocusedAsync(); + if (await input.EvaluateAsync("el => el.type === 'text'")) + { + await page.Keyboard.PressAsync("ControlOrMeta+A"); + await page.Keyboard.PressAsync("Backspace"); + } + else + { + // A partial date or time may look empty through .value. Clear every visible segment. + for (int i = 0; i < 4; i++) + { + await page.Keyboard.PressAsync("Backspace"); + if (i < 3) + { + await page.Keyboard.PressAsync("ArrowRight"); + } + } + } + for (int i = 0; i < 8 && await input.EvaluateAsync("el => el === document.activeElement"); i++) + { + await page.Keyboard.PressAsync("Tab"); + } + await Expect(input).Not.ToBeFocusedAsync(); + await Expect(input).ToHaveValueAsync(""); + Assert.True(await input.EvaluateAsync("el => el.validity.valid"), $"{id} must be empty and valid before native submit."); + } +} diff --git a/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs b/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs index 164f32f..5b4ed6c 100644 --- a/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs +++ b/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs @@ -91,6 +91,136 @@ public void EditContextMessagesShowAndClearAfterRerender() Assert.False(cut.Find("input").HasAttribute("aria-invalid")); } + [Fact] + public async Task UnchangedValidationDoesNotRenderTheFieldContentAgain() + { + var edit = new EditContext(_model); + var messages = new ValidationMessageStore(edit); + var trace = new List(); + edit.OnValidationStateChanged += (_, _) => trace.Add("validation notification"); + var cut = _context.Render>(p => p.Add(c => c.Value, edit) + .AddChildContent(field => field.Add(f => f.Label, "Quiet time") + .Add(f => f.ChildContent, (RenderFragment)(builder => + { + trace.Add($"field content: {_model.QuietTime:HH:mm:ss}"); + builder.OpenComponent>(0); + builder.AddComponentParameter(1, nameof(FlTimeInput.Value), _model.QuietTime); + builder.AddComponentParameter(2, nameof(FlTimeInput.ValueExpression), (Expression>)(() => _model.QuietTime)); + builder.CloseComponent(); + })))); + Assert.Equal("09:15:30", cut.Find("input").GetAttribute("value")); + trace.Clear(); + + await cut.InvokeAsync(edit.NotifyValidationStateChanged); + await cut.InvokeAsync(() => + { + messages.Add(edit.Field(nameof(Project.Email)), "Enter an email."); + edit.NotifyValidationStateChanged(); + }); + + Assert.Equal(["validation notification", "validation notification"], trace); + Assert.Empty(cut.FindAll(".fl-field__error")); + } + + [Fact] + public async Task AnUnchangedGroupMessageKeepsItsOwnerWhileIndividualInvalidStatesChange() + { + const string message = "Enter a whole number."; + var edit = new EditContext(_model); + var messages = new ValidationMessageStore(edit); + int contentRenders = 0; + var cut = _context.Render>(p => p.Add(c => c.Value, edit) + .AddChildContent(field => field.Add(f => f.Label, "Size").Add(f => f.Help, "Width and height.") + .Add(f => f.ChildContent, (RenderFragment)(builder => + { + contentRenders++; + Input(builder, 0, () => _model.Width, "Width"); + Input(builder, 10, () => _model.Height, "Height"); + })))); + string id = cut.Find("input[aria-label=Width]").Id!; + + await cut.InvokeAsync(() => + { + messages.Add(edit.Field(nameof(Project.Width)), message); + edit.NotifyValidationStateChanged(); + }); + Assert.Equal(message, cut.Find($"#{id}__error").TextContent); + Assert.Equal("true", cut.Find("input[aria-label=Width]").GetAttribute("aria-invalid")); + int rendersWithMessage = contentRenders; + + await cut.InvokeAsync(() => + { + messages.Clear(); + messages.Add(edit.Field(nameof(Project.Height)), message); + edit.NotifyValidationStateChanged(); + }); + Assert.Equal(rendersWithMessage, contentRenders); + var group = cut.Find("[role=group]"); + Assert.Equal($"{id}__label", group.GetAttribute("aria-labelledby")); + Assert.Equal($"{id}__error {id}__help", group.GetAttribute("aria-describedby")); + Assert.Single(cut.FindAll(".fl-field__error")); + Assert.False(cut.Find("input[aria-label=Width]").HasAttribute("aria-invalid")); + Assert.Equal("true", cut.Find("input[aria-label=Height]").GetAttribute("aria-invalid")); + Assert.All(cut.FindAll("input"), input => Assert.False(input.HasAttribute("aria-describedby"))); + + await cut.InvokeAsync(() => + { + messages.Clear(); + messages.Add(edit.Field(nameof(Project.Height)), "Enter a positive height."); + edit.NotifyValidationStateChanged(); + }); + Assert.Equal("Enter a positive height.", cut.Find($"#{id}__error").TextContent); + + await cut.InvokeAsync(() => + { + messages.Clear(); + edit.NotifyValidationStateChanged(); + }); + Assert.Empty(cut.FindAll(".fl-field__error")); + Assert.Equal($"{id}__help", cut.Find("[role=group]").GetAttribute("aria-describedby")); + Assert.False(cut.Find("input[aria-label=Height]").HasAttribute("aria-invalid")); + } + + [Fact] + public async Task ReplacingTheEditContextKeepsOnlyTheCurrentValidationSubscription() + { + var original = new EditContext(_model); + var next = new EditContext(_model); + var originalMessages = new ValidationMessageStore(original); + var nextMessages = new ValidationMessageStore(next); + originalMessages.Add(original.Field(nameof(Project.Email)), "Previous context error."); + EditContext active = original; + void Configure(ComponentParameterCollectionBuilder> p) => p.Add(c => c.Value, active) + .AddChildContent(field => field.Add(f => f.Label, "Email").Add(f => f.Help, "Used for sign-in.") + .Add(f => f.ChildContent, (RenderFragment)(builder => + { + // InputBase requires a new input instance when its EditContext changes. + builder.OpenComponent>(0); + builder.SetKey(active); + builder.AddComponentParameter(1, nameof(CascadingValue.Value), active); + builder.AddComponentParameter(2, nameof(CascadingValue.IsFixed), true); + builder.AddComponentParameter(3, nameof(CascadingValue.ChildContent), (RenderFragment)(child => Input(child, 0, () => _model.Email, null))); + builder.CloseComponent(); + }))); + var cut = _context.Render>(Configure); + var field = cut.FindComponent().Instance; + Assert.Equal("Previous context error.", cut.Find(".fl-field__error").TextContent); + + active = next; + cut.Render(Configure); + Assert.Same(field, cut.FindComponent().Instance); + Assert.Empty(cut.FindAll(".fl-field__error")); + nextMessages.Add(next.Field(nameof(Project.Email)), "Current context error."); + + await cut.InvokeAsync(original.NotifyValidationStateChanged); + Assert.Empty(cut.FindAll(".fl-field__error")); + + await cut.InvokeAsync(next.NotifyValidationStateChanged); + string id = cut.Find("input").Id!; + Assert.Equal("Current context error.", cut.Find($"#{id}__error").TextContent); + Assert.Equal($"{id}__error {id}__help", cut.Find("input").GetAttribute("aria-describedby")); + } + [Fact] public async Task TheCounterFollowsTypingAndMarksALongValue() { @@ -217,5 +347,6 @@ internal sealed class Project public string? Company { get; set; } public string? Width { get; set; } public string? Height { get; set; } + public TimeOnly? QuietTime { get; set; } = new TimeOnly(9, 15, 30); } } diff --git a/tests/FluentCMS.Components.Tests/Forms/FormPostBoundaryTests.cs b/tests/FluentCMS.Components.Tests/Forms/FormPostBoundaryTests.cs new file mode 100644 index 0000000..4594b49 --- /dev/null +++ b/tests/FluentCMS.Components.Tests/Forms/FormPostBoundaryTests.cs @@ -0,0 +1,61 @@ +using System.Linq.Expressions; +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; + +namespace FluentCMS.Components.Tests.Forms; + +public sealed class FormPostBoundaryTests : IDisposable +{ + private readonly BunitContext _context = new(); + private int _seats = 6; + private int _changes; + + [Fact] + public async Task MalformedNumberIsAFrameworkParseErrorNotAHostRejectionOfAValidWireValue() + { + var editContext = new EditContext(this); + Expression> expression = () => _seats; + var field = FieldIdentifier.Create(expression); + var cut = _context.Render(p => p.Add(f => f.EditContext, editContext) + .Add(f => f.ChildContent, (RenderFragment)(_ => builder => + { + builder.OpenComponent(0); + builder.AddComponentParameter(1, nameof(FlField.Label), "Seats"); + builder.AddComponentParameter(2, nameof(FlField.Help), "The draft can use up to 12 seats."); + builder.AddComponentParameter(3, nameof(FlField.ChildContent), (RenderFragment)(child => + { + child.OpenComponent>(0); + child.AddComponentParameter(1, nameof(FlNumberInput.Value), _seats); + child.AddComponentParameter(2, nameof(FlNumberInput.ValueExpression), expression); + child.AddComponentParameter(3, nameof(FlNumberInput.ValueChanged), EventCallback.Factory.Create(this, SetSeats)); + child.AddComponentParameter(4, nameof(FlNumberInput.DisplayName), "Seats"); + child.CloseComponent(); + })); + builder.CloseComponent(); + }))); + + // A browser may sanitize this string before POST. Exercise the real component binder directly. + await cut.Find("input[type=number]").ChangeAsync("not a number"); + Assert.Equal(0, _changes); + Assert.Equal(6, _seats); + Assert.Equal("The Seats field must be a number.", Assert.Single(editContext.GetValidationMessages(field))); + var input = cut.Find("input[type=number]"); + Assert.Equal("true", input.GetAttribute("aria-invalid")); + Assert.Equal($"{input.Id}__error {input.Id}__help", input.GetAttribute("aria-describedby")); + + await input.ChangeAsync("8"); + Assert.Equal(8, _seats); + Assert.Equal(1, _changes); + Assert.Empty(editContext.GetValidationMessages(field)); + Assert.Empty(cut.FindAll(".fl-field__error")); + } + + private void SetSeats(int value) + { + _seats = value; + _changes++; + } + + public void Dispose() => _context.Dispose(); +}