From 635b1e32112c0c2e528c72d226732d85950536c3 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 11:13:45 -0500 Subject: [PATCH 01/13] Exercise native draft form submission --- docs/guides/static-edit-form.md | 53 ++++ gallery/Gallery.Client/GalleryPages.cs | 1 + gallery/Gallery.Client/Pages/FormPost.razor | 221 +++++++++++++++++ .../Forms/FormPostPrerenderTests.cs | 88 +++++++ .../Forms/FormPostTests.cs | 232 ++++++++++++++++++ .../Forms/FormPostBoundaryTests.cs | 61 +++++ 6 files changed, 656 insertions(+) create mode 100644 docs/guides/static-edit-form.md create mode 100644 gallery/Gallery.Client/Pages/FormPost.razor create mode 100644 tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs create mode 100644 tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs create mode 100644 tests/FluentCMS.Components.Tests/Forms/FormPostBoundaryTests.cs diff --git a/docs/guides/static-edit-form.md b/docs/guides/static-edit-form.md new file mode 100644 index 0000000..2fd73fd --- /dev/null +++ b/docs/guides/static-edit-form.md @@ -0,0 +1,53 @@ +# 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 draft fixture currently uses the merged field, text input, text area, number, select, date and time controls. Coverage of unchecked booleans and exactly-one radio or segmented choices is pending those inputs; the fixture does not stand them in with HTML or faked values. + +## 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")]`. | +| 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. **Save draft** sends a real POST. `18` is a valid number and within the browser's range of 1–100, but the host allows only 1–12. The field group owns the date error once, before its help and external description, and the inputs keep their edited values. 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. Follow **Include the city in submit validation** to open a fresh draft where the host also validates that property. This 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 a field and leave it. The change indicator comes from `EditContext.OnFieldChanged`. 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. + +```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 e0fed5e..185a1f0 100644 --- a/gallery/Gallery.Client/GalleryPages.cs +++ b/gallery/Gallery.Client/GalleryPages.cs @@ -17,6 +17,7 @@ public static class GalleryPages new("number-input", "Number input"), new("select", "Select"), 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..6a4fd1e --- /dev/null +++ b/gallery/Gallery.Client/Pages/FormPost.razor @@ -0,0 +1,221 @@ +@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.

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

Checks for native checkbox, radio, switch and segmented inputs are not in this fixture yet.

+
+ +
+

@@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 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; + 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"; + + 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", Start = new DateOnly(2026, 11, 24), + End = new DateOnly(2026, 11, 25), QuietTime = new TimeOnly(9, 15, 30), LockedReference = "Managed by the host", + }; + 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 }; + _editContext.OnFieldChanged += OnFieldChanged; + if (CheckCity) + { + _cityMessages = new ValidationMessageStore(_editContext); + _editContext.OnValidationRequested += ValidateCity; + } + } + + 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(); + AddressDraft address = Model!.Address; + if (!CityRule.IsValid(address.City)) + { + _cityMessages.Add(new FieldIdentifier(address, nameof(AddressDraft.City)), 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)), ("alias", "Support alias", Display(Alias)), + ("start", "Start date", Display(result.Start?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))), + ("end", "End date", Display(result.End?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))), + ("quiet", "Quiet time", Display(result.QuietTime?.ToString("HH:mm:ss", CultureInfo.InvariantCulture))), + ("locked", "Locked reference", result.LockedReference ?? "(not sent)"), + ]; + } + + private void NotSaved() => _saved = null; + + private static string Display(string? text) => string.IsNullOrEmpty(text) ? "(empty)" : text; + + 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 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/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs new file mode 100644 index 0000000..e0e0553 --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs @@ -0,0 +1,88 @@ +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 .fl-field')]; + 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); + // 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(11, 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 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..02425f5 --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -0,0 +1,232 @@ +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 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", "2026-12-03"), + ("end", "Model.End", "2026-12-01"), + ("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); + 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 CorrectDraftAsync(page); + NameValueCollection corrected = await PostAsync(page, "#integration-save"); + AssertWire(corrected, successful: true); + await AssertSavedDraftAsync(page, mode); + await AssertReturnedControlsAsync(page, successful: true); + 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 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); + var address = new Uri(page.Url); + await page.Locator("#integration-save").ClickAsync(); + await AssertInvalidDraftAsync(page); + await AssertReturnedControlsAsync(page); + await CorrectDraftAsync(page); + await page.Locator("#integration-save").ClickAsync(); + await AssertSavedDraftAsync(page, mode); + 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) + { + foreach (var (id, _, value) in DraftEdits) + { + ILocator input = page.Locator($"#integration-{id}"); + if (id == "language") + { + await input.SelectOptionAsync(value); + } + else + { + await input.FillAsync(value); + } + } + } + + private static async Task CorrectDraftAsync(IPage page) + { + await page.Locator("#integration-seats").FillAsync("8"); + await page.Locator("#integration-end").FillAsync("2026-12-04"); + } + + private static async Task PostAsync(IPage page, string submitter) + { + IResponse response = await page.RunAndWaitForResponseAsync(() => page.Locator(submitter).ClickAsync(), + r => r.Request.Method == "POST" && new Uri(r.Url).AbsolutePath.EndsWith("/static/form-post", StringComparison.Ordinal)); + Assert.True(response.Ok && response.Request.IsNavigationRequest, $"Expected successful POST document, got HTTP {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 void AssertWire(NameValueCollection form, bool successful = false) + { + foreach (var (id, name, value) in DraftEdits) + { + AssertWireValue(form, name, Expected(id, value, successful)); + } + 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") => "2026-12-04", + _ => 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 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-window")).ToHaveAttributeAsync("aria-describedby", "integration-start__help integration-window-policy"); + } +} 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(); +} From 1f9ab4df759310f9334b1e758a21ae078a03702e Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 11:54:36 -0500 Subject: [PATCH 02/13] Verify segmented selection in the draft form --- docs/guides/static-edit-form.md | 5 +-- gallery/Gallery.Client/Pages/FormPost.razor | 12 +++++-- .../Forms/FormPostPrerenderTests.cs | 16 +++++++--- .../Forms/FormPostTests.cs | 32 +++++++++++++++++++ 4 files changed, 55 insertions(+), 10 deletions(-) diff --git a/docs/guides/static-edit-form.md b/docs/guides/static-edit-form.md index 2fd73fd..ac566b5 100644 --- a/docs/guides/static-edit-form.md +++ b/docs/guides/static-edit-form.md @@ -6,7 +6,7 @@ The gallery's `form-post` page uses the library controls in one named `EditForm` 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 draft fixture currently uses the merged field, text input, text area, number, select, date and time controls. Coverage of unchecked booleans and exactly-one radio or segmented choices is pending those inputs; the fixture does not stand them in with HTML or faked values. +Open the printed address at `/static/form-post`; the same form is available at `/server/form-post` and `/wasm/form-post`. The draft fixture currently uses the merged field, text input, text area, number, select, segmented, date and time controls. The dedicated checkbox, radio-group and switch cases are pending; the fixture does not stand them in with HTML or faked values. ## The form and its names @@ -20,6 +20,7 @@ Open the printed address at `/static/form-post`; the same form is available at ` | 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. | | 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. | @@ -40,7 +41,7 @@ An explicit `name` wins, including from an attribute dictionary. Keep the receiv ## 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. **Save draft** sends a real POST. `18` is a valid number and within the browser's range of 1–100, but the host allows only 1–12. The field group owns the date error once, before its help and external description, and the inputs keep their edited values. Correct the two errors and save again. The result lists what the handler received. +- 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. The native radios skip disabled **Owners only** and choose **Shared**. **Save draft** sends an actual POST with one review-mode value. `18` is a valid number and within the browser's range of 1–100, but the host allows only 1–12. The field group owns the date error once, before its help and external description, and the inputs keep their edited values, including the selected review mode. 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. Follow **Include the city in submit validation** to open a fresh draft where the host also validates that property. This 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 a field and leave it. The change indicator comes from `EditContext.OnFieldChanged`. 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. diff --git a/gallery/Gallery.Client/Pages/FormPost.razor b/gallery/Gallery.Client/Pages/FormPost.razor index 6a4fd1e..d90c194 100644 --- a/gallery/Gallery.Client/Pages/FormPost.razor +++ b/gallery/Gallery.Client/Pages/FormPost.razor @@ -46,6 +46,9 @@ + + +
@@ -70,7 +73,7 @@
-

Checks for native checkbox, radio, switch and segmented inputs are not in this fixture yet.

+

The segmented review mode submits one choice. Checks for the dedicated checkbox, radio-group and switch controls are not in this fixture yet.

@@ -82,6 +85,7 @@ @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 IReadOnlyDictionary AliasAttributes = new Dictionary { ["id"] = "integration-alias", ["NAME"] = "support_alias" }; private static readonly RequiredAttribute CityRule = new(); @@ -108,7 +112,7 @@ Model = new DraftSettings { Title = "Workspace handbook", Address = new AddressDraft { City = "Harbor" }, Tags = ["guide", "draft"], - Notes = "A short draft.", Seats = 6, Language = "en", Start = new DateOnly(2026, 11, 24), + 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", }; Alias = "settings-help"; @@ -156,7 +160,8 @@ ("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)), ("alias", "Support alias", Display(Alias)), + ("language", "Language", Display(result.Language)), ("review", "Review mode", Display(result.ReviewMode)), + ("alias", "Support alias", Display(Alias)), ("start", "Start date", Display(result.Start?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))), ("end", "End date", Display(result.End?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))), ("quiet", "Quiet time", Display(result.QuietTime?.ToString("HH:mm:ss", CultureInfo.InvariantCulture))), @@ -189,6 +194,7 @@ public string? Notes { get; set; } public int Seats { get; set; } public string? Language { get; set; } + public string? ReviewMode { get; set; } public DateOnly? Start { get; set; } public DateOnly? End { get; set; } public TimeOnly? QuietTime { get; set; } diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs index e0e0553..c2623e0 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs @@ -40,10 +40,14 @@ await page.RouteAsync("**/_framework/blazor.web*.js", async route => 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); + 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.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. @@ -77,12 +81,14 @@ await page.RouteAsync("**/_framework/blazor.web*.js", async route => resume.TrySetResult(); } - Assert.Equal(11, before.Length); + Assert.Equal(12, 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 FieldIdentity.AssertAsync(page); } } diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index 02425f5..8b1eb94 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -41,12 +41,14 @@ public async Task NativePostPreservesValuesAfterValidationAndSavesCorrected(Rend AssertWire(first); await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); + await AssertSharedReviewModeAsync(page); await CorrectDraftAsync(page); NameValueCollection corrected = await PostAsync(page, "#integration-save"); AssertWire(corrected, successful: true); await AssertSavedDraftAsync(page, mode); await AssertReturnedControlsAsync(page, successful: true); + await AssertSharedReviewModeAsync(page); await FieldIdentity.AssertAsync(page); } @@ -98,13 +100,16 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("2"); await EditDraftAsync(page); + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); var address = new Uri(page.Url); await page.Locator("#integration-save").ClickAsync(); await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); + await AssertSharedReviewModeAsync(page); await CorrectDraftAsync(page); await page.Locator("#integration-save").ClickAsync(); await AssertSavedDraftAsync(page, mode); + await AssertSharedReviewModeAsync(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); @@ -150,6 +155,31 @@ private static async Task EditDraftAsync(IPage page) await input.FillAsync(value); } } + + 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); + } + + 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 CorrectDraftAsync(IPage page) @@ -176,6 +206,7 @@ private static void AssertWire(NameValueCollection form, bool successful = false { AssertWireValue(form, name, Expected(id, value, successful)); } + AssertWireValue(form, "Model.ReviewMode", "shared"); Assert.Null(form["Model.LockedReference"]); Assert.Null(form["Alias"]); } @@ -227,6 +258,7 @@ private static async Task AssertSavedDraftAsync(IPage page, RenderMode mode) } // 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-window")).ToHaveAttributeAsync("aria-describedby", "integration-start__help integration-window-policy"); } } From 69bc5c710b4744ceb321992708191808b39fada2 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 14:05:36 -0500 Subject: [PATCH 03/13] Verify each delivery date reaches the draft model --- docs/guides/static-edit-form.md | 4 +- gallery/Gallery.Client/Pages/FormPost.razor | 11 ++- .../Forms/FormPostTests.cs | 72 +++++++++++++++++-- 3 files changed, 76 insertions(+), 11 deletions(-) diff --git a/docs/guides/static-edit-form.md b/docs/guides/static-edit-form.md index ac566b5..2a8ad48 100644 --- a/docs/guides/static-edit-form.md +++ b/docs/guides/static-edit-form.md @@ -44,7 +44,9 @@ An explicit `name` wins, including from an attribute dictionary. Keep the receiv - 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. The native radios skip disabled **Owners only** and choose **Shared**. **Save draft** sends an actual POST with one review-mode value. `18` is a valid number and within the browser's range of 1–100, but the host allows only 1–12. The field group owns the date error once, before its help and external description, and the inputs keep their edited values, including the selected review mode. 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. Follow **Include the city in submit validation** to open a fresh draft where the host also validates that property. This 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 a field and leave it. The change indicator comes from `EditContext.OnFieldChanged`. 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. +- 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' diff --git a/gallery/Gallery.Client/Pages/FormPost.razor b/gallery/Gallery.Client/Pages/FormPost.razor index d90c194..b0fac65 100644 --- a/gallery/Gallery.Client/Pages/FormPost.razor +++ b/gallery/Gallery.Client/Pages/FormPost.razor @@ -67,6 +67,8 @@

Changes: @_changes. Latest field: @_lastChanged.

+

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

Save draft Check on server @@ -162,9 +164,8 @@ ("notes", "Draft notes", Display(result.Notes)), ("seats", "Seats", result.Seats.ToString(CultureInfo.InvariantCulture)), ("language", "Language", Display(result.Language)), ("review", "Review mode", Display(result.ReviewMode)), ("alias", "Support alias", Display(Alias)), - ("start", "Start date", Display(result.Start?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))), - ("end", "End date", Display(result.End?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))), - ("quiet", "Quiet time", Display(result.QuietTime?.ToString("HH:mm:ss", CultureInfo.InvariantCulture))), + ("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)"), ]; } @@ -173,6 +174,10 @@ 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)); + public void Dispose() { _editContext.OnFieldChanged -= OnFieldChanged; diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index 8b1eb94..1c47bd0 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -11,6 +11,9 @@ 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"), @@ -20,8 +23,8 @@ private static readonly (string Id, string Name, string Value)[] DraftEdits = ("notes", "Model.Notes", "Review & publish"), ("seats", "Model.Seats", "18"), ("language", "Model.Language", "fr"), - ("start", "Model.Start", "2026-12-03"), - ("end", "Model.End", "2026-12-01"), + ("start", "Model.Start", EditedStart), + ("end", "Model.End", EditedEnd), ("quiet", "Model.QuietTime", ""), ("alias", "support_alias", "draft-help"), ]; @@ -33,6 +36,7 @@ public async Task NativePostPreservesValuesAfterValidationAndSavesCorrected(Rend await using IBrowserContext context = await gallery.Browser.NewContextAsync(new() { JavaScriptEnabled = false }); IPage page = await OpenStaticAsync(context, mode); await EditDraftAsync(page); + 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."); @@ -43,7 +47,7 @@ public async Task NativePostPreservesValuesAfterValidationAndSavesCorrected(Rend await AssertReturnedControlsAsync(page); await AssertSharedReviewModeAsync(page); - await CorrectDraftAsync(page); + await CorrectDraftAsync(page, mode); NameValueCollection corrected = await PostAsync(page, "#integration-save"); AssertWire(corrected, successful: true); await AssertSavedDraftAsync(page, mode); @@ -101,14 +105,16 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren await EditDraftAsync(page); await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); + await EditInitialDatesAsync(page, mode); var address = new Uri(page.Url); await page.Locator("#integration-save").ClickAsync(); await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); await AssertSharedReviewModeAsync(page); - await CorrectDraftAsync(page); + await CorrectDraftAsync(page, mode); await page.Locator("#integration-save").ClickAsync(); await AssertSavedDraftAsync(page, mode); + await AssertReturnedControlsAsync(page, successful: true); await AssertSharedReviewModeAsync(page); await Expect(page).ToHaveURLAsync(address.AbsoluteUri); Assert.True(int.Parse(await page.Locator("#integration-change-count").InnerTextAsync(), CultureInfo.InvariantCulture) > 2); @@ -145,6 +151,10 @@ private static async Task EditDraftAsync(IPage page) { foreach (var (id, _, value) in DraftEdits) { + if (id is "start" or "end" or "quiet") + { + continue; + } ILocator input = page.Locator($"#integration-{id}"); if (id == "language") { @@ -182,10 +192,56 @@ private static async Task AssertSharedReviewModeAsync(IPage page) await Expect(disabled).Not.ToBeCheckedAsync(); } - private static async Task CorrectDraftAsync(IPage page) + 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); + 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-end").FillAsync("2026-12-04"); + 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) @@ -221,7 +277,7 @@ private static void AssertWireValue(NameValueCollection form, string name, strin private static string Expected(string id, string value, bool successful) => (successful, id) switch { (true, "seats") => "8", - (true, "end") => "2026-12-04", + (true, "end") => CorrectedEnd, _ => value, }; @@ -245,6 +301,7 @@ private static async Task AssertInvalidDraftAsync(IPage page) 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); } @@ -260,5 +317,6 @@ private static async Task AssertSavedDraftAsync(IPage page, RenderMode mode) 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-window")).ToHaveAttributeAsync("aria-describedby", "integration-start__help integration-window-policy"); + await AssertDeliveryModelAsync(page, EditedStart, CorrectedEnd, "(empty)"); } } From 854177832b2277105dda0ce6928795a8af080704 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 15:41:43 -0500 Subject: [PATCH 04/13] Trace native validation before draft Save --- .../Forms/FormPostTests.cs | 84 +++++++++++++++++-- 1 file changed, 78 insertions(+), 6 deletions(-) diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index 1c47bd0..8e75f78 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -14,6 +14,7 @@ public sealed class FormPostTests(GalleryFixture gallery) private const string EditedStart = "2026-12-03"; private const string EditedEnd = "2026-12-01"; private const string CorrectedEnd = "2026-12-04"; + private string? _beforeSave; private static readonly (string Id, string Name, string Value)[] DraftEdits = [ ("title", "Model.Title", "Team handbook"), @@ -107,12 +108,19 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); await EditInitialDatesAsync(page, mode); var address = new Uri(page.Url); - await page.Locator("#integration-save").ClickAsync(); - await AssertInvalidDraftAsync(page); + await ClickSaveAsync(page); + try + { + await AssertInvalidDraftAsync(page); + } + catch (PlaywrightException error) + { + throw await SaveFailureAsync(page, error, "Interactive Save: native submit/invalid events below."); + } await AssertReturnedControlsAsync(page); await AssertSharedReviewModeAsync(page); await CorrectDraftAsync(page, mode); - await page.Locator("#integration-save").ClickAsync(); + await ClickSaveAsync(page); await AssertSavedDraftAsync(page, mode); await AssertReturnedControlsAsync(page, successful: true); await AssertSharedReviewModeAsync(page); @@ -244,10 +252,30 @@ private static async Task AssertDeliveryModelAsync(IPage page, string start, str await Expect(page.Locator("#integration-model-quiet")).ToHaveTextAsync(quiet); } - private static async Task PostAsync(IPage page, string submitter) + private async Task PostAsync(IPage page, string submitter) { - IResponse response = await page.RunAndWaitForResponseAsync(() => page.Locator(submitter).ClickAsync(), - r => r.Request.Method == "POST" && new Uri(r.Url).AbsolutePath.EndsWith("/static/form-post", StringComparison.Ordinal)); + bool IsFormPost(IRequest request) => request.Method == "POST" && new Uri(request.Url).AbsolutePath.EndsWith("/static/form-post", StringComparison.Ordinal); + var requests = new System.Collections.Concurrent.ConcurrentQueue(); + EventHandler record = (_, request) => + { + if (IsFormPost(request)) requests.Enqueue($"POST navigation={request.IsNavigationRequest}"); + }; + page.Request += record; + IResponse response; + try + { + response = await page.RunAndWaitForResponseAsync( + () => submitter == "#integration-save" ? ClickSaveAsync(page) : page.Locator(submitter).ClickAsync(), + r => IsFormPost(r.Request)); + } + catch (TimeoutException error) when (submitter == "#integration-save") + { + throw await SaveFailureAsync(page, error, requests.IsEmpty ? "No form POST request observed." : string.Join(", ", requests)); + } + finally + { + page.Request -= record; + } Assert.True(response.Ok && response.Request.IsNavigationRequest, $"Expected successful POST document, got HTTP {response.Status}."); await Expect(page.Locator("main[data-render-mode=static] #integration-form")).ToBeVisibleAsync(); var form = HttpUtility.ParseQueryString(response.Request.PostData ?? ""); @@ -256,6 +284,50 @@ private static async Task PostAsync(IPage page, string subm return form; } + private async Task ClickSaveAsync(IPage page) + { + await page.EvaluateAsync(""" + () => { + if (matchMedia('(scripting: none)').matches) return; + const form = document.querySelector('#integration-form'); + if (!form.postSaveEvents) { + form.postSaveEvents = []; + for (const kind of ['invalid', 'submit']) { + form.addEventListener(kind, e => form.postSaveEvents.push(`${e.type}: ${e.target.id}`), true); + } + } + form.postSaveEvents.length = 0; + } + """); + _beforeSave = await NativeSaveStateAsync(page); + await page.Locator("#integration-save").ClickAsync(); + } + + private async Task SaveFailureAsync(IPage page, Exception error, string traffic) + { + string after; + try { after = await NativeSaveStateAsync(page).WaitAsync(TimeSpan.FromSeconds(4)); } + catch (Exception snapshotError) { after = $"Snapshot unavailable: {snapshotError.GetType().Name}"; } + return new Xunit.Sdk.XunitException($"{error.Message}\n{traffic}\nBefore normal Save: {_beforeSave}\nAfter normal Save: {after}"); + } + + private static Task NativeSaveStateAsync(IPage page) => page.EvaluateAsync(""" + () => { + const save = document.querySelector('#integration-save'); + const form = save.form; + const flags = ['badInput', 'customError', 'patternMismatch', 'rangeOverflow', 'rangeUnderflow', 'stepMismatch', 'tooLong', 'tooShort', 'typeMismatch', 'valueMissing']; + return JSON.stringify({ + active: document.activeElement?.id, formNoValidate: form.noValidate, saveNoValidate: save.formNoValidate, + nativeInvalid: form.matches(':invalid'), events: form.postSaveEvents ?? null, + controls: [...form.elements].filter(el => el.matches('input:not([type=hidden]), textarea, select')).map(el => ({ + id: el.id, name: el.name, declared: el.getAttribute('type'), type: el.type, value: el.value, + required: el.required, willValidate: el.willValidate, valid: el.validity.valid, + nativeInvalid: el.matches(':invalid'), flags: flags.filter(flag => el.validity[flag]), message: el.validationMessage + })) + }); + } + """); + private static void AssertWire(NameValueCollection form, bool successful = false) { foreach (var (id, name, value) in DraftEdits) From 22edcaeb1b040973c0e045ce605406b9eaf9ea24 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 15:49:29 -0500 Subject: [PATCH 05/13] Clear optional draft time through native keyboard segments --- .../Forms/FormPostTests.cs | 107 +++++------------- .../Forms/TemporalTests.cs | 36 +----- .../Harness/TemporalInput.cs | 39 +++++++ 3 files changed, 70 insertions(+), 112 deletions(-) create mode 100644 tests/FluentCMS.Components.Browser/Harness/TemporalInput.cs diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index 8e75f78..f6498d0 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -14,7 +14,6 @@ public sealed class FormPostTests(GalleryFixture gallery) private const string EditedStart = "2026-12-03"; private const string EditedEnd = "2026-12-01"; private const string CorrectedEnd = "2026-12-04"; - private string? _beforeSave; private static readonly (string Id, string Name, string Value)[] DraftEdits = [ ("title", "Model.Title", "Team handbook"), @@ -109,14 +108,7 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren await EditInitialDatesAsync(page, mode); var address = new Uri(page.Url); await ClickSaveAsync(page); - try - { - await AssertInvalidDraftAsync(page); - } - catch (PlaywrightException error) - { - throw await SaveFailureAsync(page, error, "Interactive Save: native submit/invalid events below."); - } + await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); await AssertSharedReviewModeAsync(page); await CorrectDraftAsync(page, mode); @@ -222,11 +214,18 @@ private static async Task EditTemporalAsync(IPage page, RenderMode mode, string { ILocator input = page.Locator($"#integration-{id}"); await Expect(input).ToHaveAttributeAsync("type", type); - 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 (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); @@ -252,31 +251,13 @@ private static async Task AssertDeliveryModelAsync(IPage page, string start, str await Expect(page.Locator("#integration-model-quiet")).ToHaveTextAsync(quiet); } - private async Task PostAsync(IPage page, string submitter) + private static async Task PostAsync(IPage page, string submitter) { - bool IsFormPost(IRequest request) => request.Method == "POST" && new Uri(request.Url).AbsolutePath.EndsWith("/static/form-post", StringComparison.Ordinal); - var requests = new System.Collections.Concurrent.ConcurrentQueue(); - EventHandler record = (_, request) => - { - if (IsFormPost(request)) requests.Enqueue($"POST navigation={request.IsNavigationRequest}"); - }; - page.Request += record; - IResponse response; - try - { - response = await page.RunAndWaitForResponseAsync( - () => submitter == "#integration-save" ? ClickSaveAsync(page) : page.Locator(submitter).ClickAsync(), - r => IsFormPost(r.Request)); - } - catch (TimeoutException error) when (submitter == "#integration-save") - { - throw await SaveFailureAsync(page, error, requests.IsEmpty ? "No form POST request observed." : string.Join(", ", requests)); - } - finally - { - page.Request -= record; - } - Assert.True(response.Ok && response.Request.IsNavigationRequest, $"Expected successful POST document, got HTTP {response.Status}."); + 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"]); @@ -284,50 +265,20 @@ private async Task PostAsync(IPage page, string submitter) return form; } - private async Task ClickSaveAsync(IPage page) + private static async Task ClickSaveAsync(IPage page) { - await page.EvaluateAsync(""" - () => { - if (matchMedia('(scripting: none)').matches) return; - const form = document.querySelector('#integration-form'); - if (!form.postSaveEvents) { - form.postSaveEvents = []; - for (const kind of ['invalid', 'submit']) { - form.addEventListener(kind, e => form.postSaveEvents.push(`${e.type}: ${e.target.id}`), true); - } - } - form.postSaveEvents.length = 0; - } + 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}`) """); - _beforeSave = await NativeSaveStateAsync(page); - await page.Locator("#integration-save").ClickAsync(); + Assert.Empty(blockers); + await save.ClickAsync(); } - private async Task SaveFailureAsync(IPage page, Exception error, string traffic) - { - string after; - try { after = await NativeSaveStateAsync(page).WaitAsync(TimeSpan.FromSeconds(4)); } - catch (Exception snapshotError) { after = $"Snapshot unavailable: {snapshotError.GetType().Name}"; } - return new Xunit.Sdk.XunitException($"{error.Message}\n{traffic}\nBefore normal Save: {_beforeSave}\nAfter normal Save: {after}"); - } - - private static Task NativeSaveStateAsync(IPage page) => page.EvaluateAsync(""" - () => { - const save = document.querySelector('#integration-save'); - const form = save.form; - const flags = ['badInput', 'customError', 'patternMismatch', 'rangeOverflow', 'rangeUnderflow', 'stepMismatch', 'tooLong', 'tooShort', 'typeMismatch', 'valueMissing']; - return JSON.stringify({ - active: document.activeElement?.id, formNoValidate: form.noValidate, saveNoValidate: save.formNoValidate, - nativeInvalid: form.matches(':invalid'), events: form.postSaveEvents ?? null, - controls: [...form.elements].filter(el => el.matches('input:not([type=hidden]), textarea, select')).map(el => ({ - id: el.id, name: el.name, declared: el.getAttribute('type'), type: el.type, value: el.value, - required: el.required, willValidate: el.willValidate, valid: el.validity.valid, - nativeInvalid: el.matches(':invalid'), flags: flags.filter(flag => el.validity[flag]), message: el.validationMessage - })) - }); - } - """); - private static void AssertWire(NameValueCollection form, bool successful = false) { foreach (var (id, name, value) in DraftEdits) 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."); + } +} From 416f9c7369cb050ba684aff1c7103259fe106be6 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 16:12:36 -0500 Subject: [PATCH 06/13] Trace native quiet-time validity across interactive rendering --- .../Forms/FormPostTests.cs | 35 ++++++++++- .../Forms/QuietTimeEvidence.cs | 60 +++++++++++++++++++ 2 files changed, 93 insertions(+), 2 deletions(-) create mode 100644 tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index f6498d0..579e00c 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -107,7 +107,17 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); await EditInitialDatesAsync(page, mode); var address = new Uri(page.Url); - await ClickSaveAsync(page); + try + { + await ClickSaveAsync(page); + } + catch (Xunit.Sdk.XunitException error) + { + var observed = await QuietTimeEvidence.ReadAsync(page); + string plain = await ReplayQuietTimeAsync(RenderMode.Static, traceWrites: false); + string binding = await ReplayQuietTimeAsync(mode, traceWrites: true); + throw new Xunit.Sdk.XunitException($"{error.Message}\nActual interactive: {observed}\nObservation-only static: {plain}\nInteractive setter witness: {binding}"); + } await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); await AssertSharedReviewModeAsync(page); @@ -192,7 +202,7 @@ private static async Task AssertSharedReviewModeAsync(IPage page) await Expect(disabled).Not.ToBeCheckedAsync(); } - private static async Task EditInitialDatesAsync(IPage page, RenderMode mode) + private static async Task EditInitialDatesAsync(IPage page, RenderMode mode, bool traceWrites = false) { await AssertDeliveryModelAsync(page, "2026-11-24", "2026-11-25", "09:15:30"); await EditTemporalAsync(page, mode, "start", "Start", "date", EditedStart); @@ -207,9 +217,30 @@ private static async Task EditInitialDatesAsync(IPage page, RenderMode mode) { await AssertDeliveryModelAsync(page, EditedStart, EditedEnd, "09:15:30"); } + await QuietTimeEvidence.StartAsync(page, traceWrites); await EditTemporalAsync(page, mode, "quiet", "QuietTime", "time", ""); } + private async Task ReplayQuietTimeAsync(RenderMode mode, bool traceWrites) + { + try + { + await using GalleryPage sample = await gallery.OpenAsync(mode, Path); + sample.Page.SetDefaultTimeout(5000); + await EditDraftAsync(sample.Page); + if (mode.IsInteractive()) + { + await Expect(sample.Page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); + } + await EditInitialDatesAsync(sample.Page, mode, traceWrites); + return await QuietTimeEvidence.ReadAsync(sample.Page); + } + catch (Exception error) + { + return $"Witness failed: {error.GetType().Name}: {error.Message}"; + } + } + private static async Task EditTemporalAsync(IPage page, RenderMode mode, string id, string field, string type, string value) { ILocator input = page.Locator($"#integration-{id}"); diff --git a/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs b/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs new file mode 100644 index 0000000..f37c260 --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs @@ -0,0 +1,60 @@ +using Microsoft.Playwright; + +namespace FluentCMS.Components.Browser.Forms; + +internal static class QuietTimeEvidence +{ + internal static Task StartAsync(IPage page, bool traceWrites) => page.EvaluateAsync(""" + traceWrites => { + if (matchMedia('(scripting: none)').matches) return; + const field = document.querySelector('#integration-quiet'); + const form = field.form; + const outputIds = ['integration-change-count', 'integration-last-change', 'integration-model-quiet']; + const outputs = () => outputIds.map(id => document.getElementById(id).textContent.trim()); + const descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); + const read = () => { + const el = document.getElementById(field.id); + return {sameNode: el === field, type: el.type, value: descriptor.get.call(el), defaultValue: el.defaultValue, + valid: el.validity.valid, badInput: el.validity.badInput, invalid: el.matches(':invalid'), + active: document.activeElement?.id, model: outputs()}; + }; + const steps = []; + const record = (at, details) => { + if (steps.length < 60) steps.push({t: Math.round(performance.now()), at, ...read(), details}); + }; + for (const kind of ['keydown', 'keyup', 'input', 'change', 'focusin', 'focusout', 'invalid']) { + form.addEventListener(kind, e => { + if (e.target.id === field.id) record(kind, {key: e.key, inputType: e.inputType, trusted: e.isTrusted}); + }, true); + } + let previous = JSON.stringify(outputs()); + new MutationObserver(changes => { + const latest = JSON.stringify(outputs()); + const fieldAttributes = changes.filter(m => m.target === field && m.type === 'attributes').map(m => m.attributeName); + if (previous !== latest || fieldAttributes.length || !field.isConnected) record('DOM render observed', fieldAttributes); + previous = latest; + }).observe(form, {subtree: true, childList: true, characterData: true, attributes: true}); + if (traceWrites) { + // In the independent witness only; record the genuine setter before and after the original call. + Object.defineProperty(field, 'value', {configurable: true, + get() { return descriptor.get.call(this); }, + set(value) { + record('author value write before', {assigned: value, caller: new Error().stack?.split('\n').slice(1, 5)}); + descriptor.set.call(this, value); + record('author value write after', {assigned: value}); + } + }); + } + window.integrationQuietTrace = {steps, read}; + record('before label'); + } + """, traceWrites); + + internal static Task ReadAsync(IPage page) => page.EvaluateAsync(""" + () => JSON.stringify({ + steps: window.integrationQuietTrace?.steps ?? [], + end: window.integrationQuietTrace?.read() ?? null, + nativeBlockers: [...document.querySelectorAll('#integration-form :invalid')].map(el => el.id) + }) + """).WaitAsync(TimeSpan.FromSeconds(5)); +} From a845c44921490c07e97f7436f9903a24589042df Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 16:43:52 -0500 Subject: [PATCH 07/13] Compare framework and component time binding on native WebKit --- .../Pages/TemporalBindingProbe.razor | 78 +++++++++++++++++ .../Forms/FormPostTests.cs | 31 ++----- .../Forms/QuietTimeEvidence.cs | 24 ++++-- .../Forms/TimeBindingComparison.cs | 86 +++++++++++++++++++ 4 files changed, 184 insertions(+), 35 deletions(-) create mode 100644 gallery/Gallery.Client/Pages/TemporalBindingProbe.razor create mode 100644 tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs diff --git a/gallery/Gallery.Client/Pages/TemporalBindingProbe.razor b/gallery/Gallery.Client/Pages/TemporalBindingProbe.razor new file mode 100644 index 0000000..3999613 --- /dev/null +++ b/gallery/Gallery.Client/Pages/TemporalBindingProbe.razor @@ -0,0 +1,78 @@ +@page "/temporal-binding-probe" +@implements IDisposable +@using System.Globalization +@using FluentCMS.Components +@using Microsoft.AspNetCore.Components.Forms + + + + @if (FieldKind == "wrapped") + { + + + + } + else + { + + @if (FieldKind == "framework") + { + + } + else + { + + } + } + @_changes + @_lastChanged + @Show(Model.QuietTime) + + @_outcome + @_received + + +@code { + [SupplyParameterFromQuery(Name = "field")] private string? FieldKind { get; set; } + [SupplyParameterFromQuery(Name = "refresh")] private bool? RefreshHost { get; set; } + + private Draft Model { get; } = new(); + private EditContext _editContext = default!; + private int _changes; + private string _lastChanged = "(none)"; + private string _outcome = "(not submitted)"; + private string _received = "(not received)"; + + protected override void OnInitialized() + { + _editContext = new EditContext(Model) { ShouldUseFieldIdentifiers = true }; + _editContext.OnFieldChanged += OnFieldChanged; + } + + private void OnFieldChanged(object? sender, FieldChangedEventArgs args) + { + _changes++; + _lastChanged = args.FieldIdentifier.FieldName; + if (RefreshHost != false) + { + StateHasChanged(); + } + } + + private void Save() + { + _outcome = "Saved"; + _received = Show(Model.QuietTime); + } + + private void Reject() => _outcome = "Rejected by host"; + + private static string Show(TimeOnly? value) => value?.ToString("HH:mm:ss", CultureInfo.InvariantCulture) ?? "(empty)"; + + public void Dispose() => _editContext.OnFieldChanged -= OnFieldChanged; + + private sealed class Draft + { + public TimeOnly? QuietTime { get; set; } = new TimeOnly(9, 15, 30); + } +} diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index 579e00c..c416ef1 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -113,10 +113,9 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren } catch (Xunit.Sdk.XunitException error) { - var observed = await QuietTimeEvidence.ReadAsync(page); - string plain = await ReplayQuietTimeAsync(RenderMode.Static, traceWrites: false); - string binding = await ReplayQuietTimeAsync(mode, traceWrites: true); - throw new Xunit.Sdk.XunitException($"{error.Message}\nActual interactive: {observed}\nObservation-only static: {plain}\nInteractive setter witness: {binding}"); + var observed = await QuietTimeEvidence.ReadAsync(page, compact: true); + var comparison = await TimeBindingComparison.CompareAsync(gallery, mode); + throw new Xunit.Sdk.XunitException($"{error.Message}\nActual interactive: {observed}\n{comparison}"); } await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); @@ -202,7 +201,7 @@ private static async Task AssertSharedReviewModeAsync(IPage page) await Expect(disabled).Not.ToBeCheckedAsync(); } - private static async Task EditInitialDatesAsync(IPage page, RenderMode mode, bool traceWrites = false) + 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); @@ -217,30 +216,10 @@ private static async Task EditInitialDatesAsync(IPage page, RenderMode mode, boo { await AssertDeliveryModelAsync(page, EditedStart, EditedEnd, "09:15:30"); } - await QuietTimeEvidence.StartAsync(page, traceWrites); + await QuietTimeEvidence.StartAsync(page, traceWrites: false); await EditTemporalAsync(page, mode, "quiet", "QuietTime", "time", ""); } - private async Task ReplayQuietTimeAsync(RenderMode mode, bool traceWrites) - { - try - { - await using GalleryPage sample = await gallery.OpenAsync(mode, Path); - sample.Page.SetDefaultTimeout(5000); - await EditDraftAsync(sample.Page); - if (mode.IsInteractive()) - { - await Expect(sample.Page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); - } - await EditInitialDatesAsync(sample.Page, mode, traceWrites); - return await QuietTimeEvidence.ReadAsync(sample.Page); - } - catch (Exception error) - { - return $"Witness failed: {error.GetType().Name}: {error.Message}"; - } - } - private static async Task EditTemporalAsync(IPage page, RenderMode mode, string id, string field, string type, string value) { ILocator input = page.Locator($"#integration-{id}"); diff --git a/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs b/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs index f37c260..1aefa86 100644 --- a/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs +++ b/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs @@ -22,9 +22,10 @@ internal static Task StartAsync(IPage page, bool traceWrites) => page.EvaluateAs const record = (at, details) => { if (steps.length < 60) steps.push({t: Math.round(performance.now()), at, ...read(), details}); }; - for (const kind of ['keydown', 'keyup', 'input', 'change', 'focusin', 'focusout', 'invalid']) { + for (const kind of ['keydown', 'keyup', 'input', 'change', 'focusin', 'focusout', 'invalid', 'submit']) { form.addEventListener(kind, e => { - if (e.target.id === field.id) record(kind, {key: e.key, inputType: e.inputType, trusted: e.isTrusted}); + if (e.target.id === field.id || (kind === 'submit' && e.target === form)) + record(kind, {key: e.key, inputType: e.inputType, trusted: e.isTrusted, target: e.target.id}); }, true); } let previous = JSON.stringify(outputs()); @@ -50,11 +51,16 @@ internal static Task StartAsync(IPage page, bool traceWrites) => page.EvaluateAs } """, traceWrites); - internal static Task ReadAsync(IPage page) => page.EvaluateAsync(""" - () => JSON.stringify({ - steps: window.integrationQuietTrace?.steps ?? [], - end: window.integrationQuietTrace?.read() ?? null, - nativeBlockers: [...document.querySelectorAll('#integration-form :invalid')].map(el => el.id) - }) - """).WaitAsync(TimeSpan.FromSeconds(5)); + internal static Task ReadAsync(IPage page, bool compact = false) => page.EvaluateAsync(""" + compact => { + const all = window.integrationQuietTrace?.steps ?? []; + const lastClear = [...all].reverse().find(step => step.at === 'keyup' && step.details?.key === 'Backspace'); + return JSON.stringify({ + steps: compact ? all.filter(step => step === lastClear || step.at === 'before label' || step.at === 'change' + || step.at === 'focusout' || step.at === 'DOM render observed' || step.at.startsWith('author value write')) : all, + end: window.integrationQuietTrace?.read() ?? null, + nativeBlockers: [...document.querySelectorAll('#integration-form :invalid')].map(el => el.id) + }); + } + """, compact).WaitAsync(TimeSpan.FromSeconds(5)); } diff --git a/tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs b/tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs new file mode 100644 index 0000000..5a84d19 --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs @@ -0,0 +1,86 @@ +using FluentCMS.Components.Browser.Harness; +using Microsoft.Playwright; +using static Microsoft.Playwright.Assertions; + +namespace FluentCMS.Components.Browser.Forms; + +internal static class TimeBindingComparison +{ + internal static async Task CompareAsync(GalleryFixture gallery, RenderMode mode) + { + var cases = new List(); + foreach (string field in new[] { "framework", "component", "wrapped" }) + { + cases.Add(await RunAsync(gallery, mode, field, refresh: true)); + } + if (cases.All(result => result.NativeBlocked)) + { + cases.Add(await RunAsync(gallery, mode, "framework", refresh: false)); + } + return string.Join('\n', cases.Select(result => result.Description)); + } + + private static async Task RunAsync(GalleryFixture gallery, RenderMode mode, string field, bool refresh) + { + string prefix = $"Time comparison {field}, explicit field-change refresh={refresh}"; + try + { + await using GalleryPage sample = await gallery.OpenAsync(mode, $"temporal-binding-probe?field={field}&refresh={(refresh ? "true" : "false")}"); + IPage page = sample.Page; + page.SetDefaultTimeout(5000); + ILocator input = page.Locator("#integration-quiet"); + await Expect(input).ToHaveAttributeAsync("type", "time"); + await Expect(input).ToHaveAttributeAsync("step", "1"); + await Expect(input).ToHaveAttributeAsync("name", "Model.QuietTime"); + await Expect(input).ToHaveValueAsync("09:15:30"); + await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("0"); + + await QuietTimeEvidence.StartAsync(page, traceWrites: true); + await TemporalInput.ClearOptionalAsync(page, "integration-quiet"); + await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("1"); + await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("QuietTime"); + await Expect(page.Locator("#integration-model-quiet")).ToHaveTextAsync("(empty)"); + ILocator save = page.Locator("#integration-save"); + Assert.True(await save.EvaluateAsync("el => !el.form.noValidate && !el.formNoValidate")); + bool invalid = await input.EvaluateAsync("el => el.matches(':invalid')"); + string before = await QuietTimeEvidence.ReadAsync(page, compact: true); + + // Observation only: normal Save with constraints still active, even in a blocked witness. + await save.ClickAsync(); + bool submitted = await page.EvaluateAsync("window.integrationQuietTrace.steps.some(step => step.at === 'submit')"); + ILocator outcome = page.Locator("#probe-outcome"); + ILocator receiver = page.Locator("#probe-received"); + string? mismatch = null; + try + { + Assert.Equal(!invalid, submitted); + if (submitted) + { + await Expect(outcome).ToHaveTextAsync("Saved"); + await Expect(receiver).ToHaveTextAsync("(empty)"); + } + else + { + await Expect(input).ToBeFocusedAsync(); + await Expect(outcome).ToHaveTextAsync("(not submitted)"); + } + } + catch (Exception error) when (error is Xunit.Sdk.XunitException or PlaywrightException) + { + mismatch = error.Message; + } + string label = $"{prefix}: :invalid before Save={invalid}; submit={submitted}; host={await outcome.TextContentAsync()}; receiver={await receiver.TextContentAsync()}"; + string[] saveEvents = await page.EvaluateAsync(""" + window.integrationQuietTrace.steps.filter(step => step.at === 'submit' || step.at === 'invalid').map(step => `${step.at}: ${step.details.target}; active=${step.active}`) + """); + return new Witness(invalid && !submitted && mismatch is null, + $"{label}\nBefore Save witness: {before}\nSave events: {string.Join(", ", saveEvents)}" + (mismatch is null ? "" : $"\nWitness mismatch: {mismatch}")); + } + catch (Exception error) + { + return new Witness(false, $"{prefix}: witness failed ({error.GetType().Name}): {error.Message}"); + } + } + + private sealed record Witness(bool NativeBlocked, string Description); +} From bf30970530954abc46d766d2075d101d169ab4ed Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 16:57:58 -0500 Subject: [PATCH 08/13] Remove temporary time binding diagnostics --- .../Pages/TemporalBindingProbe.razor | 78 ----------------- .../Forms/FormPostTests.cs | 12 +-- .../Forms/QuietTimeEvidence.cs | 66 -------------- .../Forms/TimeBindingComparison.cs | 86 ------------------- 4 files changed, 1 insertion(+), 241 deletions(-) delete mode 100644 gallery/Gallery.Client/Pages/TemporalBindingProbe.razor delete mode 100644 tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs delete mode 100644 tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs diff --git a/gallery/Gallery.Client/Pages/TemporalBindingProbe.razor b/gallery/Gallery.Client/Pages/TemporalBindingProbe.razor deleted file mode 100644 index 3999613..0000000 --- a/gallery/Gallery.Client/Pages/TemporalBindingProbe.razor +++ /dev/null @@ -1,78 +0,0 @@ -@page "/temporal-binding-probe" -@implements IDisposable -@using System.Globalization -@using FluentCMS.Components -@using Microsoft.AspNetCore.Components.Forms - - - - @if (FieldKind == "wrapped") - { - - - - } - else - { - - @if (FieldKind == "framework") - { - - } - else - { - - } - } - @_changes - @_lastChanged - @Show(Model.QuietTime) - - @_outcome - @_received - - -@code { - [SupplyParameterFromQuery(Name = "field")] private string? FieldKind { get; set; } - [SupplyParameterFromQuery(Name = "refresh")] private bool? RefreshHost { get; set; } - - private Draft Model { get; } = new(); - private EditContext _editContext = default!; - private int _changes; - private string _lastChanged = "(none)"; - private string _outcome = "(not submitted)"; - private string _received = "(not received)"; - - protected override void OnInitialized() - { - _editContext = new EditContext(Model) { ShouldUseFieldIdentifiers = true }; - _editContext.OnFieldChanged += OnFieldChanged; - } - - private void OnFieldChanged(object? sender, FieldChangedEventArgs args) - { - _changes++; - _lastChanged = args.FieldIdentifier.FieldName; - if (RefreshHost != false) - { - StateHasChanged(); - } - } - - private void Save() - { - _outcome = "Saved"; - _received = Show(Model.QuietTime); - } - - private void Reject() => _outcome = "Rejected by host"; - - private static string Show(TimeOnly? value) => value?.ToString("HH:mm:ss", CultureInfo.InvariantCulture) ?? "(empty)"; - - public void Dispose() => _editContext.OnFieldChanged -= OnFieldChanged; - - private sealed class Draft - { - public TimeOnly? QuietTime { get; set; } = new TimeOnly(9, 15, 30); - } -} diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index c416ef1..f6498d0 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -107,16 +107,7 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); await EditInitialDatesAsync(page, mode); var address = new Uri(page.Url); - try - { - await ClickSaveAsync(page); - } - catch (Xunit.Sdk.XunitException error) - { - var observed = await QuietTimeEvidence.ReadAsync(page, compact: true); - var comparison = await TimeBindingComparison.CompareAsync(gallery, mode); - throw new Xunit.Sdk.XunitException($"{error.Message}\nActual interactive: {observed}\n{comparison}"); - } + await ClickSaveAsync(page); await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); await AssertSharedReviewModeAsync(page); @@ -216,7 +207,6 @@ private static async Task EditInitialDatesAsync(IPage page, RenderMode mode) { await AssertDeliveryModelAsync(page, EditedStart, EditedEnd, "09:15:30"); } - await QuietTimeEvidence.StartAsync(page, traceWrites: false); await EditTemporalAsync(page, mode, "quiet", "QuietTime", "time", ""); } diff --git a/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs b/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs deleted file mode 100644 index 1aefa86..0000000 --- a/tests/FluentCMS.Components.Browser/Forms/QuietTimeEvidence.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Microsoft.Playwright; - -namespace FluentCMS.Components.Browser.Forms; - -internal static class QuietTimeEvidence -{ - internal static Task StartAsync(IPage page, bool traceWrites) => page.EvaluateAsync(""" - traceWrites => { - if (matchMedia('(scripting: none)').matches) return; - const field = document.querySelector('#integration-quiet'); - const form = field.form; - const outputIds = ['integration-change-count', 'integration-last-change', 'integration-model-quiet']; - const outputs = () => outputIds.map(id => document.getElementById(id).textContent.trim()); - const descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); - const read = () => { - const el = document.getElementById(field.id); - return {sameNode: el === field, type: el.type, value: descriptor.get.call(el), defaultValue: el.defaultValue, - valid: el.validity.valid, badInput: el.validity.badInput, invalid: el.matches(':invalid'), - active: document.activeElement?.id, model: outputs()}; - }; - const steps = []; - const record = (at, details) => { - if (steps.length < 60) steps.push({t: Math.round(performance.now()), at, ...read(), details}); - }; - for (const kind of ['keydown', 'keyup', 'input', 'change', 'focusin', 'focusout', 'invalid', 'submit']) { - form.addEventListener(kind, e => { - if (e.target.id === field.id || (kind === 'submit' && e.target === form)) - record(kind, {key: e.key, inputType: e.inputType, trusted: e.isTrusted, target: e.target.id}); - }, true); - } - let previous = JSON.stringify(outputs()); - new MutationObserver(changes => { - const latest = JSON.stringify(outputs()); - const fieldAttributes = changes.filter(m => m.target === field && m.type === 'attributes').map(m => m.attributeName); - if (previous !== latest || fieldAttributes.length || !field.isConnected) record('DOM render observed', fieldAttributes); - previous = latest; - }).observe(form, {subtree: true, childList: true, characterData: true, attributes: true}); - if (traceWrites) { - // In the independent witness only; record the genuine setter before and after the original call. - Object.defineProperty(field, 'value', {configurable: true, - get() { return descriptor.get.call(this); }, - set(value) { - record('author value write before', {assigned: value, caller: new Error().stack?.split('\n').slice(1, 5)}); - descriptor.set.call(this, value); - record('author value write after', {assigned: value}); - } - }); - } - window.integrationQuietTrace = {steps, read}; - record('before label'); - } - """, traceWrites); - - internal static Task ReadAsync(IPage page, bool compact = false) => page.EvaluateAsync(""" - compact => { - const all = window.integrationQuietTrace?.steps ?? []; - const lastClear = [...all].reverse().find(step => step.at === 'keyup' && step.details?.key === 'Backspace'); - return JSON.stringify({ - steps: compact ? all.filter(step => step === lastClear || step.at === 'before label' || step.at === 'change' - || step.at === 'focusout' || step.at === 'DOM render observed' || step.at.startsWith('author value write')) : all, - end: window.integrationQuietTrace?.read() ?? null, - nativeBlockers: [...document.querySelectorAll('#integration-form :invalid')].map(el => el.id) - }); - } - """, compact).WaitAsync(TimeSpan.FromSeconds(5)); -} diff --git a/tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs b/tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs deleted file mode 100644 index 5a84d19..0000000 --- a/tests/FluentCMS.Components.Browser/Forms/TimeBindingComparison.cs +++ /dev/null @@ -1,86 +0,0 @@ -using FluentCMS.Components.Browser.Harness; -using Microsoft.Playwright; -using static Microsoft.Playwright.Assertions; - -namespace FluentCMS.Components.Browser.Forms; - -internal static class TimeBindingComparison -{ - internal static async Task CompareAsync(GalleryFixture gallery, RenderMode mode) - { - var cases = new List(); - foreach (string field in new[] { "framework", "component", "wrapped" }) - { - cases.Add(await RunAsync(gallery, mode, field, refresh: true)); - } - if (cases.All(result => result.NativeBlocked)) - { - cases.Add(await RunAsync(gallery, mode, "framework", refresh: false)); - } - return string.Join('\n', cases.Select(result => result.Description)); - } - - private static async Task RunAsync(GalleryFixture gallery, RenderMode mode, string field, bool refresh) - { - string prefix = $"Time comparison {field}, explicit field-change refresh={refresh}"; - try - { - await using GalleryPage sample = await gallery.OpenAsync(mode, $"temporal-binding-probe?field={field}&refresh={(refresh ? "true" : "false")}"); - IPage page = sample.Page; - page.SetDefaultTimeout(5000); - ILocator input = page.Locator("#integration-quiet"); - await Expect(input).ToHaveAttributeAsync("type", "time"); - await Expect(input).ToHaveAttributeAsync("step", "1"); - await Expect(input).ToHaveAttributeAsync("name", "Model.QuietTime"); - await Expect(input).ToHaveValueAsync("09:15:30"); - await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("0"); - - await QuietTimeEvidence.StartAsync(page, traceWrites: true); - await TemporalInput.ClearOptionalAsync(page, "integration-quiet"); - await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("1"); - await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("QuietTime"); - await Expect(page.Locator("#integration-model-quiet")).ToHaveTextAsync("(empty)"); - ILocator save = page.Locator("#integration-save"); - Assert.True(await save.EvaluateAsync("el => !el.form.noValidate && !el.formNoValidate")); - bool invalid = await input.EvaluateAsync("el => el.matches(':invalid')"); - string before = await QuietTimeEvidence.ReadAsync(page, compact: true); - - // Observation only: normal Save with constraints still active, even in a blocked witness. - await save.ClickAsync(); - bool submitted = await page.EvaluateAsync("window.integrationQuietTrace.steps.some(step => step.at === 'submit')"); - ILocator outcome = page.Locator("#probe-outcome"); - ILocator receiver = page.Locator("#probe-received"); - string? mismatch = null; - try - { - Assert.Equal(!invalid, submitted); - if (submitted) - { - await Expect(outcome).ToHaveTextAsync("Saved"); - await Expect(receiver).ToHaveTextAsync("(empty)"); - } - else - { - await Expect(input).ToBeFocusedAsync(); - await Expect(outcome).ToHaveTextAsync("(not submitted)"); - } - } - catch (Exception error) when (error is Xunit.Sdk.XunitException or PlaywrightException) - { - mismatch = error.Message; - } - string label = $"{prefix}: :invalid before Save={invalid}; submit={submitted}; host={await outcome.TextContentAsync()}; receiver={await receiver.TextContentAsync()}"; - string[] saveEvents = await page.EvaluateAsync(""" - window.integrationQuietTrace.steps.filter(step => step.at === 'submit' || step.at === 'invalid').map(step => `${step.at}: ${step.details.target}; active=${step.active}`) - """); - return new Witness(invalid && !submitted && mismatch is null, - $"{label}\nBefore Save witness: {before}\nSave events: {string.Join(", ", saveEvents)}" + (mismatch is null ? "" : $"\nWitness mismatch: {mismatch}")); - } - catch (Exception error) - { - return new Witness(false, $"{prefix}: witness failed ({error.GetType().Name}): {error.Message}"); - } - } - - private sealed record Witness(bool NativeBlocked, string Description); -} From 5bdbdee4e9e0d46a19f320094e5b7b64b2481168 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 17:04:11 -0500 Subject: [PATCH 09/13] Cover unchanged and changing field validation refresh --- .../Forms/FlFieldTests.cs | 115 +++++++++++++++++- 1 file changed, 114 insertions(+), 1 deletion(-) diff --git a/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs b/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs index 164f32f..0cd9ba0 100644 --- a/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs +++ b/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs @@ -91,6 +91,117 @@ 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); + 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 => + { + Input(builder, 0, () => _model.Width, "Width"); + Input(builder, 10, () => _model.Height, "Height"); + })))); + var field = cut.FindComponent(); + 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 = field.RenderCount; + + await cut.InvokeAsync(() => + { + messages.Clear(); + messages.Add(edit.Field(nameof(Project.Height)), message); + edit.NotifyValidationStateChanged(); + }); + Assert.Equal(rendersWithMessage, field.RenderCount); + 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(); + 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; + var cut = _context.Render>(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 => Input(builder, 0, () => _model.Email, null, active))))); + var field = cut.FindComponent().Instance; + Assert.Equal("Previous context error.", cut.Find(".fl-field__error").TextContent); + + active = next; + cut.Render(p => p.Add(c => c.Value, active)); + 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() { @@ -197,9 +308,10 @@ private static void Field(RenderTreeBuilder builder, string label, string help, builder.CloseComponent(); } - private static void Input(RenderTreeBuilder builder, int sequence, Expression> expression, string? ariaLabel) + private static void Input(RenderTreeBuilder builder, int sequence, Expression> expression, string? ariaLabel, object? key = null) { builder.OpenComponent(sequence); + builder.SetKey(key); builder.AddComponentParameter(sequence + 1, nameof(FlTextInput.Value), expression.Compile()()); builder.AddComponentParameter(sequence + 2, nameof(FlTextInput.ValueChanged), EventCallback.Factory.Create(new object(), _ => { })); builder.AddComponentParameter(sequence + 3, nameof(FlTextInput.ValueExpression), expression); @@ -217,5 +329,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); } } From 8eac03ea1146200c6502f724a4acd973a4f4dc3f Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 17:06:46 -0500 Subject: [PATCH 10/13] Refresh field only when its rendered validation error changes --- src/FluentCMS.Components/Forms/FlField.razor | 5 ++- .../Forms/FlField.razor.cs | 10 +++++- .../Forms/FlFieldTests.cs | 34 ++++++++++++++----- 3 files changed, 39 insertions(+), 10 deletions(-) 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.Tests/Forms/FlFieldTests.cs b/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs index 0cd9ba0..5b4ed6c 100644 --- a/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs +++ b/tests/FluentCMS.Components.Tests/Forms/FlFieldTests.cs @@ -128,14 +128,15 @@ public async Task AnUnchangedGroupMessageKeepsItsOwnerWhileIndividualInvalidStat 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"); })))); - var field = cut.FindComponent(); string id = cut.Find("input[aria-label=Width]").Id!; await cut.InvokeAsync(() => @@ -145,7 +146,7 @@ await cut.InvokeAsync(() => }); Assert.Equal(message, cut.Find($"#{id}__error").TextContent); Assert.Equal("true", cut.Find("input[aria-label=Width]").GetAttribute("aria-invalid")); - int rendersWithMessage = field.RenderCount; + int rendersWithMessage = contentRenders; await cut.InvokeAsync(() => { @@ -153,7 +154,7 @@ await cut.InvokeAsync(() => messages.Add(edit.Field(nameof(Project.Height)), message); edit.NotifyValidationStateChanged(); }); - Assert.Equal(rendersWithMessage, field.RenderCount); + 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")); @@ -162,6 +163,14 @@ await cut.InvokeAsync(() => 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(); @@ -181,14 +190,24 @@ public async Task ReplacingTheEditContextKeepsOnlyTheCurrentValidationSubscripti var nextMessages = new ValidationMessageStore(next); originalMessages.Add(original.Field(nameof(Project.Email)), "Previous context error."); EditContext active = original; - var cut = _context.Render>(p => p.Add(c => c.Value, active) + 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 => Input(builder, 0, () => _model.Email, null, active))))); + .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(p => p.Add(c => c.Value, active)); + 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."); @@ -308,10 +327,9 @@ private static void Field(RenderTreeBuilder builder, string label, string help, builder.CloseComponent(); } - private static void Input(RenderTreeBuilder builder, int sequence, Expression> expression, string? ariaLabel, object? key = null) + private static void Input(RenderTreeBuilder builder, int sequence, Expression> expression, string? ariaLabel) { builder.OpenComponent(sequence); - builder.SetKey(key); builder.AddComponentParameter(sequence + 1, nameof(FlTextInput.Value), expression.Compile()()); builder.AddComponentParameter(sequence + 2, nameof(FlTextInput.ValueChanged), EventCallback.Factory.Create(new object(), _ => { })); builder.AddComponentParameter(sequence + 3, nameof(FlTextInput.ValueExpression), expression); From a312f3b2e9354d12266118864a9d1975aa2f5c2b Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 17:37:04 -0500 Subject: [PATCH 11/13] Exercise landed native choices in the named form --- docs/guides/static-edit-form.md | 7 +- gallery/Gallery.Client/Pages/FormPost.razor | 18 ++++- .../Forms/FormPostPrerenderTests.cs | 10 ++- .../Forms/FormPostTests.cs | 67 +++++++++++++++++-- 4 files changed, 92 insertions(+), 10 deletions(-) diff --git a/docs/guides/static-edit-form.md b/docs/guides/static-edit-form.md index 2a8ad48..97f8f49 100644 --- a/docs/guides/static-edit-form.md +++ b/docs/guides/static-edit-form.md @@ -6,7 +6,7 @@ The gallery's `form-post` page uses the library controls in one named `EditForm` 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 draft fixture currently uses the merged field, text input, text area, number, select, segmented, date and time controls. The dedicated checkbox, radio-group and switch cases are pending; the fixture does not stand them in with HTML or faked values. +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 @@ -21,6 +21,9 @@ Open the printed address at `/static/form-post`; the same form is available at ` | 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. | @@ -41,7 +44,7 @@ An explicit `name` wins, including from an attribute dictionary. Keep the receiv ## 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. The native radios skip disabled **Owners only** and choose **Shared**. **Save draft** sends an actual POST with one review-mode value. `18` is a valid number and within the browser's range of 1–100, but the host allows only 1–12. The field group owns the date error once, before its help and external description, and the inputs keep their edited values, including the selected review mode. Correct the two errors and save again. The result lists what the handler received. +- 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. Follow **Include the city in submit validation** to open a fresh draft where the host also validates that property. This 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. diff --git a/gallery/Gallery.Client/Pages/FormPost.razor b/gallery/Gallery.Client/Pages/FormPost.razor index b0fac65..eaa14a3 100644 --- a/gallery/Gallery.Client/Pages/FormPost.razor +++ b/gallery/Gallery.Client/Pages/FormPost.razor @@ -49,6 +49,12 @@ + + + + + +
@@ -75,7 +81,7 @@
-

The segmented review mode submits one choice. Checks for the dedicated checkbox, radio-group and switch controls are not in this fixture yet.

+

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

@@ -88,6 +94,7 @@ 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(); @@ -116,6 +123,7 @@ 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"; } @@ -163,6 +171,8 @@ ("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)), @@ -178,6 +188,8 @@ 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; @@ -200,6 +212,10 @@ 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; } diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs index c2623e0..3bc0d8d 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostPrerenderTests.cs @@ -33,7 +33,7 @@ await page.RouteAsync("**/_framework/blazor.web*.js", async route => await FieldIdentity.AssertAsync(page); before = await main.EvaluateAsync(""" main => { - const fields = root => [...root.querySelectorAll('#integration-form .fl-field')]; + 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); @@ -44,7 +44,7 @@ await page.RouteAsync("**/_framework/blazor.web*.js", async route => [...copy.querySelectorAll('input, textarea, select')].forEach((input, i) => { input.removeAttribute('value'); input.setAttribute('data-live-value', originals[i].value); - if (input.type === 'radio') { + if (input.type === 'radio' || input.type === 'checkbox') { input.removeAttribute('checked'); input.setAttribute('data-live-checked', originals[i].checked); } @@ -81,7 +81,7 @@ await page.RouteAsync("**/_framework/blazor.web*.js", async route => resume.TrySetResult(); } - Assert.Equal(12, before.Length); + 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")); @@ -89,6 +89,10 @@ await page.RouteAsync("**/_framework/blazor.web*.js", async route => 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 index f6498d0..0383b0a 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -35,7 +35,7 @@ public async Task NativePostPreservesValuesAfterValidationAndSavesCorrected(Rend { await using IBrowserContext context = await gallery.Browser.NewContextAsync(new() { JavaScriptEnabled = false }); IPage page = await OpenStaticAsync(context, mode); - await EditDraftAsync(page); + 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"), @@ -46,6 +46,7 @@ public async Task NativePostPreservesValuesAfterValidationAndSavesCorrected(Rend await AssertInvalidDraftAsync(page); await AssertReturnedControlsAsync(page); await AssertSharedReviewModeAsync(page); + await AssertNativeChoicesAsync(page); await CorrectDraftAsync(page, mode); NameValueCollection corrected = await PostAsync(page, "#integration-save"); @@ -53,6 +54,7 @@ public async Task NativePostPreservesValuesAfterValidationAndSavesCorrected(Rend await AssertSavedDraftAsync(page, mode); await AssertReturnedControlsAsync(page, successful: true); await AssertSharedReviewModeAsync(page); + await AssertNativeChoicesAsync(page); await FieldIdentity.AssertAsync(page); } @@ -103,19 +105,21 @@ public async Task InteractiveChangesNotifyAndUseTheSameValidationAndReceiver(Ren await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("Language"); await Expect(page.Locator("#integration-change-count")).ToHaveTextAsync("2"); - await EditDraftAsync(page); - await Expect(page.Locator("#integration-last-change")).ToHaveTextAsync("ReviewMode"); + 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); @@ -147,7 +151,7 @@ private async Task OpenStaticAsync(IBrowserContext context, RenderMode mo return page; } - private static async Task EditDraftAsync(IPage page) + private static async Task EditDraftAsync(IPage page, RenderMode mode) { foreach (var (id, _, value) in DraftEdits) { @@ -166,6 +170,24 @@ private static async Task EditDraftAsync(IPage page) } } + 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(); @@ -176,6 +198,18 @@ private static async Task EditDraftAsync(IPage page) 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) @@ -192,6 +226,23 @@ private static async Task AssertSharedReviewModeAsync(IPage page) 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"); @@ -286,6 +337,10 @@ private static void AssertWire(NameValueCollection form, bool successful = false 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"]); } @@ -339,6 +394,10 @@ private static async Task AssertSavedDraftAsync(IPage page, RenderMode mode) // 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)"); } From 0fab8aa8b57560a67eeffea5a5a73d80a1ba838e Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 17:54:34 -0500 Subject: [PATCH 12/13] Cover interactive nested validation navigation --- .../Forms/FormPostTests.cs | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs index 0383b0a..39e5ae1 100644 --- a/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/FormPostTests.cs @@ -91,6 +91,76 @@ public async Task TopLevelValidationDoesNotImplyNestedValidation(RenderMode mode 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) From 3d27327caa84d021bf9db0b5bcbd7fbb4cd948cd Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Sat, 28 Nov 2026 17:55:44 -0500 Subject: [PATCH 13/13] Keep nested validation in sync with interactive query links --- docs/guides/static-edit-form.md | 2 +- gallery/Gallery.Client/Pages/FormPost.razor | 23 ++++++++++++++------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/docs/guides/static-edit-form.md b/docs/guides/static-edit-form.md index 97f8f49..f938554 100644 --- a/docs/guides/static-edit-form.md +++ b/docs/guides/static-edit-form.md @@ -46,7 +46,7 @@ An explicit `name` wins, including from an attribute dictionary. Keep the receiv - 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. Follow **Include the city in submit validation** to open a fresh draft where the host also validates that property. This 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. +- 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). diff --git a/gallery/Gallery.Client/Pages/FormPost.razor b/gallery/Gallery.Client/Pages/FormPost.razor index eaa14a3..7601c93 100644 --- a/gallery/Gallery.Client/Pages/FormPost.razor +++ b/gallery/Gallery.Client/Pages/FormPost.razor @@ -106,13 +106,14 @@ private string? Alias { get; set; } private EditContext _editContext = default!; - private ValidationMessageStore? _cityMessages; + 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() { @@ -135,11 +136,18 @@ Model.Tags = tags; } _editContext = new EditContext(Model) { ShouldUseFieldIdentifiers = true }; + _cityMessages = new ValidationMessageStore(_editContext); _editContext.OnFieldChanged += OnFieldChanged; - if (CheckCity) + _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 = new ValidationMessageStore(_editContext); - _editContext.OnValidationRequested += ValidateCity; + _cityMessages.Clear(); + _editContext.NotifyValidationStateChanged(); } } @@ -154,11 +162,10 @@ private void ValidateCity(object? sender, ValidationRequestedEventArgs args) { - _cityMessages!.Clear(); - AddressDraft address = Model!.Address; - if (!CityRule.IsValid(address.City)) + _cityMessages.Clear(); + if (CheckCity && !CityRule.IsValid(Model!.Address.City)) { - _cityMessages.Add(new FieldIdentifier(address, nameof(AddressDraft.City)), CityRequired); + _cityMessages.Add(CityField, CityRequired); } }