diff --git a/docs/guides/settings-reference.md b/docs/guides/settings-reference.md new file mode 100644 index 0000000..9e2f83e --- /dev/null +++ b/docs/guides/settings-reference.md @@ -0,0 +1,44 @@ +# Staged settings reference + +Run the gallery and open `/static/settings`, `/server/settings` or `/wasm/settings` at its printed address. The five sections are Identity, Language and region, Content, Access and Danger zone. This is the C1 gallery route for [#76](https://github.com/fluentcms/FluentCMS.Components/issues/76), not the CMS and not a preview of the later controls. + +## Try the save workflow + +1. On the static route with JavaScript disabled, edit the name, description, locale and publication time. Enter `500` in Items per page and activate **Save changes**. The named native form posts those values with antiforgery. The form deliberately lets this invalid range reach the host, as in the reference screen. The host rejects it and returns the submitted edits with an error on Items per page. +2. Tab to **Go to the field** and activate it. Focus reaches the labelled number input without replacing the document or dropping its query and edits. Its description starts with the error and includes the help and the unit. Enter `45`, then save. **Settings saved** reports the received sample values. +3. Before submitting, **Discard changes** in a script-free browser resets to the values of the current document. After a response, those defaults are the ones in that response. In Server and WASM, Discard instead restores the last accepted in-memory sample, clears validation, and replaces the form's edit context. A full reload starts a new sample. +4. **Preview deleting the site** opens a native disclosure with a confirmation message. There is no delete command or endpoint. The logo input opens the browser's real chooser but has no form name: it sends no file or filename. The browser does not restore a selected file after a document is replaced, and this route makes no promise to keep file handles. + +The form uses `DataAnnotationsValidator` on its sample model, not a component validator. Radio groups keep one label and help description on their field; individual options keep their own labels and descriptions. A native POST sends one choice per radio group, `true` for checked checkboxes and switches, and no entry for unchecked or disabled toggles. The badge marks values different from the last accepted sample. A successful save or interactive Discard clears it. A native reset without JavaScript restores the current document's inputs; it cannot remove a badge rendered on an invalid response. In the interactive host a small same-origin gallery module focuses the correction target; Blazor's fragment navigation otherwise only scrolls. Without JavaScript the same link is an ordinary browser fragment. Neither path promises to retain focus or an uncommitted edit across interactive takeover. + +**Windows Playwright WebKit limitation.** This build uses a text fallback for publication time. With JavaScript disabled, a valid typed time can be posted; malformed text was posted and received as an empty optional time without a field error. In interactive modes, editing to `10:15` left the receiver at `09:00` because the fallback's change did not reach Blazor. The keyboard correction check without a time edit verifies focus and the page-size save, not temporal binding. This is not a Safari result. + +## What is staged and who replaces it + +| In this gallery | Replacement owner | +| --- | --- | +| Gallery chrome, native section links and an inline validation summary. No new shell, sticky band or tabs component. | [#85 — shared shell, navigation, tabs and persistent alert](https://github.com/fluentcms/FluentCMS.Components/issues/85). | +| Named inline save status; locale checkboxes and zone select instead of searchable choices; harmless deletion disclosure. | [#93 — notification, combobox and dialog retrofits](https://github.com/fluentcms/FluentCMS.Components/issues/93). | +| Labelled native logo chooser; no upload or storage. | [#95 — file drop zone and actual logo-upload retrofit](https://github.com/fluentcms/FluentCMS.Components/issues/95). | +| Existing gallery page navigation, with no imitation global search. | [#85 — native search in the shared shell](https://github.com/fluentcms/FluentCMS.Components/issues/85), then [#96 — global search and command palette parity](https://github.com/fluentcms/FluentCMS.Components/issues/96). | + +## Relevant reference workarounds + +The reference at [design/system/screens/settings.html](../../design/system/screens/settings.html) loads [screens.css](../../design/system/screens/screens.css). This gallery keeps the following ownership record for [#27](https://github.com/fluentcms/FluentCMS.Components/issues/27), without copying the complete reference stylesheet: + +| Reference rule | In the staged route | Owner | +| --- | --- | --- | +| `screen-page`, `screen-form` | The gallery has a local 50rem reading measure for these five cards. | Shared shell and page measure in #85; page-container item in #27. | +| `screen-band`, `screen-band--sticky`, `screen-band--tabs` | A normal page header and section links. Save is not in a sticky shell band. | #85. | +| `screen-wide`, `screen-narrow`, `screen-search`, `screen-identity` | Not copied: the gallery has no application search/locale/avatar frame to collapse or truncate. | #85 for the frame and narrow header, #96 for search parity; shell and avatar notes in #27. | +| `screen-short` | Scoped maximum width only for Items per page and Time of a publication. | Input width follow-up under #27. | +| `screen-tall`, `screen-tall--start` | Scoped horizontal tall-row layout keeps a label and its help together. The native logo chooser is short and does not need the drop-zone offset. | Horizontal field behavior under #27; #95 for the logo retrofit. | +| Danger card/action | The card is ordinary; the native preview trigger carries danger styling. | #93 for the confirmation dialog, with the card tone/action question tracked in #27. | + +## Automated checks + +```powershell +dotnet test --project tests/FluentCMS.Components.Browser --filter-class 'FluentCMS.Components.Browser.Forms.SiteSettings*' +``` + +Run with `FLUENTCMS_MODES` unset to cover all three render modes. The scoped tests check the actual posted and retained values, range validation, native and interactive reset, keyboard focus, first interactive markup, axe and small-width targets. The visual comparison uses actual HTTP pages and records differences due to the staged controls and gallery chrome; it does not claim full reference parity. diff --git a/gallery/Gallery.Client/GalleryPages.cs b/gallery/Gallery.Client/GalleryPages.cs index 37a779b..3fc630b 100644 --- a/gallery/Gallery.Client/GalleryPages.cs +++ b/gallery/Gallery.Client/GalleryPages.cs @@ -23,6 +23,7 @@ public static class GalleryPages new("segmented", "Segmented"), new("date-time", "Date and time"), new("form-post", "Form submission"), + new("settings", "Site settings"), new("tokens", "Tokens"), new("theme-provider", "Theme provider"), new("patterns", "Patterns"), diff --git a/gallery/Gallery.Client/Pages/SiteSettings.razor b/gallery/Gallery.Client/Pages/SiteSettings.razor new file mode 100644 index 0000000..cd35aed --- /dev/null +++ b/gallery/Gallery.Client/Pages/SiteSettings.razor @@ -0,0 +1,295 @@ +@page "/settings" +@using System.ComponentModel.DataAnnotations +@using System.Globalization +@using FluentCMS.Components +@using Microsoft.AspNetCore.Components.Forms +@inject IJSRuntime JS +@inject NavigationManager Navigation + +Site settings — FluentCMS Components + + + Settings sections + @foreach (var section in Sections) + { + @section.Title + } + + + + +@code { + private static readonly (string Id, string Title)[] Sections = + [ + ("settings-identity", "Identity"), ("settings-region", "Language and region"), ("settings-content", "Content"), + ("settings-access", "Access"), ("settings-danger", "Danger zone"), + ]; + private static readonly FlSelectOption[] Locales = [new("en", "English (EN)"), new("fr", "Français (FR)"), new("de", "Deutsch (DE)")]; + private static readonly FlSelectOption[] Zones = [new("Europe/Berlin", "Europe/Berlin"), new("Europe/Lisbon", "Europe/Lisbon"), new("America/New_York", "America/New_York")]; + private static readonly FlRadioOption[] DateFormats = + [ + new("written", "26 November 2026"), new("day-first", "26/11/2026"), new("month-first", "11/26/2026"), new("iso", "2026-11-26"), + ]; + private static readonly FlRadioOption[] SignupChoices = + [ + new("invited", "Invited people only") { Description = "An administrator sends each invitation." }, + new("domain", "People with an address at northwind.example") { Description = "They join as authors once the address is confirmed." }, + new("anyone", "Anyone") { Description = "A new account can read drafts until it is given a role." }, + ]; + + // Appearance links update the layout without replacing this page; refresh its fragment links too. + [CascadingParameter] private GalleryContext Context { get; set; } = default!; + [SupplyParameterFromForm(FormName = "settings-sample")] + private SampleSettings? Settings { get; set; } + private EditContext _editContext = default!; + private SampleSettings _accepted = new() + { + SiteName = "Northwind Journal", Description = "Stories, release notes and guides from the people who build Northwind.", + Locale = "en", English = true, French = true, German = true, TimeZone = "Europe/Berlin", DateFormat = "written", + ItemsPerPage = 25, PublishTime = new TimeOnly(9, 0), ScheduledPublishing = true, AiAssist = true, + Signup = "invited", MailSignup = true, MailFailure = true, + }; + private SampleSettings? _saved; + private bool _submitted; + private bool _discarded; + + private bool VersionHistory => true; + private bool HasUnsavedChanges => Settings != _accepted; + + // The base points at the mode root; keep the exact settings document URL for a same-page link. + private string FragmentHref(string id) => $"{Navigation.Uri.Split('#', 2)[0]}#{id}"; + + private string? CorrectionId => !_submitted ? null + : HasError(nameof(SampleSettings.ItemsPerPage)) ? "set-page-size" + : HasError(nameof(SampleSettings.SiteName)) ? "set-name" + : HasError(nameof(SampleSettings.Description)) ? "set-description" : null; + + protected override void OnInitialized() + { + Settings ??= _accepted with { }; + _editContext = new EditContext(Settings) { ShouldUseFieldIdentifiers = true }; + } + + private bool HasError(string field) => _editContext.GetValidationMessages(_editContext.Field(field)).Any(); + + private async Task FocusCorrectionAsync(string id) + { + // The interactive router scrolls to the hash but does not focus its target. + await using var module = await JS.InvokeAsync("import", "./settings-focus.js"); + await module.InvokeVoidAsync("focusCorrection", id); + } + + private void Save() + { + _accepted = Settings! with { }; + _saved = _accepted; + _submitted = false; + _discarded = false; + } + + private void NotSaved() + { + _submitted = true; + _discarded = false; + _saved = null; + } + + private void Discard() + { + Settings = _accepted with { }; + _editContext = new EditContext(Settings) { ShouldUseFieldIdentifiers = true }; + _saved = null; + _submitted = false; + _discarded = true; + } + + private static string TimeValue(TimeOnly? value) => value?.ToString("HH:mm", CultureInfo.InvariantCulture) ?? "(empty)"; + + private sealed record SampleSettings + { + [Required(ErrorMessage = "Enter a site name.")] + [StringLength(60, ErrorMessage = "Use no more than 60 characters for the site name.")] + public string? SiteName { get; set; } + + [StringLength(160, ErrorMessage = "Use no more than 160 characters for the description.")] + public string? Description { get; set; } + + public string? Locale { get; set; } + public bool English { get; set; } + public bool French { get; set; } + public bool German { get; set; } + public string? TimeZone { get; set; } + public string? DateFormat { get; set; } + + [Required(ErrorMessage = "Enter the number of items per page.")] + [Range(5, 100, ErrorMessage = "Enter a number from 5 to 100.")] + public int? ItemsPerPage { get; set; } + + public TimeOnly? PublishTime { get; set; } + public bool ScheduledPublishing { get; set; } + public bool AiAssist { get; set; } + public bool DraftComments { get; set; } + public string? Signup { get; set; } + public bool MailSignup { get; set; } + public bool MailFailure { get; set; } + public bool MailApiKey { get; set; } + public bool Maintenance { get; set; } + } +} diff --git a/gallery/Gallery.Client/wwwroot/gallery.css b/gallery/Gallery.Client/wwwroot/gallery.css index e3b5292..ddf5b9a 100644 --- a/gallery/Gallery.Client/wwwroot/gallery.css +++ b/gallery/Gallery.Client/wwwroot/gallery.css @@ -131,6 +131,87 @@ body.gallery { /* Page */ +/* Settings reference: the gallery keeps its own shell until the shared shell is available. */ +.gallery-settings { + max-inline-size: var(--fl-size-xl); + margin-inline: auto; +} + +.gallery-settings-section-links { + display: none; +} + +@media (max-width: 60rem) { + .gallery-settings-section-links { + display: flex; + } +} + +.gallery-settings-notice { + margin: 0; + padding: var(--fl-inset-m); + border: var(--fl-border-width) solid var(--fl-color-border); + border-inline-start-width: var(--fl-border-width-strong); + border-inline-start-color: var(--fl-color-accent); + border-radius: var(--fl-radius-m); + background-color: var(--fl-color-surface); +} + +.gallery-settings-notice[role="alert"] { + border-inline-start-color: var(--fl-color-danger-solid); +} + +.gallery-settings-notice p { + margin: 0; +} + +.gallery-settings-short { + max-inline-size: var(--fl-size-2xs); +} + +/* Keep help near the label for tall rows, the reference workaround tracked in #27. */ +.gallery-settings .fl-field--horizontal:has(> .gallery-settings-tall) { + grid-template-rows: auto 1fr; +} + +@container (min-inline-size: 30rem) { + .gallery-settings .fl-field--horizontal > .gallery-settings-tall { + grid-row: 1 / span 2; + align-self: start; + } + + .gallery-settings .fl-field--horizontal:has(> .gallery-settings-tall) > .fl-field__help { + grid-row: 2; + } +} + +.gallery-settings-file { + inline-size: 100%; + min-inline-size: 0; + min-block-size: var(--fl-target-min); + font: inherit; + + &::file-selector-button { + min-block-size: var(--fl-target-min); + margin-inline-end: var(--fl-space-2); + padding-inline: var(--fl-space-2); + border: var(--fl-border-width) solid var(--fl-color-border-control); + border-radius: var(--fl-control-radius); + background: var(--fl-color-surface); + color: var(--fl-color-text); + font: inherit; + } +} + +.gallery-settings-file:focus-visible { + outline: var(--fl-focus-ring); + outline-offset: var(--fl-focus-ring-offset); +} + +.gallery-settings-preview p { + margin-block-end: 0; +} + .gallery-layout { display: grid; grid-template-columns: 13rem minmax(0, 1fr); diff --git a/gallery/Gallery.Client/wwwroot/settings-focus.js b/gallery/Gallery.Client/wwwroot/settings-focus.js new file mode 100644 index 0000000..0c8bbaf --- /dev/null +++ b/gallery/Gallery.Client/wwwroot/settings-focus.js @@ -0,0 +1,4 @@ +export function focusCorrection(id) { + const control = document.getElementById(id); + if (control?.closest('#settings-form')) control.focus(); +} diff --git a/tests/FluentCMS.Components.Browser/Forms/SiteSettingsPrerenderTests.cs b/tests/FluentCMS.Components.Browser/Forms/SiteSettingsPrerenderTests.cs new file mode 100644 index 0000000..8731b3b --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/SiteSettingsPrerenderTests.cs @@ -0,0 +1,94 @@ +using FluentCMS.Components.Browser.Harness; +using Microsoft.Playwright; +using static Microsoft.Playwright.Assertions; + +namespace FluentCMS.Components.Browser.Forms; + +public sealed class SiteSettingsPrerenderTests(GalleryFixture gallery) +{ + [Theory] + [ModeData(RenderMode.Server, RenderMode.Wasm)] + public async Task FirstInteractiveScreenKeepsTheSettingsControlsAndNames(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()}/settings?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("#settings-preview-trigger")).ToBeAttachedAsync(); + await FieldIdentity.AssertAsync(page); + before = await main.EvaluateAsync(""" + main => { + const parts = root => [...root.querySelectorAll('.gallery-settings .fl-page-header, .gallery-settings .fl-card')]; + const capture = root => parts(root).map(el => { + const copy = el.cloneNode(true); + const walker = document.createTreeWalker(copy, NodeFilter.SHOW_COMMENT); + const comments = []; + while (walker.nextNode()) if (walker.currentNode.data === '!') comments.push(walker.currentNode); + comments.forEach(node => node.remove()); + const originals = [...el.querySelectorAll('input, textarea, select')]; + [...copy.querySelectorAll('input, textarea, select')].forEach((input, i) => { + input.removeAttribute('value'); + input.setAttribute('data-live-value', originals[i].value); + if (input.localName === 'textarea') input.textContent = ''; + if (input.type === 'checkbox' || input.type === 'radio') { + input.removeAttribute('checked'); + input.setAttribute('data-live-checked', originals[i].checked); + } + // InputNumber captures the framework ElementReference only in interactive mode. + 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 before = parts(main).flatMap(el => [el, ...el.querySelectorAll('*')]); + window.firstSettings = new Promise(resolve => { + const observer = new MutationObserver(() => { + const interactive = document.querySelector('main[data-interactive="true"]'); + if (!interactive) return; + observer.disconnect(); + resolve({replaced: before.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(6, before.Length); + await Expect(main).ToHaveAttributeAsync("data-interactive", "true", new() { Timeout = 30000 }); + Assert.True(await page.EvaluateAsync("async () => (await window.firstSettings).replaced")); + Assert.Equal(before, await page.EvaluateAsync("async () => (await window.firstSettings).markup")); + await Expect(page.Locator("#settings-unsaved")).ToHaveCountAsync(0); + await Expect(page.Locator("#set-date-style input[name='Settings.DateFormat']")).ToHaveCountAsync(4); + await Expect(page.Locator("#set-date-style input[value=written]")).ToBeCheckedAsync(); + await Expect(page.Locator("#set-signup input[name='Settings.Signup']")).ToHaveCountAsync(3); + await Expect(page.Locator("#set-signup input[value=invited]")).ToBeCheckedAsync(); + await FieldIdentity.AssertAsync(page); + } +} diff --git a/tests/FluentCMS.Components.Browser/Forms/SiteSettingsTests.cs b/tests/FluentCMS.Components.Browser/Forms/SiteSettingsTests.cs new file mode 100644 index 0000000..ee93b0d --- /dev/null +++ b/tests/FluentCMS.Components.Browser/Forms/SiteSettingsTests.cs @@ -0,0 +1,428 @@ +using System.Collections.Specialized; +using System.Web; +using FluentCMS.Components.Browser.Harness; +using Microsoft.Playwright; +using static Microsoft.Playwright.Assertions; + +namespace FluentCMS.Components.Browser.Forms; + +public sealed class SiteSettingsTests(GalleryFixture gallery) +{ + private const string Path = "settings"; + private const string Name = "Northwind Field Notes"; + private const string Description = "Independent release notes & guides."; + private const string DomainSignup = "People with an address at northwind.example"; + private static readonly string[] SectionTitles = ["Identity", "Language and region", "Content", "Access", "Danger zone"]; + private static readonly (string Name, string Value)[] PostedSettings = + [ + ("Settings.SiteName", Name), ("Settings.Description", Description), ("Settings.Locale", "fr"), + ("Settings.English", "true"), ("Settings.French", "true"), ("Settings.TimeZone", "Europe/Lisbon"), + ("Settings.DateFormat", "iso"), ("Settings.PublishTime", "10:15"), ("Settings.AiAssist", "true"), + ("Settings.DraftComments", "true"), ("Settings.Signup", "domain"), ("Settings.MailSignup", "true"), + ("Settings.MailApiKey", "true"), ("Settings.Maintenance", "true"), + ]; + private static readonly string[] OmittedSettings = ["Settings.German", "Settings.ScheduledPublishing", "Settings.MailFailure", "locked_versions"]; + + [Theory] + [ModeData(RenderMode.Static)] + public async Task NativePostReturnsRangeErrorAndReceivesTheCorrectionWithoutJavaScript(RenderMode mode) + { + await using IBrowserContext context = await gallery.Browser.NewContextAsync(new() { JavaScriptEnabled = false }); + IPage page = await OpenStaticAsync(context, mode); + await EditSettingsAsync(page); + ILocator logo = page.Locator("#set-logo"); + await Expect(logo).ToHaveAccessibleNameAsync("Logo"); + Assert.Null(await logo.GetAttributeAsync("name")); + await logo.SetInputFilesAsync(new FilePayload { Name = "preview.png", MimeType = "image/png", Buffer = [1, 2, 3] }); + Assert.Equal(1, await logo.EvaluateAsync("input => input.files.length")); + Assert.True(await page.Locator("#set-page-size").EvaluateAsync("el => el.validity.rangeOverflow")); + + NameValueCollection first = await PostAsync(page, "#settings-save"); + AssertPayload(first, "500"); + Assert.Equal(0, await logo.EvaluateAsync("input => input.files.length")); + await AssertRangeErrorAsync(page); + await AssertEditedSettingsAsync(page, "500"); + await FollowErrorLinkAsync(page); + + await page.Locator("#set-page-size").FillAsync("45"); + NameValueCollection corrected = await PostAsync(page, "#settings-save"); + AssertPayload(corrected, "45"); + await AssertSavedAsync(page); + await AssertEditedSettingsAsync(page, "45"); + await FieldIdentity.AssertAsync(page); + } + + [Theory] + [ModeData(RenderMode.Static)] + public async Task NativeDiscardAndHarmlessDeletePreviewWorkWithoutJavaScript(RenderMode mode) + { + await using IBrowserContext context = await gallery.Browser.NewContextAsync(new() { JavaScriptEnabled = false }); + IPage page = await OpenStaticAsync(context, mode); + await page.Locator("#set-name").FillAsync("Unsaved name"); + await page.Locator("#set-locale").SelectOptionAsync("de"); + var address = new Uri(page.Url); + var keys = page.Keys(); + await keys.StartAtTopAsync(); + await keys.TabToAsync("#settings-discard"); + await keys.AssertFocusNameAsync("Discard changes"); + await keys.PressAsync("Enter"); + await Expect(page.Locator("#set-name")).ToHaveValueAsync("Northwind Journal"); + await Expect(page.Locator("#set-locale")).ToHaveValueAsync("en"); + await Expect(page).ToHaveURLAsync(address.AbsoluteUri); + await Expect(page.Locator("#settings-saved")).ToHaveCountAsync(0); + + await keys.TabToAsync("#settings-preview-trigger", maxPresses: 120); + await keys.AssertFocusNameAsync("Preview deleting the site"); + await keys.PressAsync("Space"); + await Expect(page.Locator("#settings-delete-preview[open]")).ToBeVisibleAsync(); + await Expect(page.Locator("#settings-preview-result")).ToHaveTextAsync("Preview only. Nothing has been deleted."); + await Expect(page).ToHaveURLAsync(address.AbsoluteUri); + } + + [Theory] + [ModeData(RenderMode.Static)] + public async Task CorrectionAndSectionLinksPreserveThePostedDraftAndExactQuery(RenderMode mode) + { + const string query = "?theme=light&density=comfortable&dir=ltr"; + await using IBrowserContext context = await gallery.Browser.NewContextAsync(new() + { + JavaScriptEnabled = false, + ViewportSize = new() { Width = 1440, Height = 900 }, + }); + IPage page = await OpenStaticAsync(context, mode, query); + await page.Locator("#set-name").FillAsync(Name); + await page.Locator("#set-page-size").FillAsync("500"); + var invalid = await PostAsync(page, "#settings-save"); + Assert.Equal(Name, Assert.Single(invalid.GetValues("Settings.SiteName") ?? [])); + Assert.Equal("500", Assert.Single(invalid.GetValues("Settings.ItemsPerPage") ?? [])); + await AssertRangeErrorAsync(page); + Assert.EndsWith(query, page.Url, StringComparison.Ordinal); + string documentUrl = page.Url; + double timeOrigin = await page.EvaluateAsync("performance.timeOrigin"); + int documentRequests = 0; + EventHandler record = (_, request) => + { + if (request.IsNavigationRequest && request.Frame == page.MainFrame) + { + Interlocked.Increment(ref documentRequests); + } + }; + page.Request += record; + + async Task AssertSameDraftAsync(string target) + { + await Expect(page).ToHaveURLAsync($"{documentUrl}#{target}"); + Assert.Equal(timeOrigin, await page.EvaluateAsync("performance.timeOrigin")); + Assert.Equal(0, Volatile.Read(ref documentRequests)); + await Expect(page.Locator("#set-name")).ToHaveValueAsync(Name); + await Expect(page.Locator("#set-page-size")).ToHaveValueAsync("500"); + await Expect(page.Locator("#set-page-size__error")).ToBeVisibleAsync(); + } + + await FollowErrorLinkAsync(page); + await AssertSameDraftAsync("set-page-size"); + await page.GetByRole(AriaRole.Navigation, new() { Name = "On this page" }).GetByRole(AriaRole.Link, new() { Name = "Content", Exact = true }).ClickAsync(); + await AssertSameDraftAsync("settings-content"); + await page.SetViewportSizeAsync(320, 800); + await page.GetByRole(AriaRole.Navigation, new() { Name = "Settings sections" }).GetByRole(AriaRole.Link, new() { Name = "Access", Exact = true }).ClickAsync(); + await AssertSameDraftAsync("settings-access"); + + await page.Locator("#set-name").FillAsync("Temporary browser edit"); + KeyboardDriver keys = page.Keys(); + await keys.StartAtTopAsync(); + await keys.TabToAsync("#settings-discard"); + await keys.PressAsync("Enter"); + await AssertSameDraftAsync("settings-access"); + await Expect(page.Locator("#settings-unsaved")).ToHaveTextAsync("Unsaved changes"); + + page.Request -= record; + await page.Locator("#set-page-size").FillAsync("45"); + var corrected = await PostAsync(page, "#settings-save"); + Assert.Equal(Name, Assert.Single(corrected.GetValues("Settings.SiteName") ?? [])); + Assert.Equal("45", Assert.Single(corrected.GetValues("Settings.ItemsPerPage") ?? [])); + await Expect(page.Locator("#settings-saved-name")).ToHaveTextAsync(Name); + await Expect(page.Locator("#settings-saved-size")).ToHaveTextAsync("45"); + await Expect(page.Locator("#settings-unsaved")).ToHaveCountAsync(0); + } + + [Theory] + [ModeData(RenderMode.Server, RenderMode.Wasm)] + public async Task InteractiveSaveAndDiscardUseTheBoundModel(RenderMode mode) + { + await using GalleryPage sample = await gallery.OpenAsync(mode, Path); + IPage page = sample.Page; + await EditSettingsAsync(page); + await Expect(page.Locator("#settings-unsaved.fl-badge--warning.fl-badge--dot")).ToHaveTextAsync("Unsaved changes"); + await page.Locator("#settings-save").ClickAsync(); + await AssertRangeErrorAsync(page); + await AssertEditedSettingsAsync(page, "500"); + await FollowErrorLinkAsync(page); + + await page.Locator("#set-page-size").FillAsync("45"); + await page.Locator("#settings-save").ClickAsync(); + await AssertSavedAsync(page); + + await page.Locator("#set-name").FillAsync("Discard this temporary name"); + await page.Locator("#set-name").PressAsync("Tab"); + await Expect(page.Locator("#settings-unsaved")).ToHaveTextAsync("Unsaved changes"); + await page.Locator("#set-locale").SelectOptionAsync("de"); + ILocator date = RadioGroup(page, "Date format").Locator("input[value=day-first]"); + ILocator signup = RadioGroup(page, "Who can sign up").Locator("input[value=anyone]"); + await date.ClickAsync(); + await Expect(date).ToBeCheckedAsync(); + await signup.ClickAsync(); + await Expect(signup).ToBeCheckedAsync(); + await page.Locator("#set-maintenance").UncheckAsync(); + await page.Locator("#set-page-size").FillAsync("500"); + await page.Locator("#settings-save").ClickAsync(); + await AssertRangeErrorAsync(page); + await Expect(page.Locator("#set-name")).ToHaveValueAsync("Discard this temporary name"); + await Expect(page.Locator("#set-locale")).ToHaveValueAsync("de"); + await Expect(date).ToBeCheckedAsync(); + await Expect(signup).ToBeCheckedAsync(); + await Expect(page.Locator("#set-maintenance")).Not.ToBeCheckedAsync(); + var keys = page.Keys(); + await keys.StartAtTopAsync(); + await keys.TabToAsync("#settings-discard"); + await keys.AssertFocusNameAsync("Discard changes"); + await keys.PressAsync("Enter"); + await Expect(page.Locator("#settings-discarded")).ToHaveTextAsync("Changes discarded."); + await Expect(page.Locator("#settings-error")).ToHaveCountAsync(0); + await Expect(page.Locator("#settings-unsaved")).ToHaveCountAsync(0); + await AssertEditedSettingsAsync(page, "45"); + // A DOM-only reset would leave the abandoned values in the EditContext model. + await page.Locator("#settings-save").ClickAsync(); + await AssertSavedAsync(page); + await FieldIdentity.AssertAsync(page); + } + + [Theory] + [ModeData(RenderMode.Server, RenderMode.Wasm)] + public async Task InteractiveLinksFollowAnAppearanceChangeWithoutReplacingTheDraft(RenderMode mode) + { + const string editedName = "Appearance navigation draft"; + string[] targets = ["settings-identity", "settings-region", "settings-content", "settings-access", "settings-danger"]; + await using GalleryPage sample = await gallery.OpenAsync(mode, Path); + IPage page = sample.Page; + double timeOrigin = await page.EvaluateAsync("performance.timeOrigin"); + await page.Locator("#set-name").FillAsync(editedName); + await page.Locator("#set-page-size").FillAsync("500"); + await page.Locator("#settings-save").ClickAsync(); + await AssertRangeErrorAsync(page); + + string darkUrl = new Uri(gallery.BaseAddress, $"{mode.Segment()}/{Path}?theme=dark").AbsoluteUri; + await page.Locator(".gallery-switches").GetByRole(AriaRole.Link, new() { Name = "Dark", Exact = true }).ClickAsync(); + await Expect(page).ToHaveURLAsync(darkUrl); + await Expect(page.Locator("html")).ToHaveAttributeAsync("data-fl-theme", "dark"); + + foreach (string selector in new[] { ".gallery-toc a", ".gallery-settings-section-links a" }) + { + ILocator links = page.Locator(selector); + await Expect(links).ToHaveCountAsync(targets.Length); + for (int i = 0; i < targets.Length; i++) + { + await Expect(links.Nth(i)).ToHaveAttributeAsync("href", $"{darkUrl}#{targets[i]}"); + } + } + await Expect(page.Locator("#settings-go-to-error")).ToHaveAttributeAsync("href", $"{darkUrl}#set-page-size"); + await FollowErrorLinkAsync(page); + await Expect(page).ToHaveURLAsync($"{darkUrl}#set-page-size"); + await Expect(page.Locator("html")).ToHaveAttributeAsync("data-fl-theme", "dark"); + Assert.Equal(timeOrigin, await page.EvaluateAsync("performance.timeOrigin")); + await Expect(page.Locator("#set-name")).ToHaveValueAsync(editedName); + await Expect(page.Locator("#set-page-size")).ToHaveValueAsync("500"); + await AssertRangeErrorAsync(page); + } + + [Theory] + [ModeData] + public Task GalleryPassesAxe(RenderMode mode) => Accessibility.AssertNoViolationsAsync(gallery, mode, Path); + + [Theory] + [ModeData] + public async Task At320BothDensitiesKeepActualNativeTargetsAndSections(RenderMode mode) + { + foreach (string density in new[] { "comfortable", "compact" }) + { + await using GalleryPage sample = await gallery.OpenAsync(mode, Path, new() + { + Width = 320, Height = 800, Theme = "dark", Direction = "rtl", Density = density, + }); + IPage page = sample.Page; + await Expect(page.Locator(".gallery-settings .fl-card__title")).ToHaveTextAsync(SectionTitles); + await Expect(page.GetByRole(AriaRole.Navigation, new() { Name = "Settings sections" }).GetByRole(AriaRole.Link)).ToHaveCountAsync(5); + foreach (ForcedColors colors in new[] { ForcedColors.None, ForcedColors.Active }) + { + await page.EmulateMediaAsync(new() { ForcedColors = colors }); + var undersized = await page.Locator(".gallery-settings :is(input:not([type=hidden]), textarea, select):enabled").EvaluateAllAsync(""" + els => els.flatMap(el => { + const r = el.getBoundingClientRect(); + return r.width >= 24 && r.height >= 24 ? [] : [`${el.id}: ${r.width} x ${r.height}`]; + }) + """); + Assert.Empty(undersized); + await Wcag.AssertTargetSizesAsync(page); + await Wcag.AssertNoHorizontalScrollAsync(page); + } + await FieldIdentity.AssertAsync(page); + } + } + + [Theory] + [ModeData] + public async Task KeyboardPreviewDoesNotMoveThroughIntermediateFrames(RenderMode mode) + { + await using GalleryPage sample = await gallery.OpenAsync(mode, Path, new() { ReducedMotion = true }); + IPage page = sample.Page; + var keys = page.Keys(); + await keys.StartAtTopAsync(); + await keys.TabToAsync("#settings-preview-trigger", maxPresses: 120); + await keys.AssertFocusNameAsync("Preview deleting the site"); + await Wcag.AssertNoMotionAsync(page, async () => + { + await keys.PressAsync("Space"); + await Expect(page.Locator("#settings-preview-result")).ToBeVisibleAsync(); + await keys.AssertFocusAsync("#settings-preview-trigger"); + }); + } + + 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 EditSettingsAsync(IPage page) + { + await page.Locator("#set-name").FillAsync(Name); + await page.Locator("#set-description").FillAsync(Description); + await page.Locator("#set-locale").SelectOptionAsync("fr"); + await page.Locator("#set-locale-de").UncheckAsync(); + await page.Locator("#set-zone").SelectOptionAsync("Europe/Lisbon"); + await RadioGroup(page, "Date format").Locator("input[value=iso]").CheckAsync(); + await page.Locator("#set-page-size").FillAsync("500"); + await page.Locator("#set-publish-time").FillAsync("10:15"); + ILocator locked = page.GetByRole(AriaRole.Switch, new() { Name = "Version history", Exact = true }); + await Expect(locked).ToBeCheckedAsync(); + await Expect(locked).ToBeDisabledAsync(); + await page.GetByRole(AriaRole.Switch, new() { Name = "Scheduled publishing", Exact = true }).UncheckAsync(); + await page.GetByRole(AriaRole.Switch, new() { Name = "Comments on drafts", Exact = true }).CheckAsync(); + await RadioGroup(page, "Who can sign up").GetByRole(AriaRole.Radio, new() { Name = DomainSignup, Exact = true }).CheckAsync(); + await page.Locator("#set-mail-failure").UncheckAsync(); + await page.Locator("#set-mail-key").CheckAsync(); + await page.Locator("#set-maintenance").CheckAsync(); + } + + private static async Task AssertEditedSettingsAsync(IPage page, string size) + { + await Expect(page.Locator("#set-name")).ToHaveValueAsync(Name); + await Expect(page.Locator("#set-description")).ToHaveValueAsync(Description); + await Expect(page.Locator("#set-locale")).ToHaveValueAsync("fr"); + await Expect(page.Locator("#set-locale-de")).Not.ToBeCheckedAsync(); + await Expect(page.Locator("#set-zone")).ToHaveValueAsync("Europe/Lisbon"); + await Expect(page.Locator("#set-page-size")).ToHaveValueAsync(size); + await Expect(page.Locator("#set-publish-time")).ToHaveValueAsync("10:15"); + await Expect(page.Locator("#set-maintenance")).ToBeCheckedAsync(); + await Expect(page.Locator("#set-schedule")).Not.ToBeCheckedAsync(); + await Expect(page.Locator("#set-comments")).ToBeCheckedAsync(); + await Expect(page.Locator("#set-mail-failure")).Not.ToBeCheckedAsync(); + await Expect(page.Locator("#set-mail-key")).ToBeCheckedAsync(); + await AssertChoiceGroupsAsync(page); + } + + private static ILocator RadioGroup(IPage page, string name) => page.GetByRole(AriaRole.Radiogroup, new() { Name = name, Exact = true }); + + private static async Task AssertChoiceGroupsAsync(IPage page) + { + var date = RadioGroup(page, "Date format"); + var signup = RadioGroup(page, "Who can sign up"); + await Expect(date).ToHaveCountAsync(1); + await Expect(signup).ToHaveCountAsync(1); + await Expect(date).ToHaveAttributeAsync("aria-describedby", "set-date-style__help"); + await Expect(signup).ToHaveAttributeAsync("aria-describedby", "set-signup__help"); + await Expect(date.Locator("input:checked")).ToHaveCountAsync(1); + await Expect(date.Locator("input[value=iso]")).ToBeCheckedAsync(); + await Expect(signup.Locator("input:checked")).ToHaveCountAsync(1); + ILocator domain = signup.GetByRole(AriaRole.Radio, new() { Name = DomainSignup, Exact = true }); + await Expect(domain).ToBeCheckedAsync(); + await Expect(domain).ToHaveAccessibleDescriptionAsync("They join as authors once the address is confirmed."); + await Expect(page.Locator(".gallery-settings [role=radiogroup]")).ToHaveCountAsync(2); + foreach (string name in new[] { "Locales", "For editors", "Email the owners when" }) + { + await Expect(page.GetByRole(AriaRole.Group, new() { Name = name, Exact = true })).ToHaveCountAsync(1); + } + } + + 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/settings", 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] #settings-form")).ToBeVisibleAsync(); + var values = HttpUtility.ParseQueryString(response.Request.PostData ?? ""); + Assert.Equal("settings-sample", values["_handler"]); + Assert.False(string.IsNullOrWhiteSpace(values["__RequestVerificationToken"])); + return values; + } + + private static void AssertPayload(NameValueCollection values, string size) + { + foreach (var (name, value) in PostedSettings) + { + Assert.Equal(value, Assert.Single(values.GetValues(name) ?? [])); + } + Assert.Equal(size, Assert.Single(values.GetValues("Settings.ItemsPerPage") ?? [])); + Assert.All(OmittedSettings, name => Assert.Null(values[name])); + Assert.DoesNotContain(values.AllKeys, name => name?.Contains("logo", StringComparison.OrdinalIgnoreCase) == true); + } + + private static async Task AssertRangeErrorAsync(IPage page) + { + await Expect(page.GetByRole(AriaRole.Alert, new() { Name = "The settings were not saved" })).ToBeVisibleAsync(); + var input = page.Locator("#set-page-size"); + await Expect(input).ToHaveAccessibleNameAsync("Items per page"); + await Expect(input).ToHaveAttributeAsync("aria-invalid", "true"); + await Expect(input).ToHaveAttributeAsync("aria-describedby", "set-page-size__error set-page-size__help set-page-size__suffix"); + await Expect(page.Locator("#set-page-size__error")).ToHaveTextAsync("Enter a number from 5 to 100."); + List missing = []; + if (await page.Locator("#settings-unsaved.fl-badge--warning").CountAsync() != 1) + { + missing.Add("Expected the warning badge for retained, unsaved settings."); + } + if (await page.GetByRole(AriaRole.Radiogroup, new() { Name = "Date format", Exact = true }).CountAsync() != 1) + { + missing.Add("Expected exactly one named date format radiogroup."); + } + if (await page.GetByRole(AriaRole.Switch, new() { Name = "Maintenance mode", Exact = true }).CountAsync() != 1) + { + missing.Add("Expected a named Maintenance mode switch."); + } + Assert.Empty(missing); + await Expect(page.Locator("#settings-unsaved")).ToHaveTextAsync("Unsaved changes"); + await FieldIdentity.AssertAsync(page); + } + + private static async Task FollowErrorLinkAsync(IPage page) + { + var keys = page.Keys(); + await keys.StartAtTopAsync(); + await keys.TabToAsync("#settings-go-to-error"); + await keys.AssertFocusNameAsync("Go to the field"); + await keys.PressAsync("Enter"); + await Expect(page.Locator("#set-page-size")).ToBeFocusedAsync(); + } + + private static async Task AssertSavedAsync(IPage page) + { + await Expect(page.GetByRole(AriaRole.Status, new() { Name = "Save status" })).ToContainTextAsync("Settings saved"); + await Expect(page.Locator("#settings-saved-name")).ToHaveTextAsync(Name); + await Expect(page.Locator("#settings-saved-size")).ToHaveTextAsync("45"); + await Expect(page.Locator("#settings-saved-locale")).ToHaveTextAsync("fr"); + await Expect(page.Locator("#settings-saved-time")).ToHaveTextAsync("10:15"); + await Expect(page.Locator("#settings-error")).ToHaveCountAsync(0); + await Expect(page.Locator("#settings-unsaved")).ToHaveCountAsync(0); + } +}