From 963255aba6e72a102a9694e63b218f67a76860b7 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 30 Nov 2026 22:51:21 -0500 Subject: [PATCH 1/7] Open the page asked for, in the density asked for --- .../Harness/GalleryFixture.cs | 39 ++++++++++++++++++- .../Samples/HarnessGuardTests.cs | 24 ++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/tests/FluentCMS.Components.Browser/Harness/GalleryFixture.cs b/tests/FluentCMS.Components.Browser/Harness/GalleryFixture.cs index 29397f66..09345142 100644 --- a/tests/FluentCMS.Components.Browser/Harness/GalleryFixture.cs +++ b/tests/FluentCMS.Components.Browser/Harness/GalleryFixture.cs @@ -72,7 +72,9 @@ public async Task OpenAsync(RenderMode mode, string path, GalleryOp { context = await NewContextAsync(options, own ?? Browser); IPage page = await context.NewPageAsync(); - var address = new Uri(BaseAddress, $"{mode.Segment()}/{path}{options.Query}"); + // A path may bring a query of its own, which the options extend. + string query = path.Contains('?') && options.Query.Length > 0 ? "&" + options.Query[1..] : options.Query; + var address = new Uri(BaseAddress, $"{mode.Segment()}/{path}{query}"); IResponse? response = await page.GotoAsync(address.AbsoluteUri); if (response is null || !response.Ok) { @@ -80,6 +82,12 @@ public async Task OpenAsync(RenderMode mode, string path, GalleryOp throw new InvalidOperationException($"Opening {address} returned {status}."); } + // A redirect that answers with another page is not the page asked for. The fragment is not compared. + if (!new Uri(response.Url).Equals(address)) + { + throw new InvalidOperationException($"Opening {address} ended at {response.Url}."); + } + await WaitUntilReadyAsync(page, mode); if (options.Theme is "light" or "dark") { @@ -91,6 +99,15 @@ public async Task OpenAsync(RenderMode mode, string path, GalleryOp await CheckAppearanceAsync(page, "direction", options.Direction, "direction"); } + if (options.Density is not null) + { + string? density = await page.Locator("html").GetAttributeAsync("data-fl-density"); + if (density != options.Density) + { + throw new InvalidOperationException($"{page.Url} density: expected '{options.Density}', got '{density}'."); + } + } + return new GalleryPage(context, page, mode, path, own); } catch @@ -163,12 +180,19 @@ private async Task StartGalleryAsync() start.ArgumentList.Add(targetPath); start.ArgumentList.Add("--urls"); start.ArgumentList.Add("http://127.0.0.1:0"); + // The host reads its settings from the environment too. What the parent has set for its own hosts (an + // environment, addresses, logging, startup hooks) would change this one, so none of it is passed on. + foreach (string name in start.Environment.Keys.Where(InheritedHostSetting).ToList()) + { + start.Environment.Remove(name); + } + // Development, as under dotnet run: the host then finds the static files of the // build output through the manifest the build wrote. start.Environment["ASPNETCORE_ENVIRONMENT"] = "Development"; start.Environment["DOTNET_ENVIRONMENT"] = "Development"; // Information logging costs every request a line on the pipe; the suite reads none of it. - start.Environment.TryAdd("Logging__LogLevel__Default", "Warning"); + start.Environment["Logging__LogLevel__Default"] = "Warning"; // The lifetime logger announces the port Kestrel picked, even if the parent logs only warnings. start.Environment["Logging__LogLevel__Microsoft.Hosting.Lifetime"] = "Information"; start.Environment["DOTNET_NOLOGO"] = "1"; @@ -195,6 +219,17 @@ private async Task StartGalleryAsync() } } + private static bool InheritedHostSetting(string name) => + name.StartsWith("ASPNETCORE_", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("Kestrel__", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("Logging__", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("DOTNET_HOSTINGSTARTUP", StringComparison.OrdinalIgnoreCase) + || name.Equals("DOTNET_ENVIRONMENT", StringComparison.OrdinalIgnoreCase) + || name.Equals("DOTNET_URLS", StringComparison.OrdinalIgnoreCase) + || name.Equals("DOTNET_CONTENTROOT", StringComparison.OrdinalIgnoreCase) + || name.Equals("DOTNET_STARTUP_HOOKS", StringComparison.OrdinalIgnoreCase) + || name.Equals("URLS", StringComparison.OrdinalIgnoreCase); + private void OnLine(string? line, TaskCompletionSource listening) { if (line is null) diff --git a/tests/FluentCMS.Components.Browser/Samples/HarnessGuardTests.cs b/tests/FluentCMS.Components.Browser/Samples/HarnessGuardTests.cs index 407091c7..1f2db944 100644 --- a/tests/FluentCMS.Components.Browser/Samples/HarnessGuardTests.cs +++ b/tests/FluentCMS.Components.Browser/Samples/HarnessGuardTests.cs @@ -44,6 +44,30 @@ public async Task OpenRejectsALeftToRightDocumentWhenRightToLeftWasRequested(Ren Assert.Contains("direction: expected 'rtl', got 'ltr'", error.Message); } + // The options extend a query that the path brings, so the editor opens the article asked for, in the density asked for. + [Theory] + [ModeData(RenderMode.Static)] + public async Task OpenExtendsTheQueryOfThePath(RenderMode mode) + { + await using GalleryPage page = await gallery.OpenAsync(mode, "content-list/entry?id=whats-new-spring-release", new GalleryOptions { Density = "compact" }); + + Assert.EndsWith("?id=whats-new-spring-release&density=compact", page.Page.Url); + Assert.Equal("What's new in the spring release", await page.Page.Locator("main h1").InnerTextAsync()); + } + + [Theory] + [ModeData(RenderMode.Static)] + public async Task OpenRejectsAPageInAnotherDensity(RenderMode mode) + { + // The fragment keeps the density of the options out of the request, so the page comes in the comfortable one. + InvalidOperationException error = await Assert.ThrowsAsync(async () => + { + await using GalleryPage page = await gallery.OpenAsync(mode, "tokens#fixed-appearance", new GalleryOptions { Density = "compact" }); + }); + + Assert.Contains("density: expected 'compact', got 'comfortable'", error.Message); + } + [Theory] [InlineData(",")] [InlineData(" , , ")] From e11a909279876af8d75523b367e25f5ec7636c5d Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 30 Nov 2026 22:51:21 -0500 Subject: [PATCH 2/7] Run the startup regression nightly with parents that set host settings --- .github/workflows/nightly.yml | 21 +++++++++++++++++++ .../test-startup.mjs | 12 ++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 207741df..6dd6c196 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -42,3 +42,24 @@ jobs: browser: ${{ matrix.engine.browser }} modes: ${{ matrix.part.mode }} filter: ${{ matrix.part.filter }} + + # The fixture must start the gallery that was built, in Development, whatever the parent's environment holds + # (CONTRIBUTING.md, Browser tests). Each case runs one browser test under a parent that would break it. + startup: + name: Gallery startup + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/setup-dotnet + - name: Build browser tests and gallery + shell: bash + run: dotnet build tests/FluentCMS.Components.Browser + - name: Install Chromium + shell: bash + run: pwsh tests/FluentCMS.Components.Browser/bin/Debug/net10.0/playwright.ps1 install chromium + - name: Start the gallery under each parent environment + shell: bash + run: node tests/FluentCMS.Components.Browser/test-startup.mjs diff --git a/tests/FluentCMS.Components.Browser/test-startup.mjs b/tests/FluentCMS.Components.Browser/test-startup.mjs index c97e0086..cb4d5ffb 100644 --- a/tests/FluentCMS.Components.Browser/test-startup.mjs +++ b/tests/FluentCMS.Components.Browser/test-startup.mjs @@ -1,11 +1,16 @@ -// node tests/FluentCMS.Components.Browser/test-startup.mjs [artifacts|environment|logging] +// node tests/FluentCMS.Components.Browser/test-startup.mjs [artifacts|environment|logging|console|kestrel] import { spawnSync } from 'node:child_process'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { basename, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -const cases = ['artifacts', 'environment', 'logging']; +const cases = ['artifacts', 'environment', 'logging', 'console', 'kestrel']; +// Settings a parent may hold that would change the host the fixture starts, by case. +const inherited = { + console: { Logging__Console__LogLevel__Default: 'Warning', Logging__Console__FormatterName: 'json' }, + kestrel: { Kestrel__Endpoints__Http__Url: 'http://127.0.0.1:1', ASPNETCORE_URLS: 'http://127.0.0.1:1' }, +}; const selected = process.argv.slice(2); const root = fileURLToPath(new URL('../../', import.meta.url)); @@ -18,6 +23,7 @@ for (const name of selected.length ? selected : cases) { FLUENTCMS_MODES: mode.toLowerCase(), DOTNET_ENVIRONMENT: name === 'environment' ? 'Production' : 'Development', Logging__LogLevel__Default: name === 'logging' ? 'Warning' : 'Information', + ...inherited[name], }; const args = ['test', '--project', 'tests/FluentCMS.Components.Browser', '--filter-display-name', `*EveryModeBecomesWhatItsAddressNames(mode: ${mode})`, @@ -26,7 +32,7 @@ for (const name of selected.length ? selected : cases) { try { // A fresh configuration means a previous default-bin build cannot mask the bug. if (artifacts) args.push('--configuration', basename(artifacts), '--artifacts-path', artifacts); - console.log(`[${name}] FLUENTCMS_MODES=${env.FLUENTCMS_MODES} DOTNET_ENVIRONMENT=${env.DOTNET_ENVIRONMENT} Logging__LogLevel__Default=${env.Logging__LogLevel__Default}`); + console.log(`[${name}] FLUENTCMS_MODES=${env.FLUENTCMS_MODES} DOTNET_ENVIRONMENT=${env.DOTNET_ENVIRONMENT} Logging__LogLevel__Default=${env.Logging__LogLevel__Default}`, inherited[name] ?? ''); console.log('dotnet', args.map(arg => arg.includes(' ') ? `"${arg}"` : arg).join(' ')); const result = spawnSync('dotnet', args, { cwd: root, env, stdio: 'inherit' }); if (result.error) throw result.error; From 4dc1447d06dd125e9e8f50a3f93b5447eb68e7e2 Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 30 Nov 2026 22:51:22 -0500 Subject: [PATCH 3/7] Measure targets as a pointer reaches them and see movement no box shows --- .../Harness/Wcag.cs | 99 +++++++++++++++---- .../Samples/HelperFaultTests.cs | 82 +++++++++++++++ 2 files changed, 161 insertions(+), 20 deletions(-) diff --git a/tests/FluentCMS.Components.Browser/Harness/Wcag.cs b/tests/FluentCMS.Components.Browser/Harness/Wcag.cs index 748c35c3..5c686688 100644 --- a/tests/FluentCMS.Components.Browser/Harness/Wcag.cs +++ b/tests/FluentCMS.Components.Browser/Harness/Wcag.cs @@ -76,34 +76,72 @@ private static void Fail(string[] findings, string title) private const string TargetSizes = "() => {" + Describe + """ const SELECTOR = 'a[href], button, input:not([type=hidden]), select, textarea, summary, ' + '[role=button], [role=link], [role=checkbox], [role=radio], [role=switch], [role=tab], ' + - '[role=menuitem], [role=option], [role=slider], [role=treeitem], [tabindex]:not([tabindex="-1"])'; + '[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio], [role=option], [role=slider], [role=combobox], ' + + '[role=treeitem], [contenteditable]:not([contenteditable=false]), [tabindex]:not([tabindex="-1"])'; const MIN = 24; - const hitRects = el => { - const style = getComputedStyle(el); - if (el.closest('[hidden], [inert]') || style.visibility !== 'visible' || style.pointerEvents === 'none') return []; - return [...el.getClientRects()].filter(r => r.width > 0 && r.height > 0); + // An expanded tree item holds the group of its children; its own target is its row. + const parts = el => el.matches('[role=treeitem]') ? [...el.children].filter(child => !child.matches('[role=group]')) : [el]; + const owns = (el, node) => !!node && el.contains(node) && !(el.matches('[role=treeitem]') && node.closest('[role=group]')?.closest('[role=treeitem]') === el); + // What a pointer can reach of a box: an ancestor that clips its overflow cuts it, also when it scrolls. Only the + // ancestors that contain the box clip it: a box in the top layer escapes them all, a fixed one too, and an + // absolute one escapes those that are not positioned. + const clip = (el, r) => { + let { left, top, right, bottom } = r; + for (let node = el; node.parentElement && node.parentElement !== document.documentElement;) { + if (node.matches(':modal, :popover-open')) break; + const position = getComputedStyle(node).position; + if (position === 'fixed') break; + let a = node.parentElement; + if (position === 'absolute') { + while (a && a !== document.documentElement && getComputedStyle(a).position === 'static' && getComputedStyle(a).transform === 'none') a = a.parentElement; + if (!a || a === document.documentElement) break; + } + const style = getComputedStyle(a); + // An element with display: contents has no box, so it clips nothing. + if (style.display !== 'contents' && (style.overflowX !== 'visible' || style.overflowY !== 'visible')) { + const box = a.getBoundingClientRect(); + left = Math.max(left, box.left + a.clientLeft); + top = Math.max(top, box.top + a.clientTop); + right = Math.min(right, box.left + a.clientLeft + a.clientWidth); + bottom = Math.min(bottom, box.top + a.clientTop + a.clientHeight); + } + node = a; + } + return { left, top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) }; }; - // A pseudo-element can widen a target beyond the box of its element. Where the box is too small, the target - // is what a pointer hits: the corners of the smallest allowed square, centred on the element. - const hitSquare = el => { - el.scrollIntoView({ block: 'center', inline: 'center' }); + // Drawn at all: not hidden, not in a closed details element, not without pointer events. + const rendered = el => !el.closest('[inert]') && el.checkVisibility({ visibilityProperty: true }) + && getComputedStyle(el).pointerEvents !== 'none'; + const hitRects = el => rendered(el) ? parts(el).flatMap(part => [...part.getClientRects()].map(r => clip(part, r))).filter(r => r.width > 0 && r.height > 0) : []; + // Where the box is too small, the target is what a pointer hits, as when a pseudo-element widens it: every point + // of a grid over the smallest allowed square, centred on the element, must reach it or its label. + const hitSquare = (el, labels) => { const box = el.getBoundingClientRect(); - const x = box.left + box.width / 2, y = box.top + box.height / 2, half = MIN / 2 - 0.1; - return [[-half, -half], [half, -half], [-half, half], [half, half]].every(([dx, dy]) => el.contains(document.elementFromPoint(x + dx, y + dy))); + const x = box.left + box.width / 2, y = box.top + box.height / 2, half = MIN / 2 - 0.5; + for (let i = 0; i < 5; i++) { + for (let j = 0; j < 5; j++) { + const hit = document.elementFromPoint(x - half + i * half / 2, y - half + j * half / 2); + if (!owns(el, hit) && !labels.some(label => label.contains(hit))) return false; + } + } + return true; }; - const scroll = [scrollX, scrollY]; + const scrolled = [document.scrollingElement, ...document.querySelectorAll('*')] + .filter(el => el && (el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth)) + .map(el => [el, el.scrollLeft, el.scrollTop]); const findings = []; for (const el of document.querySelectorAll(SELECTOR)) { - if (el.matches(':disabled') || el.closest('[inert]')) continue; + if (el.matches(':disabled') || el.closest('[inert]') || !rendered(el) || el.getClientRects().length === 0) continue; + // In view, so that what clips it is what a person would meet after scrolling to it. + el.scrollIntoView({ block: 'center', inline: 'center' }); const rects = hitRects(el); - if (el.matches('input[type=checkbox], input[type=radio]')) { - for (const label of el.labels) rects.push(...hitRects(label)); - } - if (rects.length === 0 || rects.some(r => r.width >= MIN && r.height >= MIN) || hitSquare(el)) continue; - const sizes = rects.map(r => `${r.width.toFixed(1)} by ${r.height.toFixed(1)} px`); + const labels = el.matches('input[type=checkbox], input[type=radio]') ? [...el.labels].filter(rendered) : []; + for (const label of labels) rects.push(...hitRects(label)); + if (rects.some(r => r.width >= MIN && r.height >= MIN) || hitSquare(el, labels)) continue; + const sizes = rects.length ? rects.map(r => `${r.width.toFixed(1)} by ${r.height.toFixed(1)} px`) : ['no visible box']; findings.push(`${describe(el)}: ${sizes.join('; ')}`); } - scrollTo(...scroll); + for (const [el, left, top] of scrolled) el.scrollTo(left, top); return findings; } """; @@ -139,6 +177,24 @@ private static void Fail(string[] findings, string title) findings.push('The page scrolls smoothly.'); } const moved = new Set(); + // An animation or a transition of a property that moves or resizes, on an element or a pseudo-element: what + // the boxes do not show (a pseudo-element, a background that travels, a step between frames that look the same) + // still runs here. One of colour or opacity alone is not motion. + const MOVING = /^(transform|translate|rotate|scale|offset|inset|top|right|bottom|left|margin|width|height|inline-size|block-size|min-|max-|grid-template|background-position|mask-position|object-position)/; + const animated = new Map(); + const properties = animation => animation instanceof CSSTransition ? [animation.transitionProperty] + : (animation.effect?.getKeyframes() ?? []).flatMap(frame => Object.keys(frame)).filter(key => !['offset', 'easing', 'composite', 'computedOffset'].includes(key)) + .map(key => key.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase())); + const watchAnimations = () => { + for (const animation of document.getAnimations()) { + if (animation.playState !== 'running' || !(animation.effect?.getComputedTiming().activeDuration > 0)) continue; + const moving = properties(animation).filter(property => MOVING.test(property)); + if (!moving.length) continue; + const target = animation.effect.target; + const name = target ? describe(target) + (animation.effect.pseudoElement ?? '') : 'an animation'; + animated.set(name, `${name} animates ${[...new Set(moving)].join(', ')} (${animation.animationName ?? 'a transition'})`); + } + }; let last = new Map(); let frame; const sample = () => { @@ -155,6 +211,7 @@ private static void Fail(string[] findings, string title) current.set(el, { geometry, changed }); } last = current; + watchAnimations(); frame = requestAnimationFrame(sample); }; sample(); @@ -162,8 +219,10 @@ private static void Fail(string[] findings, string title) stop: () => cancelAnimationFrame(frame), finish: async () => { await new Promise(resolve => setTimeout(resolve, 400)); + // A transition that waits for its delay is running already, so one that starts after the window is seen too. + watchAnimations(); const outermost = [...moved].filter(el => !moved.has(el.parentElement)); - return findings.concat(outermost.slice(0, 5).map(el => `${describe(el)} changes geometry across frames`)); + return findings.concat(outermost.slice(0, 5).map(el => `${describe(el)} changes geometry across frames`), [...animated.values()].slice(0, 5)); } }; } diff --git a/tests/FluentCMS.Components.Browser/Samples/HelperFaultTests.cs b/tests/FluentCMS.Components.Browser/Samples/HelperFaultTests.cs index 6d1ab442..281d53d0 100644 --- a/tests/FluentCMS.Components.Browser/Samples/HelperFaultTests.cs +++ b/tests/FluentCMS.Components.Browser/Samples/HelperFaultTests.cs @@ -129,6 +129,59 @@ public async Task TargetSizeChecksTreeItemsOutsideTheTabOrder() Assert.Contains("div#second", failure.Message); } + // A box of 24 pixels that an ancestor clips to 12 can be hit only across those 12. + [Fact] + public async Task TargetSizeMeasuresWhatAClippingAncestorLeaves() + { + await using GalleryPage page = await gallery.OpenBlankAsync(Head + """ +
+ """); + + XunitException failure = await Assert.ThrowsAnyAsync(() => Wcag.AssertTargetSizesAsync(page.Page)); + + Assert.Contains("button#cut \"A\": 24.0 by 12.0 px", failure.Message); + } + + // The box of an open tree item holds its children; its own target is its row. + [Fact] + public async Task TargetSizeMeasuresTheRowOfAnOpenTreeItem() + { + await using GalleryPage page = await gallery.OpenBlankAsync(Head + """ +
  • Parent
    +
    • Child
    • Child
+ """); + + XunitException failure = await Assert.ThrowsAnyAsync(() => Wcag.AssertTargetSizesAsync(page.Page)); + + Assert.Contains("li#open", failure.Message); + } + + // A control with no box of its own is measured by what a pointer hits, here a pseudo-element of 10 pixels. + [Fact] + public async Task TargetSizeProbesAControlWithAnEmptyBox() + { + await using GalleryPage page = await gallery.OpenBlankAsync(Head + """ + + """); + + XunitException failure = await Assert.ThrowsAnyAsync(() => Wcag.AssertTargetSizesAsync(page.Page)); + + Assert.Contains("button#empty", failure.Message); + } + + [Fact] + public async Task TargetSizeChecksMenuItemsThatAreNotButtons() + { + await using GalleryPage page = await gallery.OpenBlankAsync(Head + """ +
Bold
+ """); + + XunitException failure = await Assert.ThrowsAnyAsync(() => Wcag.AssertTargetSizesAsync(page.Page)); + + Assert.Contains("div#check", failure.Message); + } + [Fact] public async Task TargetSizeExcludesControlsDisabledByAFieldset() { @@ -181,6 +234,35 @@ public async Task MotionFailsOnAnAnimationThatIgnoresReducedMotion() Assert.Contains("div#mover", failure.Message); } + // Movement that no box of an element shows: a pseudo-element, a background that travels, and a spinner that jumps + // in steps with still frames between them. + [Theory] + [InlineData("@keyframes slide { to { translate: 120px } } #mover::after { content: ''; display: block; width: 10px; height: 10px; animation: slide 2s infinite alternate }", "::after animates translate")] + [InlineData("@keyframes travel { to { background-position: 200px 0 } } #mover { height: 10px; background: linear-gradient(90deg, red, blue); animation: travel 2s linear infinite }", "div#mover")] + [InlineData("@keyframes spin { to { rotate: 1turn } } #mover { width: 20px; animation: spin 2s steps(4) infinite }", "div#mover")] + public async Task MotionFailsOnMovementThatNoBoxShows(string css, string expected) + { + await using GalleryPage page = await gallery.OpenBlankAsync($"{Head}
Moves
"); + + XunitException failure = await Assert.ThrowsAnyAsync(() => Wcag.AssertNoMotionAsync(page.Page)); + + Assert.Contains(expected, failure.Message); + } + + // A transition that starts after the window that watches the interaction still counts. + [Fact] + public async Task MotionFailsOnATransitionThatWaitsForItsDelay() + { + await using GalleryPage page = await gallery.OpenBlankAsync(Head + """ + +
→
+ """); + + XunitException failure = await Assert.ThrowsAnyAsync(() => Wcag.AssertNoMotionAsync(page.Page, () => page.Page.Locator("button").HoverAsync())); + + Assert.Contains("div#marker", failure.Message); + } + [Fact] public async Task MotionPassesAnAnimationThatReducedMotionTurnsOff() { From 47da723d889773c0d95f54ff272d276f3985f87c Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 30 Nov 2026 22:51:23 -0500 Subject: [PATCH 4/7] Ask a change of 3:1 of the focus indicator --- .../Forms/SelectTests.cs | 2 +- .../Forms/TemporalTests.cs | 2 +- .../Forms/TextInputTests.cs | 2 +- .../Harness/KeyboardDriver.cs | 20 +++++++++++++++++++ .../Samples/KeyboardIndicatorTests.cs | 12 ++++++++++- 5 files changed, 34 insertions(+), 4 deletions(-) diff --git a/tests/FluentCMS.Components.Browser/Forms/SelectTests.cs b/tests/FluentCMS.Components.Browser/Forms/SelectTests.cs index b2968292..97066e85 100644 --- a/tests/FluentCMS.Components.Browser/Forms/SelectTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/SelectTests.cs @@ -78,7 +78,7 @@ public async Task KeyboardChangesTheBoundValueAndHostRerendersRetainTheAccessibl IPage page = sample.Page; KeyboardDriver keys = page.Keys(); await keys.StartAtTopAsync(); - await keys.TabToAndAssertPaintChangeAsync(Binding, 0, page.Locator(".fl-select:has(> #select-binding)")); + await keys.TabToAndAssertPaintChangeAsync(Binding, -1, page.Locator(".fl-select:has(> #select-binding)")); await keys.AssertFocusNameAsync("Project role"); ILocator binding = page.Locator(Binding); await Expect(binding.Locator("option[value=owner]")).ToBeDisabledAsync(); diff --git a/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs b/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs index 0ce82d59..342597fd 100644 --- a/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/TemporalTests.cs @@ -187,7 +187,7 @@ public async Task NativeKeyboardEditKeepsFocusWithReducedMotion(RenderMode mode) await keys.StartAtTopAsync(); // The native controls before this example contribute several real segment stops each. await keys.TabToAsync(LiveLocal, maxPresses: 120); - await keys.TabToAndAssertPaintChangeAsync(LiveTime, 0, page.Locator(".fl-time-input:has(> #temporal-live-time)")); + await keys.TabToAndAssertPaintChangeAsync(LiveTime, -1, page.Locator(".fl-time-input:has(> #temporal-live-time)")); await keys.AssertFocusAsync(LiveTime); ILocator time = page.Locator(LiveTime); await Expect(time).ToHaveAccessibleNameAsync("Reminder time"); diff --git a/tests/FluentCMS.Components.Browser/Forms/TextInputTests.cs b/tests/FluentCMS.Components.Browser/Forms/TextInputTests.cs index 9e6d0288..2117afd8 100644 --- a/tests/FluentCMS.Components.Browser/Forms/TextInputTests.cs +++ b/tests/FluentCMS.Components.Browser/Forms/TextInputTests.cs @@ -16,7 +16,7 @@ public async Task TabReachesEachInputThenItsNamedActions(RenderMode mode) await FormsPage.FocusSettledAsync(page, mode); KeyboardDriver keys = page.Keys(); await keys.StartAtTopAsync(); - await keys.TabToAndAssertPaintChangeAsync("#input-clear", xFromLeft: 0, indicator: page.Locator("#parts .fl-input:has(> #input-clear)")); + await keys.TabToAndAssertPaintChangeAsync("#input-clear", xFromLeft: -1, indicator: page.Locator("#parts .fl-input:has(> #input-clear)")); await keys.AssertFocusNameAsync("With a clear action"); await keys.TabAsync(); await keys.AssertFocusAsync("#parts .fl-input:has(> #input-clear) > button.fl-input__action"); diff --git a/tests/FluentCMS.Components.Browser/Harness/KeyboardDriver.cs b/tests/FluentCMS.Components.Browser/Harness/KeyboardDriver.cs index 249c84f4..8cad1270 100644 --- a/tests/FluentCMS.Components.Browser/Harness/KeyboardDriver.cs +++ b/tests/FluentCMS.Components.Browser/Harness/KeyboardDriver.cs @@ -118,6 +118,26 @@ public async Task TabToAndAssertPaintChangeAsync(string selector, int xFromLeft, await TabToAsync(selector); string after = await ReadPixelAsync(indicator, xFromLeft); Assert.True(before != after, $"Tab reached '{selector}', but the indicator pixel on {indicator} at x={xFromLeft} stayed {after}."); + // A change has to be seen: RECIPE asks 3:1 of a mark that is needed, and focus is one. + double contrast = Contrast(before, after); + Assert.True(contrast >= 3, $"Tab reached '{selector}', but the indicator pixel on {indicator} at x={xFromLeft} went from {before} to {after}, {contrast:0.00}:1 where 3:1 is needed."); + } + + private static double Contrast(string first, string second) + { + static double Luminance(string pixel) + { + double Channel(int start) + { + double value = Convert.ToInt32(pixel.Substring(start, 2), 16) / 255.0; + return value <= 0.03928 ? value / 12.92 : Math.Pow((value + 0.055) / 1.055, 2.4); + } + + return 0.2126 * Channel(1) + 0.7152 * Channel(3) + 0.0722 * Channel(5); + } + + double a = Luminance(first), b = Luminance(second); + return (Math.Max(a, b) + 0.05) / (Math.Min(a, b) + 0.05); } // Waits a moment for focus to settle, since a pattern may move it after the key press. diff --git a/tests/FluentCMS.Components.Browser/Samples/KeyboardIndicatorTests.cs b/tests/FluentCMS.Components.Browser/Samples/KeyboardIndicatorTests.cs index 1a8c1eb7..2004446c 100644 --- a/tests/FluentCMS.Components.Browser/Samples/KeyboardIndicatorTests.cs +++ b/tests/FluentCMS.Components.Browser/Samples/KeyboardIndicatorTests.cs @@ -32,13 +32,23 @@ public async Task KeyboardDoesNotShowAnIndicatorWhenThePaintIsUnchanged(string c Assert.Contains("stayed", failure.Message); } + // A ring of 2 per cent black changes the pixel, but nobody sees it. + [Fact] + public async Task KeyboardDoesNotShowAnIndicatorThatCannotBeSeen() + { + await using GalleryPage page = await gallery.OpenBlankAsync(""); + KeyboardDriver keys = page.Page.Keys(); + XunitException failure = await Assert.ThrowsAnyAsync(() => keys.TabToAndAssertPaintChangeAsync("button", xFromLeft: -1)); + Assert.Contains("where 3:1 is needed", failure.Message); + } + [Fact] public async Task KeyboardShowsABackgroundOnlyIndicator() { await using GalleryPage page = await gallery.OpenBlankAsync(""" """); From fc0e5fbc4e43e01331475fcccb51d4ba5f6d314c Mon Sep 17 00:00:00 2001 From: Amir Pournasserian Date: Mon, 30 Nov 2026 22:51:24 -0500 Subject: [PATCH 5/7] Say what the helpers check and mark the superseded sentence of record 0002 --- CONTRIBUTING.md | 12 ++++++------ docs/decisions/0002-styling-architecture.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b467cacc..26f76203 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -202,7 +202,7 @@ $env:FLUENTCMS_BROWSER = "firefox" dotnet test --project tests/FluentCMS.Components.Browser --filter-class "*AccessibilitySamples" ``` -A test is written once for the three modes. The mode comes from `[ModeData]`. `OpenAsync` requires a successful document response and waits for the requested mode; in an interactive mode it also waits for `data-interactive="true"`. Before an axe scan starts, the fixture checks that the document's computed colour scheme and direction match the request. A 404 page or a second LTR scan in place of RTL fails the test. +A test is written once for the three modes. The mode comes from `[ModeData]`. `OpenAsync` requires a successful document response at the address it asked for (a redirect fails), extends a query that the path brings, and waits for the requested mode; in an interactive mode it also waits for `data-interactive="true"`. Before an axe scan starts, the fixture checks that the document's computed colour scheme and direction, and its density, match the request. A 404 page or a second LTR scan in place of RTL fails the test. For example: @@ -220,18 +220,18 @@ The helpers are in `tests/FluentCMS.Components.Browser/Harness`: | Helper | Checks | | --- | --- | | `Accessibility.AssertNoViolationsAsync` | axe-core finds nothing, in light, dark and right to left (light only in an interactive mode on a page in `StaticPages`). A failure names the rule, the target and the help address | -| `page.Keys()` | Drives the page with the keyboard. `AssertFocusNameAsync` checks the focused element's accessible name with Playwright; `TabToAndAssertPaintChangeAsync` checks a known point on its focus indicator | -| `Wcag.AssertTargetSizesAsync` | Every operable target is at least 24 by 24 CSS pixels in both densities. This is the [project rule](design/system/RECIPE.md), not a check that permits smaller targets if they are spaced apart. A box under the minimum passes only if a pointer hits the element across the whole square, as when a pseudo-element widens it | +| `page.Keys()` | Drives the page with the keyboard. `AssertFocusNameAsync` checks the focused element's accessible name with Playwright; `TabToAndAssertPaintChangeAsync` checks that a known point on its focus indicator changes by at least 3:1 | +| `Wcag.AssertTargetSizesAsync` | Every operable target is at least 24 by 24 CSS pixels in both densities. This is the [project rule](design/system/RECIPE.md), not a check that permits smaller targets if they are spaced apart. A box is measured as a pointer can reach it: an ancestor that clips its overflow cuts it, and an open tree item is its row. A box under the minimum passes only if a pointer hits the element across the whole square, as when a pseudo-element widens it | | `Wcag.AssertNoHorizontalScrollAsync` | The page does not scroll sideways at 320 pixels (1.4.10) | -| `Wcag.AssertNoMotionAsync` | Watches for movement under reduced motion before and during the supplied interaction. A colour change alone is not movement | +| `Wcag.AssertNoMotionAsync` | Watches for movement under reduced motion before and during the supplied interaction: boxes that move, and animations or transitions of a property that moves or resizes, also on a pseudo-element, a travelling background, or one that waits for its delay. A colour or opacity change alone is not movement | | `Overlay.IsOpenAsync`, `IsModalAsync`, `IsInertAsync`, `AssertTabStaysInsideAsync` | A dialog or a popover is open, is modal, leaves the page behind it inert, and keeps Tab inside. `Overlay.SettledAsync` waits past the event of a close before a test says that focus stayed where it was | | `Scrolling.AtRestAsync`, `IntoViewAsync`, `AssertInWindow` | Waits until the page has stopped scrolling, which Firefox and WebKit may do over several frames after a key or a call; brings an element into view; checks that a point a pointer is sent to lies in the window | -For a focus ring drawn on a wrapper, pass the wrapper as `indicator` and choose a point on the ring: the offset is measured from the left edge, halfway down. This checks a visible change at that point, not focus contrast across the whole control. For motion, pass the action itself, for example `Wcag.AssertNoMotionAsync(page, () => button.HoverAsync())`. Checking only after the action can miss a transition that has already finished. +For a focus ring drawn on a wrapper, pass the wrapper as `indicator` and choose a point on the ring: the offset is measured from the left edge, halfway down. The change at that point must be at least 3:1, which the recipe asks of a mark that is needed; it is not focus contrast across the whole control. Choose a point where the ring lies on the background, not on a border it covers. For motion, pass the action itself, for example `Wcag.AssertNoMotionAsync(page, () => button.HoverAsync())`. Checking only after the action can miss a transition that has already finished. In an interactive mode, let .NET remove what .NET rendered. A test that takes such an element out with script leaves Blazor with a page it no longer knows, and what follows fails for that reason alone. The overlay tests remove an element with script in static mode only. -`tests/FluentCMS.Components.Browser/Samples` holds working examples and regressions that put each helper in front of the fault it should catch. The gallery itself holds no deliberate fault. To check gallery startup with a non-default build path, a production parent environment, and quiet logging, run the separate regression from the repository root: +`tests/FluentCMS.Components.Browser/Samples` holds working examples and regressions that put each helper in front of the fault it should catch. The gallery itself holds no deliberate fault. The fixture passes the gallery none of the host settings of its own environment (`ASPNETCORE_*`, `Kestrel__*`, `Logging__*`, the environment, addresses and startup hooks of `DOTNET_*`), and sets what the gallery needs. To check gallery startup with a non-default build path and under a parent that sets a production environment, quiet logging, console logging settings or addresses of its own, run the separate regression from the repository root; the nightly workflow runs it too: ```powershell node tests/FluentCMS.Components.Browser/test-startup.mjs diff --git a/docs/decisions/0002-styling-architecture.md b/docs/decisions/0002-styling-architecture.md index f9b2cd78..e0dc84e1 100644 --- a/docs/decisions/0002-styling-architecture.md +++ b/docs/decisions/0002-styling-architecture.md @@ -22,7 +22,7 @@ The alternatives were weighed in the plan. A CSS framework such as Bootstrap or 8. **State comes from the real attribute**, never from a class: `disabled`, `aria-invalid`, `aria-pressed`, `aria-selected`, `aria-current`, `aria-expanded`, `[open]`, `:checked`, `:popover-open`. Where no attribute exists, a `data-fl-` attribute is used, such as `data-fl-active`. 9. **Names.** Classes are `fl-`, `fl-__` and `fl---`, custom properties are `--fl-…` and data attributes are `data-fl-…`. A modifier names what a thing is, not how it looks. 10. **No inline script and no injected `