Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions AuBtechReviewAgent.Tests/Web/CitationLoopContrastTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Xunit;

namespace AuBtechReviewAgent.Tests;

/// <summary>
/// The landing page's citation example (CitationLoop) at rest in each of its states, in both themes. The CI
/// accessibility check sees the example only stopped on its first verdict (it asks for less motion), so the other
/// states are checked here from the theme colours in Styles/tailwind.input.css: every text reaches 4.5:1 on what is
/// behind it once a fade has finished. Read as source.
/// </summary>
public class CitationLoopContrastTests
{
private static readonly Regex Token = new(@"--(?<name>[a-z-]+):\s*(?<r>\d+)\s+(?<g>\d+)\s+(?<b>\d+);", RegexOptions.Compiled);

// Text colour, the colour behind it, and where in the example the pair is seen.
private static readonly (string Text, string Behind, string Where)[] Pairs =
{
("muted", "page", "the card's title line"),
("text", "page", "the sentence"),
("navy", "page", "a citation number at rest"),
("navy", "active", "a citation number while it is checked"),
("muted", "soft", "\"Checking citation N against the paper…\""),
("supported", "supported-fill", "citation 5 marked Supported"),
("partly", "partly-fill", "citation 4 marked Partly supported"),
("not-supported", "not-supported-fill", "citation 10 marked Not supported"),
("supported", "page", "the Supported chip"),
("partly", "page", "the Partly supported chip"),
("not-supported", "page", "the Not supported chip"),
("text", "supported-fill", "the quote on the Supported card"),
("text", "partly-fill", "the quote on the Partly supported card"),
("text", "not-supported-fill", "the reason on the Not supported card"),
("muted", "supported-fill", "the source and note on the Supported card"),
("muted", "partly-fill", "the source and note on the Partly supported card"),
("muted", "not-supported-fill", "the source and note on the Not supported card"),
};

private static string? Root()
{
string? root = AppContext.BaseDirectory;
while (root != null && !File.Exists(Path.Join(root, "AuBtechReviewAgent.sln"))) root = Path.GetDirectoryName(root);
return root;
}

[Theory]
[InlineData(":root {")]
[InlineData("[data-theme=\"dark\"] {")]
public void EveryStateOfTheExampleMeetsContrastAtItsFinalColours(string theme)
{
string? root = Root();
if (root == null) return; // not run from the repository (packaged tests)

string css = File.ReadAllText(Path.Join(root, "AuBtechReviewAgent", "Styles", "tailwind.input.css"));
int start = css.IndexOf(theme, StringComparison.Ordinal);
Assert.True(start >= 0, $"No {theme} block in tailwind.input.css");
string block = css[start..css.IndexOf('}', start)];
var colours = Token.Matches(block).ToDictionary(
m => m.Groups["name"].Value,
m => new[] { m.Groups["r"].Value, m.Groups["g"].Value, m.Groups["b"].Value }.Select(v => int.Parse(v, CultureInfo.InvariantCulture)).ToArray());

var failing = Pairs
.Select(p => (p.Where, Ratio: Contrast(colours[p.Text], colours[p.Behind])))
.Where(p => p.Ratio < 4.5)
.Select(p => $"{p.Where} ({p.Ratio:0.00}:1)")
.ToList();

Assert.True(failing.Count == 0, $"Below 4.5:1 in {theme.TrimEnd(' ', '{')}: " + string.Join(", ", failing));
}

[Fact]
public void TheVerdictStatesUseTheColoursCheckedHere()
{
string? root = Root();
if (root == null) return;

string css = File.ReadAllText(Path.Join(root, "AuBtechReviewAgent", "Styles", "tailwind.input.css"));
Assert.Contains(".tai-loop-ok { --loop-ink: var(--supported); --loop-fill: var(--supported-fill);", css);
Assert.Contains(".tai-loop-partly { --loop-ink: var(--partly); --loop-fill: var(--partly-fill);", css);
Assert.Contains(".tai-loop-not { --loop-ink: var(--not-supported); --loop-fill: var(--not-supported-fill);", css);
Assert.Contains("0%, 8% { background-color: rgb(var(--active)); color: rgb(var(--navy));", css);
Assert.Contains("9.5%, 31.5% { background-color: rgb(var(--loop-fill)); color: rgb(var(--loop-ink));", css);
Assert.Contains("33.3%, 100% { background-color: transparent; color: rgb(var(--navy));", css);
}

// WCAG 2.x contrast ratio of two sRGB colours.
private static double Contrast(int[] a, int[] b)
{
double la = Luminance(a), lb = Luminance(b);
return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05);
}

private static double Luminance(int[] rgb)
{
double[] c = rgb.Select(v => v / 255.0).Select(v => v <= 0.04045 ? v / 12.92 : Math.Pow((v + 0.055) / 1.055, 2.4)).ToArray();
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
}
}
2 changes: 1 addition & 1 deletion docs/wiki/06-web-app-and-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ The app aims at WCAG 2.2 level AA. What that means in the code:
| Text contrast at least 4.5:1 (no `text-gray-400` for text), links inside text underlined, click targets at least 24 × 24 px, verdicts never shown by colour alone | the components and `ui-*` classes |
| Animations stop when the system asks for reduced motion | `Styles/tailwind.input.css` |

The CI job **Accessibility** starts the app and runs axe-core on the public pages (`tools/a11y/axe-check.mjs`); a serious or critical problem fails the build. The pages named in `A11Y_DARK_PAGES` are checked a second time in the dark theme. Four pages are checked at once (`A11Y_WORKERS`, issue #396), each in its own browser context as before, and the log lists the pages in their usual order whatever order they finish in, so the pages, the rules and the failures reported are the same as when they were checked one by one; on CI this cut the axe-core step from about 135 s to 44 s. The job also photographs every checked page at 390 × 844, 1440 × 900 and 1920 × 1080 px and uploads the pictures as the workflow artifact `a11y-screenshots`, so a pull request that changes markup can be looked at without running the app. A page that scrolls is also photographed whole at 1440 px (`<page>-<theme>-1440-full.png`, issue #246): the app frame is released as print mode releases it, so the Metrics tables, the report's later sections and the lower parts of the trust pages can be reviewed too. Automated checks find only part of the problems, so keyboard and screen-reader checks by hand are still needed after larger UI changes.
The CI job **Accessibility** starts the app and runs axe-core on the public pages (`tools/a11y/axe-check.mjs`); a serious or critical problem fails the build. The pages named in `A11Y_DARK_PAGES` are checked a second time in the dark theme. Four pages are checked at once (`A11Y_WORKERS`, issue #396), each in its own browser context as before, and the log lists the pages in their usual order whatever order they finish in, so the pages, the rules and the failures reported are the same as when they were checked one by one; on CI this cut the axe-core step from about 135 s to 44 s. Every page is opened asking for less motion (`prefers-reduced-motion: reduce`) and checked only once its moving parts are at rest (issue #503). axe reads colours as they are drawn, so text caught half-way through a fade used to fail colour contrast at random, most often in the landing page's citation example. With less motion asked for, `CitationLoop` stops on its first verdict, fully drawn; any animation or transition that still runs to an end is then run to it, and one that repeats for ever is paused where it is, so axe and the screenshots see the same frame. No page and no rule is left out. The example's other states (a citation being checked, Partly supported, Not supported) are not seen by axe this way, so `CitationLoopContrastTests` checks each of them at its final colours in both themes, from the tokens in `Styles/tailwind.input.css`. The job also photographs every checked page at 390 × 844, 1440 × 900 and 1920 × 1080 px and uploads the pictures as the workflow artifact `a11y-screenshots`, so a pull request that changes markup can be looked at without running the app. A page that scrolls is also photographed whole at 1440 px (`<page>-<theme>-1440-full.png`, issue #246): the app frame is released as print mode releases it, so the Metrics tables, the report's later sections and the lower parts of the trust pages can be reviewed too. Automated checks find only part of the problems, so keyboard and screen-reader checks by hand are still needed after larger UI changes.

### Speed and the live connection

Expand Down
2 changes: 1 addition & 1 deletion docs/wiki/07-extending-and-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Add an entry to `Glossary.All` in `Glossary.cs` (a key, the term, and one or two

### Checking accessibility locally

Start the app (`dotnet watch` in `AuBtechReviewAgent`), then in `tools/a11y` run `npm ci`, `npx playwright install chromium` and `node axe-check.mjs`. `BASE_URL` changes the address (default `http://localhost:5038`) and `A11Y_PAGES` the pages (default `/,/review,/metrics,/glossary`). Also try every changed page with the keyboard only: Tab through it, check that focus is always visible, and that Escape closes what it opened.
Start the app (`dotnet watch` in `AuBtechReviewAgent`), then in `tools/a11y` run `npm ci`, `npx playwright install chromium` and `node axe-check.mjs`. `BASE_URL` changes the address (default `http://localhost:5038`) and `A11Y_PAGES` the pages (default `/,/review,/metrics,/glossary`). `CHROMIUM_PATH` points it at an installed Chrome instead of Playwright's own. The check opens every page asking for less motion and brings animations to rest before it measures, so a result does not depend on when a fade was caught (issue #503). Also try every changed page with the keyboard only: Tab through it, check that focus is always visible, and that Escape closes what it opened.

`node print-check.mjs` in the same folder prints pages to PDF the way "Print or save as PDF" does and fails when a page is cut to one screen, when the top bar is printed or when the title is missing (issue #153). `PRINT_PAGES` lists the pages with the least number of A4 pages each must fill (CI: `/design/report=3,/about=1`), and `PRINT_OUT` names a folder for the PDFs; CI puts them with the screenshots in the `a11y-screenshots` artifact.

Expand Down
22 changes: 21 additions & 1 deletion tools/a11y/axe-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
//
// A11Y_WORKERS pages are checked at once (default 4, issue #396), each in its own browser context as before, so a
// page sees nothing of another. The log is printed in the order of the pages, whatever order they finish in.
//
// Every page is opened asking for less motion and checked only once its moving parts are at rest (issue #503). axe
// reads colours as they are drawn, so text caught half-way through a fade failed colour contrast at random, most
// often in the landing page's citation example. No page and no rule is left out; see settle() below.
import { chromium } from 'playwright';
import { AxeBuilder } from '@axe-core/playwright';
import { mkdirSync, readFileSync } from 'node:fs';
Expand All @@ -29,7 +33,7 @@ const browser = await chromium.launch(process.env.CHROMIUM_PATH ? { executablePa
async function check({ path, theme }) {
const label = theme === 'dark' ? `${path} (dark)` : path;
const lines = [];
const context = await browser.newContext();
const context = await browser.newContext({ reducedMotion: 'reduce' });
try {
if (theme === 'dark') await context.addInitScript(() => localStorage.setItem('traceableai-theme', 'dark'));
const page = await context.newPage();
Expand All @@ -41,6 +45,7 @@ async function check({ path, theme }) {
}
if (extraCss) await page.addStyleTag({ content: extraCss });
await page.waitForTimeout(1500);
await settle(page);
const result = await new AxeBuilder({ page }).withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']).analyze();
const blocking = result.violations.filter(v => v.impact === 'serious' || v.impact === 'critical');
lines.push(`\n${label}: ${result.violations.length} violation(s), ${blocking.length} serious or critical`);
Expand All @@ -55,6 +60,21 @@ async function check({ path, theme }) {
}
}

// Brings every animation and transition to rest before axe looks. The page asks for less motion, so the landing
// page's citation example is already stopped on its first verdict, fully drawn. Anything that still runs to an end
// (a fade-in, a colour transition) is run to that end; anything that repeats for ever and is still running is paused
// where it is, so the measurement and the screenshots see the same frame. Then two frames are drawn.
async function settle(page) {
await page.evaluate(async () => {
for (const animation of document.getAnimations()) {
const end = animation.effect ? animation.effect.getComputedTiming().endTime : Infinity;
if (Number.isFinite(end)) animation.finish();
else if (animation.playState === 'running') animation.pause();
}
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
}

async function photograph(page, path, theme) {
const name = (path.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '') || 'landing') + '-' + theme;
for (const [width, height] of widths) {
Expand Down