@entifix/testing-e2e 0.18.0 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -63,6 +63,7 @@ import { resolveE2eProfile, isMockProfile, requireLiveUrl } from '@entifix/testi
63
63
  import { entityBackendHandlers, configurationHandler } from '@entifix/testing-e2e/fixtures';
64
64
  import { defineServiceE2e } from '@entifix/testing-e2e/service';
65
65
  import { defineEntifixE2eConfig, defineEntifixE2eTest, EntityTablePage } from '@entifix/testing-e2e/playwright';
66
+ import { expectNoNewA11yViolations, walkKeyboard, expectFocusKept } from '@entifix/testing-e2e/a11y';
66
67
  ```
67
68
 
68
69
  `.` carries no Playwright, no msw and no vitest, so a consumer pulls only what
@@ -99,6 +100,41 @@ Two stubs are always needed, not one: the entity endpoint _and_ the app's
99
100
  latter before they can issue the former. `configurationHandler` exists so that
100
101
  is not something each suite has to remember.
101
102
 
103
+ ### The accessibility gate on a screen (Playwright)
104
+
105
+ `@entifix/testing-e2e/a11y` needs `@axe-core/playwright` (an optional peer).
106
+
107
+ ```ts
108
+ // After the screen has rendered what it is for:
109
+ await expectNoNewA11yViolations(page, { screen: 'customers', baselinePath });
110
+ await walkKeyboard(page, { skipLink: true, mainIndexMax: 3 });
111
+
112
+ // After each write:
113
+ await page.getByRole('button', { name: 'Guardar' }).click();
114
+ await expectFocusKept(page);
115
+ ```
116
+
117
+ - **`expectNoNewA11yViolations`** runs axe against WCAG 2.2 AA and fails on a
118
+ serious or critical fingerprint the baseline does not accept, and on an
119
+ accepted one that is no longer there. Moderate and minor findings become test
120
+ annotations. `A11Y_BASELINE=update` rewrites the screen's entries — owners
121
+ kept, a new entry's left empty for a person to fill with the issue that
122
+ removes it; `unownedEntries(baseline)` lets a spec refuse an empty one. The file
123
+ also records its fingerprint scheme under `$fingerprints`, which is not an
124
+ entry.
125
+ - **`walkKeyboard`** tabs from the top and fails on a missing skip link, a first
126
+ stop inside `main` past `mainIndexMax`, a stop with no visible indicator or
127
+ entirely hidden by something else, and a stop that jumps back more than a row
128
+ within the content it scrolls with.
129
+ - **`expectFocusKept`** fails when focus fell back to `<body>`. A write known to
130
+ drop it passes `{ lostUntil: 'owner/repo#N' }`, and the check then fails once
131
+ focus is kept, so the fix has to remove the mark.
132
+
133
+ A baseline only shrinks: switch the gate on with today's fingerprints, each
134
+ against its issue, and tighten `mainIndexMax` the same way. The pure halves —
135
+ `findingsOf`, `compareWithBaseline`, `updateBaseline` and `assessWalk` — are
136
+ exported for a host that drives a browser some other way.
137
+
102
138
  ### Service e2e (Vitest)
103
139
 
104
140
  ```ts
@@ -0,0 +1,21 @@
1
+ import { type Page } from '@playwright/test';
2
+ export interface A11yGateOptions {
3
+ /** The screen's name in every fingerprint: stable, and one per screen. */
4
+ readonly screen: string;
5
+ /** The committed baseline, shared by every screen of one e2e project. */
6
+ readonly baselinePath: string;
7
+ /** Selectors axe skips, for third-party widgets the host does not render. */
8
+ readonly exclude?: readonly string[];
9
+ }
10
+ /**
11
+ * Runs axe over the page against WCAG 2.2 AA and fails on a serious or
12
+ * critical violation the baseline does not accept, or on an accepted one that
13
+ * is gone. Moderate and minor findings are attached to the test as an
14
+ * annotation and never fail it.
15
+ *
16
+ * With `A11Y_BASELINE=update` it rewrites this screen's entries instead: an
17
+ * owner is kept where the fingerprint survived and left empty where it is new,
18
+ * for a person to fill with the issue that removes it.
19
+ */
20
+ export declare function expectNoNewA11yViolations(page: Page, { screen, baselinePath, exclude }: A11yGateOptions): Promise<void>;
21
+ //# sourceMappingURL=axe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"axe.d.ts","sourceRoot":"","sources":["../../src/a11y/axe.ts"],"names":[],"mappings":"AAUA,OAAO,EAAU,KAAK,IAAI,EAAQ,MAAM,kBAAkB,CAAC;AAa3D,MAAM,WAAW,eAAe;IAC9B,0EAA0E;IAC1E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yEAAyE;IACzE,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,6EAA6E;IAC7E,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC;AA+BD;;;;;;;;;GASG;AACH,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,IAAI,EACV,EAAE,MAAM,EAAE,YAAY,EAAE,OAAY,EAAE,EAAE,eAAe,GACtD,OAAO,CAAC,IAAI,CAAC,CAsCf"}
@@ -0,0 +1,76 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import AxeBuilder from '@axe-core/playwright';
4
+ import { expect, test } from '@playwright/test';
5
+ import { compareWithBaseline, describeVerdict, findingsOf, updateBaseline, WCAG_22_AA_TAGS } from './baseline.js';
6
+ import { settled } from './settle.js';
7
+ const readBaseline = (path)=>existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
8
+ /**
9
+ * Runs `write` while holding a directory lock beside `path`. Playwright runs
10
+ * screens in parallel workers, and two of them rewriting one baseline at once
11
+ * would each drop the other's screen.
12
+ */ const underLock = (path, write)=>{
13
+ const lock = `${path}.lock`;
14
+ const wait = new Int32Array(new SharedArrayBuffer(4));
15
+ for(let attempt = 0;; attempt += 1){
16
+ try {
17
+ mkdirSync(lock);
18
+ break;
19
+ } catch (error) {
20
+ if (attempt > 400) throw error;
21
+ Atomics.wait(wait, 0, 0, 25);
22
+ }
23
+ }
24
+ try {
25
+ write();
26
+ } finally{
27
+ rmdirSync(lock);
28
+ }
29
+ };
30
+ /**
31
+ * Runs axe over the page against WCAG 2.2 AA and fails on a serious or
32
+ * critical violation the baseline does not accept, or on an accepted one that
33
+ * is gone. Moderate and minor findings are attached to the test as an
34
+ * annotation and never fail it.
35
+ *
36
+ * With `A11Y_BASELINE=update` it rewrites this screen's entries instead: an
37
+ * owner is kept where the fingerprint survived and left empty where it is new,
38
+ * for a person to fill with the issue that removes it.
39
+ */ export async function expectNoNewA11yViolations(page, { screen, baselinePath, exclude = [] }) {
40
+ await settled(page);
41
+ // `ancestry`: fingerprint by the node's full path, which does not depend on
42
+ // what else happens to be on the page (`A11yNodeResult.ancestry`).
43
+ let builder = new AxeBuilder({
44
+ page
45
+ }).withTags([
46
+ ...WCAG_22_AA_TAGS
47
+ ]).options({
48
+ ancestry: true
49
+ });
50
+ for (const selector of exclude)builder = builder.exclude(selector);
51
+ const results = await builder.analyze();
52
+ const findings = findingsOf(screen, results.violations);
53
+ if (process.env['A11Y_BASELINE'] === 'update') {
54
+ underLock(baselinePath, ()=>{
55
+ const next = updateBaseline(screen, findings, readBaseline(baselinePath));
56
+ mkdirSync(dirname(baselinePath), {
57
+ recursive: true
58
+ });
59
+ writeFileSync(baselinePath, `${JSON.stringify(next, null, 2)}\n`);
60
+ });
61
+ return;
62
+ }
63
+ const verdict = compareWithBaseline(screen, findings, readBaseline(baselinePath));
64
+ for (const finding of verdict.reported){
65
+ test.info().annotations.push({
66
+ type: `a11y ${finding.impact}`,
67
+ description: `${finding.fingerprint} — ${finding.help}`
68
+ });
69
+ }
70
+ expect([
71
+ ...verdict.added.map((finding)=>finding.fingerprint),
72
+ ...verdict.stale
73
+ ], describeVerdict(screen, verdict)).toEqual([]);
74
+ }
75
+
76
+ //# sourceMappingURL=axe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/a11y/axe.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readFileSync,\n rmdirSync,\n writeFileSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\n\nimport AxeBuilder from '@axe-core/playwright';\nimport { expect, type Page, test } from '@playwright/test';\n\nimport {\n type A11yBaseline,\n type A11yViolation,\n compareWithBaseline,\n describeVerdict,\n findingsOf,\n updateBaseline,\n WCAG_22_AA_TAGS,\n} from './baseline.js';\nimport { settled } from './settle.js';\n\nexport interface A11yGateOptions {\n /** The screen's name in every fingerprint: stable, and one per screen. */\n readonly screen: string;\n /** The committed baseline, shared by every screen of one e2e project. */\n readonly baselinePath: string;\n /** Selectors axe skips, for third-party widgets the host does not render. */\n readonly exclude?: readonly string[];\n}\n\nconst readBaseline = (path: string): A11yBaseline =>\n existsSync(path)\n ? (JSON.parse(readFileSync(path, 'utf8')) as A11yBaseline)\n : {};\n\n/**\n * Runs `write` while holding a directory lock beside `path`. Playwright runs\n * screens in parallel workers, and two of them rewriting one baseline at once\n * would each drop the other's screen.\n */\nconst underLock = (path: string, write: () => void) => {\n const lock = `${path}.lock`;\n const wait = new Int32Array(new SharedArrayBuffer(4));\n for (let attempt = 0; ; attempt += 1) {\n try {\n mkdirSync(lock);\n break;\n } catch (error) {\n if (attempt > 400) throw error;\n Atomics.wait(wait, 0, 0, 25);\n }\n }\n try {\n write();\n } finally {\n rmdirSync(lock);\n }\n};\n\n/**\n * Runs axe over the page against WCAG 2.2 AA and fails on a serious or\n * critical violation the baseline does not accept, or on an accepted one that\n * is gone. Moderate and minor findings are attached to the test as an\n * annotation and never fail it.\n *\n * With `A11Y_BASELINE=update` it rewrites this screen's entries instead: an\n * owner is kept where the fingerprint survived and left empty where it is new,\n * for a person to fill with the issue that removes it.\n */\nexport async function expectNoNewA11yViolations(\n page: Page,\n { screen, baselinePath, exclude = [] }: A11yGateOptions,\n): Promise<void> {\n await settled(page);\n // `ancestry`: fingerprint by the node's full path, which does not depend on\n // what else happens to be on the page (`A11yNodeResult.ancestry`).\n let builder = new AxeBuilder({ page })\n .withTags([...WCAG_22_AA_TAGS])\n .options({ ancestry: true });\n for (const selector of exclude) builder = builder.exclude(selector);\n const results = await builder.analyze();\n const findings = findingsOf(\n screen,\n results.violations as unknown as readonly A11yViolation[],\n );\n\n if (process.env['A11Y_BASELINE'] === 'update') {\n underLock(baselinePath, () => {\n const next = updateBaseline(screen, findings, readBaseline(baselinePath));\n mkdirSync(dirname(baselinePath), { recursive: true });\n writeFileSync(baselinePath, `${JSON.stringify(next, null, 2)}\\n`);\n });\n return;\n }\n\n const verdict = compareWithBaseline(\n screen,\n findings,\n readBaseline(baselinePath),\n );\n for (const finding of verdict.reported) {\n test.info().annotations.push({\n type: `a11y ${finding.impact}`,\n description: `${finding.fingerprint} — ${finding.help}`,\n });\n }\n expect(\n [...verdict.added.map(finding => finding.fingerprint), ...verdict.stale],\n describeVerdict(screen, verdict),\n ).toEqual([]);\n}\n"],"names":["existsSync","mkdirSync","readFileSync","rmdirSync","writeFileSync","dirname","AxeBuilder","expect","test","compareWithBaseline","describeVerdict","findingsOf","updateBaseline","WCAG_22_AA_TAGS","settled","readBaseline","path","JSON","parse","underLock","write","lock","wait","Int32Array","SharedArrayBuffer","attempt","error","Atomics","expectNoNewA11yViolations","page","screen","baselinePath","exclude","builder","withTags","options","ancestry","selector","results","analyze","findings","violations","process","env","next","recursive","stringify","verdict","finding","reported","info","annotations","push","type","impact","description","fingerprint","help","added","map","stale","toEqual"],"mappings":"AAAA,SACEA,UAAU,EACVC,SAAS,EACTC,YAAY,EACZC,SAAS,EACTC,aAAa,QACR,UAAU;AACjB,SAASC,OAAO,QAAQ,YAAY;AAEpC,OAAOC,gBAAgB,uBAAuB;AAC9C,SAASC,MAAM,EAAaC,IAAI,QAAQ,mBAAmB;AAE3D,SAGEC,mBAAmB,EACnBC,eAAe,EACfC,UAAU,EACVC,cAAc,EACdC,eAAe,QACV,gBAAgB;AACvB,SAASC,OAAO,QAAQ,cAAc;AAWtC,MAAMC,eAAe,CAACC,OACpBhB,WAAWgB,QACNC,KAAKC,KAAK,CAAChB,aAAac,MAAM,WAC/B,CAAC;AAEP;;;;CAIC,GACD,MAAMG,YAAY,CAACH,MAAcI;IAC/B,MAAMC,OAAO,GAAGL,KAAK,KAAK,CAAC;IAC3B,MAAMM,OAAO,IAAIC,WAAW,IAAIC,kBAAkB;IAClD,IAAK,IAAIC,UAAU,IAAKA,WAAW,EAAG;QACpC,IAAI;YACFxB,UAAUoB;YACV;QACF,EAAE,OAAOK,OAAO;YACd,IAAID,UAAU,KAAK,MAAMC;YACzBC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,QAAQiB,UACxBc,OAAO,CAAC,EAAE;AACd"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The screen-level accessibility ratchet, as data: what axe found on one
3
+ * screen, reduced to fingerprints that survive a re-render, compared with what
4
+ * a committed baseline already accepts.
5
+ *
6
+ * A baseline maps each accepted fingerprint to the issue that removes it, so a
7
+ * host can switch the gate on with a backlog and the backlog can only shrink:
8
+ * a new serious or critical fingerprint fails, and so does an accepted one
9
+ * that is no longer there, which is how a fix is made to delete its entry.
10
+ */
11
+ /** axe's impact levels, least to most severe. */
12
+ export type A11yImpact = 'minor' | 'moderate' | 'serious' | 'critical';
13
+ /** The part of an axe node this module reads. */
14
+ export interface A11yNodeResult {
15
+ readonly target: readonly unknown[];
16
+ /**
17
+ * The node's full `tag:nth-child` path, present when axe ran with
18
+ * `ancestry: true`. Preferred over `target`: axe builds a target as the
19
+ * shortest selector unique on the page at that moment, so a hidden copy of
20
+ * the previous page (a router's `<Activity>`) turns `.gallery` into a long
21
+ * path on one run and back on the next.
22
+ */
23
+ readonly ancestry?: readonly unknown[];
24
+ }
25
+ /** The part of an axe violation this module reads. */
26
+ export interface A11yViolation {
27
+ readonly id: string;
28
+ readonly impact?: A11yImpact | null;
29
+ readonly help?: string;
30
+ readonly nodes: readonly A11yNodeResult[];
31
+ }
32
+ /** One fingerprint found on a screen, with the severity it was found at. */
33
+ export interface A11yFinding {
34
+ readonly fingerprint: string;
35
+ readonly impact: A11yImpact;
36
+ readonly help: string;
37
+ }
38
+ /**
39
+ * Accepted fingerprints, each against the issue that removes it, plus the
40
+ * {@link FINGERPRINT_KEY} naming the scheme they were computed with.
41
+ */
42
+ export type A11yBaseline = Readonly<Record<string, string>>;
43
+ /**
44
+ * The key a baseline records its fingerprint scheme under. Every other key is
45
+ * a fingerprint; this one is not, and no rule here treats it as one.
46
+ */
47
+ export declare const FINGERPRINT_KEY = "$fingerprints";
48
+ /**
49
+ * The scheme {@link findingsOf} computes today. It changes only when the
50
+ * fingerprint does, and a baseline recorded under another scheme is a
51
+ * re-keying rather than new debt: CI then holds it to "no more entries than
52
+ * before" instead of "no new keys", which a rename of every key would fail.
53
+ */
54
+ export declare const FINGERPRINT_SCHEME = "ancestry-1";
55
+ /** A baseline's fingerprint entries, without the scheme marker. */
56
+ export declare const baselineEntries: (baseline: A11yBaseline) => [string, string][];
57
+ /** What a gate run decides for one screen. */
58
+ export interface A11yVerdict {
59
+ /** Serious or critical, and not in the baseline: these fail. */
60
+ readonly added: readonly A11yFinding[];
61
+ /** In the baseline for this screen, and no longer found: these fail too. */
62
+ readonly stale: readonly string[];
63
+ /** Moderate or minor: reported, never failing. */
64
+ readonly reported: readonly A11yFinding[];
65
+ }
66
+ /** The levels that fail the gate (ADR 0024). */
67
+ export declare const GATED: ReadonlySet<A11yImpact>;
68
+ /** The rule tags the gate runs: WCAG 2.2 AA, with 2.1's A level. */
69
+ export declare const WCAG_22_AA_TAGS: readonly ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];
70
+ /**
71
+ * A selector stable across renders and across axe's own choices: generated ids
72
+ * written `#generated-id`; every `:nth-child(k)` and `:nth-of-type(k)` written
73
+ * with `n`, so a run of identical siblings is one fingerprint rather than one
74
+ * per row; and each compound's classes and attributes sorted, because axe
75
+ * orders them by how unique they happen to be on the page at the time.
76
+ */
77
+ export declare const normalizeTarget: (target: readonly unknown[]) => string;
78
+ /** `rule|target|screen`: the identity of one failing node. */
79
+ export declare const fingerprintOf: (rule: string, target: string, screen: string) => string;
80
+ /** The screen a fingerprint belongs to. */
81
+ export declare const screenOf: (fingerprint: string) => string;
82
+ /** Every distinct fingerprint in `violations`, at its rule's impact. */
83
+ export declare const findingsOf: (screen: string, violations: readonly A11yViolation[]) => A11yFinding[];
84
+ /** Judges one screen's findings against the baseline. */
85
+ export declare const compareWithBaseline: (screen: string, findings: readonly A11yFinding[], baseline: A11yBaseline) => A11yVerdict;
86
+ /**
87
+ * The baseline with this screen's entries replaced by what was found: owners
88
+ * kept for fingerprints still present, and an empty owner for a new one, which
89
+ * {@link unownedEntries} refuses until a person names its issue.
90
+ */
91
+ export declare const updateBaseline: (screen: string, findings: readonly A11yFinding[], baseline: A11yBaseline) => A11yBaseline;
92
+ /** An issue reference in the form GitHub links across repositories. */
93
+ export declare const ISSUE_REFERENCE: RegExp;
94
+ /** Every entry whose owner is not an `owner/repo#N` issue reference. */
95
+ export declare const unownedEntries: (baseline: A11yBaseline) => string[];
96
+ /** A failure message that names every fingerprint and what to do about it. */
97
+ export declare const describeVerdict: (screen: string, verdict: A11yVerdict) => string;
98
+ //# sourceMappingURL=baseline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"baseline.d.ts","sourceRoot":"","sources":["../../src/a11y/baseline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,iDAAiD;AACjD,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,UAAU,CAAC;AAEvE,iDAAiD;AACjD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC;IACpC;;;;;;OAMG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,OAAO,EAAE,CAAC;CACxC;AAED,sDAAsD;AACtD,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IACpC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,cAAc,EAAE,CAAC;CAC3C;AAED,4EAA4E;AAC5E,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED;;;GAGG;AACH,MAAM,MAA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GACzB,QAAQ,MAAM,EACd,UAAU,SAAS,WAAW,EAAE,EAChC,UAAU,YAAY,KACrB,YAgBF,CAAC;AAEF,uEAAuE;AACvE,eAAO,MAAM,eAAe,QAA2B,CAAC;AAExD,wEAAwE;AACxE,eAAO,MAAM,cAAc,GAAI,UAAU,YAAY,KAAG,MAAM,EAGtB,CAAC;AAEzC,8EAA8E;AAC9E,eAAO,MAAM,eAAe,GAAI,QAAQ,MAAM,EAAE,SAAS,WAAW,WAUtD,CAAC"}
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The screen-level accessibility ratchet, as data: what axe found on one
3
+ * screen, reduced to fingerprints that survive a re-render, compared with what
4
+ * a committed baseline already accepts.
5
+ *
6
+ * A baseline maps each accepted fingerprint to the issue that removes it, so a
7
+ * host can switch the gate on with a backlog and the backlog can only shrink:
8
+ * a new serious or critical fingerprint fails, and so does an accepted one
9
+ * that is no longer there, which is how a fix is made to delete its entry.
10
+ */ /** axe's impact levels, least to most severe. */ import { _ as _extends } from "@swc/helpers/_/_extends";
11
+ /**
12
+ * The key a baseline records its fingerprint scheme under. Every other key is
13
+ * a fingerprint; this one is not, and no rule here treats it as one.
14
+ */ export const FINGERPRINT_KEY = '$fingerprints';
15
+ /**
16
+ * The scheme {@link findingsOf} computes today. It changes only when the
17
+ * fingerprint does, and a baseline recorded under another scheme is a
18
+ * re-keying rather than new debt: CI then holds it to "no more entries than
19
+ * before" instead of "no new keys", which a rename of every key would fail.
20
+ */ export const FINGERPRINT_SCHEME = 'ancestry-1';
21
+ /** A baseline's fingerprint entries, without the scheme marker. */ export const baselineEntries = (baseline)=>Object.entries(baseline).filter(([key])=>key !== FINGERPRINT_KEY);
22
+ /** The levels that fail the gate (ADR 0024). */ export const GATED = new Set([
23
+ 'serious',
24
+ 'critical'
25
+ ]);
26
+ /** The rule tags the gate runs: WCAG 2.2 AA, with 2.1's A level. */ export const WCAG_22_AA_TAGS = [
27
+ 'wcag2a',
28
+ 'wcag2aa',
29
+ 'wcag21a',
30
+ 'wcag21aa',
31
+ 'wcag22aa'
32
+ ];
33
+ /**
34
+ * Ids a framework mints per render: React's `useId` (`:r1:`, `«r1»`, and their
35
+ * CSS-escaped forms), Headless UI's `headlessui-<part>-<n>` and Radix's
36
+ * `radix-…`. Each is written `#generated-id`: the node is still there, its name is not.
37
+ */ const GENERATED_ID = /#(?:headlessui-[\w-]+|(?:\\:|:|«)r[\w]+(?:\\:|:|»)[\w-]*|radix-[\w:-]+)/g;
38
+ /**
39
+ * Splits `text` wherever `isBoundary` says a new token starts, ignoring
40
+ * anything inside brackets, parentheses or quotes and any escaped character —
41
+ * `[title="Open in a new tab"]` and Tailwind's `.bg-surface\/60` are one
42
+ * token each.
43
+ */ const tokenize = (text, isBoundary)=>{
44
+ const tokens = [];
45
+ let current = '';
46
+ let depth = 0;
47
+ let quote = '';
48
+ for(let at = 0; at < text.length; at += 1){
49
+ const char = text[at];
50
+ if (char === '\\') {
51
+ var _text_;
52
+ current += char + ((_text_ = text[at + 1]) != null ? _text_ : '');
53
+ at += 1;
54
+ continue;
55
+ }
56
+ if (quote === '' && depth === 0 && current !== '' && isBoundary(char, current.at(-1))) {
57
+ tokens.push(current);
58
+ current = '';
59
+ }
60
+ if (quote !== '') {
61
+ if (char === quote) quote = '';
62
+ } else if (char === '"' || char === "'") {
63
+ quote = char;
64
+ } else if (char === '[' || char === '(') {
65
+ depth += 1;
66
+ } else if (char === ']' || char === ')') {
67
+ depth -= 1;
68
+ }
69
+ current += char;
70
+ }
71
+ tokens.push(current);
72
+ return tokens;
73
+ };
74
+ const RANK = {
75
+ '#': 1,
76
+ '.': 2,
77
+ '[': 3,
78
+ ':': 4
79
+ };
80
+ /**
81
+ * One compound selector with its ids, classes and attributes in a fixed
82
+ * order. Pseudo-classes keep theirs: `:hover:not(…)` reads differently from
83
+ * `:not(…):hover` even where the engine treats them alike.
84
+ */ const canonicalCompound = (compound)=>tokenize(compound, (char, previous)=>char in RANK && previous !== ':').map((part)=>{
85
+ var _RANK_part_;
86
+ return {
87
+ part,
88
+ rank: (_RANK_part_ = RANK[part[0]]) != null ? _RANK_part_ : 0
89
+ };
90
+ }).sort((a, b)=>a.rank - b.rank || (a.rank === 4 ? 0 : a.part.localeCompare(b.part))).map(({ part })=>part).join('');
91
+ /** A complex selector, one canonical compound at a time. */ const canonicalSelector = (selector)=>tokenize(selector.trim(), (char)=>/[\s>+~]/.test(char)).map((token)=>token.trim()).filter((token)=>token !== '').map((token)=>/^[>+~]$/.test(token) ? token : canonicalCompound(token)).join(' ');
92
+ /**
93
+ * A selector stable across renders and across axe's own choices: generated ids
94
+ * written `#generated-id`; every `:nth-child(k)` and `:nth-of-type(k)` written
95
+ * with `n`, so a run of identical siblings is one fingerprint rather than one
96
+ * per row; and each compound's classes and attributes sorted, because axe
97
+ * orders them by how unique they happen to be on the page at the time.
98
+ */ export const normalizeTarget = (target)=>target.flatMap((part)=>Array.isArray(part) ? part : [
99
+ part
100
+ ]).map((part)=>canonicalSelector(String(part).replace(GENERATED_ID, '#generated-id').replace(/:nth-child\(\d+\)/g, ':nth-child(n)').replace(/:nth-of-type\(\d+\)/g, ':nth-of-type(n)'))).join(' >>> ');
101
+ /** `rule|target|screen`: the identity of one failing node. */ export const fingerprintOf = (rule, target, screen)=>`${rule}|${target}|${screen}`;
102
+ /** The screen a fingerprint belongs to. */ export const screenOf = (fingerprint)=>fingerprint.slice(fingerprint.lastIndexOf('|') + 1);
103
+ /** Every distinct fingerprint in `violations`, at its rule's impact. */ export const findingsOf = (screen, violations)=>{
104
+ const found = new Map();
105
+ for (const violation of violations){
106
+ for (const node of violation.nodes){
107
+ var _node_ancestry, _violation_impact, _violation_help;
108
+ const fingerprint = fingerprintOf(violation.id, normalizeTarget((_node_ancestry = node.ancestry) != null ? _node_ancestry : node.target), screen);
109
+ found.set(fingerprint, {
110
+ fingerprint,
111
+ impact: (_violation_impact = violation.impact) != null ? _violation_impact : 'minor',
112
+ help: (_violation_help = violation.help) != null ? _violation_help : violation.id
113
+ });
114
+ }
115
+ }
116
+ return [
117
+ ...found.values()
118
+ ].sort((a, b)=>a.fingerprint.localeCompare(b.fingerprint));
119
+ };
120
+ /** Judges one screen's findings against the baseline. */ export const compareWithBaseline = (screen, findings, baseline)=>{
121
+ const gated = findings.filter((finding)=>GATED.has(finding.impact));
122
+ const present = new Set(gated.map((finding)=>finding.fingerprint));
123
+ return {
124
+ added: gated.filter((finding)=>!(finding.fingerprint in baseline)),
125
+ stale: baselineEntries(baseline).map(([fingerprint])=>fingerprint).filter((fingerprint)=>screenOf(fingerprint) === screen).filter((fingerprint)=>!present.has(fingerprint)).sort(),
126
+ reported: findings.filter((finding)=>!GATED.has(finding.impact))
127
+ };
128
+ };
129
+ /**
130
+ * The baseline with this screen's entries replaced by what was found: owners
131
+ * kept for fingerprints still present, and an empty owner for a new one, which
132
+ * {@link unownedEntries} refuses until a person names its issue.
133
+ */ export const updateBaseline = (screen, findings, baseline)=>{
134
+ const next = {};
135
+ for (const [fingerprint, owner] of baselineEntries(baseline)){
136
+ if (screenOf(fingerprint) !== screen) next[fingerprint] = owner;
137
+ }
138
+ for (const finding of findings){
139
+ if (GATED.has(finding.impact)) {
140
+ var _baseline_finding_fingerprint;
141
+ next[finding.fingerprint] = (_baseline_finding_fingerprint = baseline[finding.fingerprint]) != null ? _baseline_finding_fingerprint : '';
142
+ }
143
+ }
144
+ return _extends({
145
+ [FINGERPRINT_KEY]: FINGERPRINT_SCHEME
146
+ }, Object.fromEntries(Object.entries(next).sort(([a], [b])=>a.localeCompare(b))));
147
+ };
148
+ /** An issue reference in the form GitHub links across repositories. */ export const ISSUE_REFERENCE = /^[\w.-]+\/[\w.-]+#\d+$/;
149
+ /** Every entry whose owner is not an `owner/repo#N` issue reference. */ export const unownedEntries = (baseline)=>baselineEntries(baseline).filter(([, owner])=>!ISSUE_REFERENCE.test(owner)).map(([fingerprint])=>fingerprint);
150
+ /** A failure message that names every fingerprint and what to do about it. */ export const describeVerdict = (screen, verdict)=>[
151
+ ...verdict.added.map((finding)=>`${screen}: new ${finding.impact} violation ${finding.fingerprint} — ${finding.help}`),
152
+ ...verdict.stale.map((fingerprint)=>`${screen}: ${fingerprint} is in the baseline but no longer found — delete its entry`)
153
+ ].join('\n');
154
+
155
+ //# sourceMappingURL=baseline.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/a11y/baseline.ts"],"sourcesContent":["/**\n * The screen-level accessibility ratchet, as data: what axe found on one\n * screen, reduced to fingerprints that survive a re-render, compared with what\n * a committed baseline already accepts.\n *\n * A baseline maps each accepted fingerprint to the issue that removes it, so a\n * host can switch the gate on with a backlog and the backlog can only shrink:\n * a new serious or critical fingerprint fails, and so does an accepted one\n * that is no longer there, which is how a fix is made to delete its entry.\n */\n\n/** axe's impact levels, least to most severe. */\nexport type A11yImpact = 'minor' | 'moderate' | 'serious' | 'critical';\n\n/** The part of an axe node this module reads. */\nexport interface A11yNodeResult {\n readonly target: readonly unknown[];\n /**\n * The node's full `tag:nth-child` path, present when axe ran with\n * `ancestry: true`. Preferred over `target`: axe builds a target as the\n * shortest selector unique on the page at that moment, so a hidden copy of\n * the previous page (a router's `<Activity>`) turns `.gallery` into a long\n * path on one run and back on the next.\n */\n readonly ancestry?: readonly unknown[];\n}\n\n/** The part of an axe violation this module reads. */\nexport interface A11yViolation {\n readonly id: string;\n readonly impact?: A11yImpact | null;\n readonly help?: string;\n readonly nodes: readonly A11yNodeResult[];\n}\n\n/** One fingerprint found on a screen, with the severity it was found at. */\nexport interface A11yFinding {\n readonly fingerprint: string;\n readonly impact: A11yImpact;\n readonly help: string;\n}\n\n/**\n * Accepted fingerprints, each against the issue that removes it, plus the\n * {@link FINGERPRINT_KEY} naming the scheme they were computed with.\n */\nexport type A11yBaseline = Readonly<Record<string, string>>;\n\n/**\n * The key a baseline records its fingerprint scheme under. Every other key is\n * a fingerprint; this one is not, and no rule here treats it as one.\n */\nexport const FINGERPRINT_KEY = '$fingerprints';\n\n/**\n * The scheme {@link findingsOf} computes today. It changes only when the\n * fingerprint does, and a baseline recorded under another scheme is a\n * re-keying rather than new debt: CI then holds it to \"no more entries than\n * before\" instead of \"no new keys\", which a rename of every key would fail.\n */\nexport const FINGERPRINT_SCHEME = 'ancestry-1';\n\n/** A baseline's fingerprint entries, without the scheme marker. */\nexport const baselineEntries = (baseline: A11yBaseline): [string, string][] =>\n Object.entries(baseline).filter(([key]) => key !== FINGERPRINT_KEY);\n\n/** What a gate run decides for one screen. */\nexport interface A11yVerdict {\n /** Serious or critical, and not in the baseline: these fail. */\n readonly added: readonly A11yFinding[];\n /** In the baseline for this screen, and no longer found: these fail too. */\n readonly stale: readonly string[];\n /** Moderate or minor: reported, never failing. */\n readonly reported: readonly A11yFinding[];\n}\n\n/** The levels that fail the gate (ADR 0024). */\nexport const GATED: ReadonlySet<A11yImpact> = new Set(['serious', 'critical']);\n\n/** The rule tags the gate runs: WCAG 2.2 AA, with 2.1's A level. */\nexport const WCAG_22_AA_TAGS = [\n 'wcag2a',\n 'wcag2aa',\n 'wcag21a',\n 'wcag21aa',\n 'wcag22aa',\n] as const;\n\n/**\n * Ids a framework mints per render: React's `useId` (`:r1:`, `«r1»`, and their\n * CSS-escaped forms), Headless UI's `headlessui-<part>-<n>` and Radix's\n * `radix-…`. Each is written `#generated-id`: the node is still there, its name is not.\n */\nconst GENERATED_ID =\n /#(?:headlessui-[\\w-]+|(?:\\\\:|:|«)r[\\w]+(?:\\\\:|:|»)[\\w-]*|radix-[\\w:-]+)/g;\n\n/**\n * Splits `text` wherever `isBoundary` says a new token starts, ignoring\n * anything inside brackets, parentheses or quotes and any escaped character —\n * `[title=\"Open in a new tab\"]` and Tailwind's `.bg-surface\\/60` are one\n * token each.\n */\nconst tokenize = (\n text: string,\n isBoundary: (char: string, previous: string) => boolean,\n): string[] => {\n const tokens: string[] = [];\n let current = '';\n let depth = 0;\n let quote = '';\n for (let at = 0; at < text.length; at += 1) {\n const char = text[at] as string;\n if (char === '\\\\') {\n current += char + (text[at + 1] ?? '');\n at += 1;\n continue;\n }\n if (\n quote === '' &&\n depth === 0 &&\n current !== '' &&\n isBoundary(char, current.at(-1) as string)\n ) {\n tokens.push(current);\n current = '';\n }\n if (quote !== '') {\n if (char === quote) quote = '';\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === '[' || char === '(') {\n depth += 1;\n } else if (char === ']' || char === ')') {\n depth -= 1;\n }\n current += char;\n }\n tokens.push(current);\n return tokens;\n};\n\nconst RANK: Readonly<Record<string, number>> = {\n '#': 1,\n '.': 2,\n '[': 3,\n ':': 4,\n};\n\n/**\n * One compound selector with its ids, classes and attributes in a fixed\n * order. Pseudo-classes keep theirs: `:hover:not(…)` reads differently from\n * `:not(…):hover` even where the engine treats them alike.\n */\nconst canonicalCompound = (compound: string): string =>\n tokenize(compound, (char, previous) => char in RANK && previous !== ':')\n .map(part => ({ part, rank: RANK[part[0] as string] ?? 0 }))\n .sort(\n (a, b) =>\n a.rank - b.rank || (a.rank === 4 ? 0 : a.part.localeCompare(b.part)),\n )\n .map(({ part }) => part)\n .join('');\n\n/** A complex selector, one canonical compound at a time. */\nconst canonicalSelector = (selector: string): string =>\n tokenize(selector.trim(), char => /[\\s>+~]/.test(char))\n .map(token => token.trim())\n .filter(token => token !== '')\n .map(token => (/^[>+~]$/.test(token) ? token : canonicalCompound(token)))\n .join(' ');\n\n/**\n * A selector stable across renders and across axe's own choices: generated ids\n * written `#generated-id`; every `:nth-child(k)` and `:nth-of-type(k)` written\n * with `n`, so a run of identical siblings is one fingerprint rather than one\n * per row; and each compound's classes and attributes sorted, because axe\n * orders them by how unique they happen to be on the page at the time.\n */\nexport const normalizeTarget = (target: readonly unknown[]): string =>\n target\n .flatMap(part => (Array.isArray(part) ? part : [part]))\n .map(part =>\n canonicalSelector(\n String(part)\n .replace(GENERATED_ID, '#generated-id')\n .replace(/:nth-child\\(\\d+\\)/g, ':nth-child(n)')\n .replace(/:nth-of-type\\(\\d+\\)/g, ':nth-of-type(n)'),\n ),\n )\n .join(' >>> ');\n\n/** `rule|target|screen`: the identity of one failing node. */\nexport const fingerprintOf = (rule: string, target: string, screen: string) =>\n `${rule}|${target}|${screen}`;\n\n/** The screen a fingerprint belongs to. */\nexport const screenOf = (fingerprint: string) =>\n fingerprint.slice(fingerprint.lastIndexOf('|') + 1);\n\n/** Every distinct fingerprint in `violations`, at its rule's impact. */\nexport const findingsOf = (\n screen: string,\n violations: readonly A11yViolation[],\n): A11yFinding[] => {\n const found = new Map<string, A11yFinding>();\n for (const violation of violations) {\n for (const node of violation.nodes) {\n const fingerprint = fingerprintOf(\n violation.id,\n normalizeTarget(node.ancestry ?? node.target),\n screen,\n );\n found.set(fingerprint, {\n fingerprint,\n impact: violation.impact ?? 'minor',\n help: violation.help ?? violation.id,\n });\n }\n }\n return [...found.values()].sort((a, b) =>\n a.fingerprint.localeCompare(b.fingerprint),\n );\n};\n\n/** Judges one screen's findings against the baseline. */\nexport const compareWithBaseline = (\n screen: string,\n findings: readonly A11yFinding[],\n baseline: A11yBaseline,\n): A11yVerdict => {\n const gated = findings.filter(finding => GATED.has(finding.impact));\n const present = new Set(gated.map(finding => finding.fingerprint));\n return {\n added: gated.filter(finding => !(finding.fingerprint in baseline)),\n stale: baselineEntries(baseline)\n .map(([fingerprint]) => fingerprint)\n .filter(fingerprint => screenOf(fingerprint) === screen)\n .filter(fingerprint => !present.has(fingerprint))\n .sort(),\n reported: findings.filter(finding => !GATED.has(finding.impact)),\n };\n};\n\n/**\n * The baseline with this screen's entries replaced by what was found: owners\n * kept for fingerprints still present, and an empty owner for a new one, which\n * {@link unownedEntries} refuses until a person names its issue.\n */\nexport const updateBaseline = (\n screen: string,\n findings: readonly A11yFinding[],\n baseline: A11yBaseline,\n): A11yBaseline => {\n const next: Record<string, string> = {};\n for (const [fingerprint, owner] of baselineEntries(baseline)) {\n if (screenOf(fingerprint) !== screen) next[fingerprint] = owner;\n }\n for (const finding of findings) {\n if (GATED.has(finding.impact)) {\n next[finding.fingerprint] = baseline[finding.fingerprint] ?? '';\n }\n }\n return {\n [FINGERPRINT_KEY]: FINGERPRINT_SCHEME,\n ...Object.fromEntries(\n Object.entries(next).sort(([a], [b]) => a.localeCompare(b)),\n ),\n };\n};\n\n/** An issue reference in the form GitHub links across repositories. */\nexport const ISSUE_REFERENCE = /^[\\w.-]+\\/[\\w.-]+#\\d+$/;\n\n/** Every entry whose owner is not an `owner/repo#N` issue reference. */\nexport const unownedEntries = (baseline: A11yBaseline): string[] =>\n baselineEntries(baseline)\n .filter(([, owner]) => !ISSUE_REFERENCE.test(owner))\n .map(([fingerprint]) => fingerprint);\n\n/** A failure message that names every fingerprint and what to do about it. */\nexport const describeVerdict = (screen: string, verdict: A11yVerdict) =>\n [\n ...verdict.added.map(\n finding =>\n `${screen}: new ${finding.impact} violation ${finding.fingerprint} — ${finding.help}`,\n ),\n ...verdict.stale.map(\n fingerprint =>\n `${screen}: ${fingerprint} is in the baseline but no longer found — delete its entry`,\n ),\n ].join('\\n');\n"],"names":["FINGERPRINT_KEY","FINGERPRINT_SCHEME","baselineEntries","baseline","Object","entries","filter","key","GATED","Set","WCAG_22_AA_TAGS","GENERATED_ID","tokenize","text","isBoundary","tokens","current","depth","quote","at","length","char","push","RANK","canonicalCompound","compound","previous","map","part","rank","sort","a","b","localeCompare","join","canonicalSelector","selector","trim","test","token","normalizeTarget","target","flatMap","Array","isArray","String","replace","fingerprintOf","rule","screen","screenOf","fingerprint","slice","lastIndexOf","findingsOf","violations","found","Map","violation","node","nodes","id","ancestry","set","impact","help","values","compareWithBaseline","findings","gated","finding","has","present","added","stale","reported","updateBaseline","next","owner","fromEntries","ISSUE_REFERENCE","unownedEntries","describeVerdict","verdict"],"mappings":"AAAA;;;;;;;;;CASC,GAED,+CAA+C;AAqC/C;;;CAGC,GACD,OAAO,MAAMA,kBAAkB,gBAAgB;AAE/C;;;;;CAKC,GACD,OAAO,MAAMC,qBAAqB,aAAa;AAE/C,iEAAiE,GACjE,OAAO,MAAMC,kBAAkB,CAACC,WAC9BC,OA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,CAClBwB,CAAAA,cACE,GAAGF,OAAO,EAAE,EAAEE,YAAY,0DAA0D,CAAC;KAE1F,CAACjB,IAAI,CAAC,MAAM"}
@@ -0,0 +1,5 @@
1
+ export * from './axe.js';
2
+ export * from './baseline.js';
3
+ export * from './keyboard.js';
4
+ export * from './walk.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/a11y/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,6 @@
1
+ export * from './axe.js';
2
+ export * from './baseline.js';
3
+ export * from './keyboard.js';
4
+ export * from './walk.js';
5
+
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/a11y/index.ts"],"sourcesContent":["export * from './axe.js';\nexport * from './baseline.js';\nexport * from './keyboard.js';\nexport * from './walk.js';\n"],"names":[],"mappings":"AAAA,cAAc,WAAW;AACzB,cAAc,gBAAgB;AAC9B,cAAc,gBAAgB;AAC9B,cAAc,YAAY"}
@@ -0,0 +1,29 @@
1
+ import { type Page } from '@playwright/test';
2
+ import { type WalkExpectations } from './walk.js';
3
+ export interface WalkOptions extends Partial<WalkExpectations> {
4
+ /** How many Tab presses to make before giving up on reaching the end. */
5
+ readonly maxStops?: number;
6
+ }
7
+ /**
8
+ * Tabs through the page from the top and fails on what a keyboard user would
9
+ * hit (ADR 0024): no skip link first when `skipLink` is set, the first stop
10
+ * inside `main` past `mainIndexMax`, a stop with no visible indicator, a stop
11
+ * something else covers, and a stop that jumps back more than a row in its
12
+ * column.
13
+ */
14
+ export declare function walkKeyboard(page: Page, { maxStops, skipLink, mainIndexMax }?: WalkOptions): Promise<void>;
15
+ export interface FocusKeptOptions {
16
+ /**
17
+ * The issue that stops this write dropping focus, while it still does. The
18
+ * check then expects focus on `<body>` and fails once it is not, so the fix
19
+ * has to delete the option — the same ratchet as an axe baseline entry.
20
+ */
21
+ readonly lostUntil?: string;
22
+ }
23
+ /**
24
+ * After a write — a save, a delete, a submitted step — focus must land on
25
+ * something, not fall back to the document, where a screen reader loses its
26
+ * place and the next Tab starts from the top (2.4.3).
27
+ */
28
+ export declare function expectFocusKept(page: Page, { lostUntil }?: FocusKeptOptions): Promise<void>;
29
+ //# sourceMappingURL=keyboard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyboard.d.ts","sourceRoot":"","sources":["../../src/a11y/keyboard.ts"],"names":[],"mappings":"AAGA,OAAO,EAAU,KAAK,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAGrD,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,WAAW,CAAC;AAEnB,MAAM,WAAW,WAAY,SAAQ,OAAO,CAAC,gBAAgB,CAAC;IAC5D,yEAAyE;IACzE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAmJD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,IAAI,EAAE,IAAI,EACV,EAAE,QAAc,EAAE,QAAe,EAAE,YAAgB,EAAE,GAAE,WAAgB,GACtE,OAAO,CAAC,IAAI,CAAC,CAcf;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,IAAI,EACV,EAAE,SAAS,EAAE,GAAE,gBAAqB,GACnC,OAAO,CAAC,IAAI,CAAC,CAef"}
@@ -0,0 +1,186 @@
1
+ // `readStop` and the blur helpers are serialized by `page.evaluate` and run in
2
+ // the browser, so this file is checked against the DOM's types as well.
3
+ /// <reference lib="dom" />
4
+ import { expect } from '@playwright/test';
5
+ import { settled } from './settle.js';
6
+ import { assessWalk } from './walk.js';
7
+ /** Reads the focused element in the page. Runs in the browser. */ const readStop = ()=>{
8
+ var _ref, _element_getAttribute;
9
+ var _element_textContent;
10
+ const element = document.activeElement;
11
+ if (element === null || element === document.body) return null;
12
+ const rect = element.getBoundingClientRect();
13
+ const style = getComputedStyle(element);
14
+ // Where the stop sits in the content it scrolls with, not in the viewport:
15
+ // focusing a stop scrolls its container, so viewport positions taken at
16
+ // different stops are not comparable — a sidebar link further down read as
17
+ // a row *above* the one before it once the sidebar had scrolled. The nearest
18
+ // scrolling ancestor names the content, and the position is taken inside it.
19
+ let scroller = element.parentElement;
20
+ while(scroller !== null && scroller !== document.body && !(/auto|scroll/.test(getComputedStyle(scroller).overflowY) && scroller.scrollHeight > scroller.clientHeight)){
21
+ scroller = scroller.parentElement;
22
+ }
23
+ if (scroller === document.body) scroller = null;
24
+ const origin = scroller === null ? {
25
+ x: -window.scrollX,
26
+ y: -window.scrollY
27
+ } : (()=>{
28
+ const box = scroller.getBoundingClientRect();
29
+ return {
30
+ x: box.x - scroller.scrollLeft,
31
+ y: box.y - scroller.scrollTop
32
+ };
33
+ })();
34
+ const path = (node)=>{
35
+ var _ref;
36
+ var _node_parentElement;
37
+ return node === null ? 'document' : `${path(node.parentElement === document.documentElement ? null : node.parentElement)} > ${node.tagName.toLowerCase()}:${[
38
+ ...(_ref = (_node_parentElement = node.parentElement) == null ? void 0 : _node_parentElement.children) != null ? _ref : []
39
+ ].indexOf(node)}`;
40
+ };
41
+ const outline = style.outlineStyle !== 'none' && parseFloat(style.outlineWidth) > 0;
42
+ const ring = style.boxShadow !== 'none' && style.boxShadow !== '';
43
+ // WCAG 2.4.11 (AA) fails a focused control only when it is entirely hidden,
44
+ // so the stop is covered when no sampled point of it — the centre and four
45
+ // points just inside its corners — shows the element itself.
46
+ const inset = Math.min(2, rect.width / 2, rect.height / 2);
47
+ const points = [
48
+ [
49
+ rect.x + rect.width / 2,
50
+ rect.y + rect.height / 2
51
+ ],
52
+ [
53
+ rect.x + inset,
54
+ rect.y + inset
55
+ ],
56
+ [
57
+ rect.x + rect.width - inset,
58
+ rect.y + inset
59
+ ],
60
+ [
61
+ rect.x + inset,
62
+ rect.y + rect.height - inset
63
+ ],
64
+ [
65
+ rect.x + rect.width - inset,
66
+ rect.y + rect.height - inset
67
+ ]
68
+ ];
69
+ const obscured = rect.width > 0 && rect.height > 0 && points.every(([x, y])=>{
70
+ const hit = document.elementFromPoint(x, y);
71
+ return hit === null || !element.contains(hit) && !hit.contains(element);
72
+ });
73
+ // The visible `main`, and the visible element an in-page link names: a
74
+ // router that keeps the previous page mounted but hidden (React's
75
+ // `<Activity>`) leaves two of each in the document, and the first in
76
+ // document order may be the hidden one.
77
+ const visible = (candidates)=>{
78
+ var _find;
79
+ return (_find = [
80
+ ...candidates
81
+ ].find((candidate)=>candidate.checkVisibility())) != null ? _find : null;
82
+ };
83
+ const href = element.getAttribute('href');
84
+ const target = (href == null ? void 0 : href.startsWith('#')) && href.length > 1 ? visible(document.querySelectorAll(`[id="${CSS.escape(href.slice(1))}"]`)) : null;
85
+ const main = visible(document.querySelectorAll('main'));
86
+ const isSkipLink = element.tagName === 'A' && target !== null && main !== null && (target === main || main.contains(target));
87
+ const name = (_ref = (_element_getAttribute = element.getAttribute('aria-label')) != null ? _element_getAttribute : (_element_textContent = element.textContent) == null ? void 0 : _element_textContent.trim().slice(0, 40)) != null ? _ref : '';
88
+ const role = element.getAttribute('role');
89
+ return {
90
+ label: `${element.tagName.toLowerCase()}${role ? `[role=${role}]` : ''} "${name}"`,
91
+ rect: {
92
+ x: rect.x - origin.x,
93
+ y: rect.y - origin.y,
94
+ width: rect.width,
95
+ height: rect.height
96
+ },
97
+ container: path(scroller),
98
+ inMain: main !== null && main.contains(element),
99
+ isSkipLink,
100
+ indicatorVisible: outline || ring,
101
+ obscured
102
+ };
103
+ };
104
+ /** The id of the walk's starting point, so it can be removed afterwards. */ const WALK_START = 'entifix-a11y-walk-start';
105
+ /**
106
+ * Puts the browser's sequential focus starting point at the top of the
107
+ * document. Blurring is not enough: after a form posts and redirects, or a
108
+ * control was clicked, the next Tab starts from where that happened, and a
109
+ * walk from there skipped the whole header — or found nothing. A script-only
110
+ * focusable element first in `<body>` is focused instead; `tabIndex = -1`
111
+ * keeps it out of the walk itself.
112
+ */ const fromTheTop = (page)=>page.evaluate((id)=>{
113
+ window.scrollTo(0, 0);
114
+ let start = document.getElementById(id);
115
+ if (start === null) {
116
+ start = document.createElement('span');
117
+ start.id = id;
118
+ start.tabIndex = -1;
119
+ document.body.prepend(start);
120
+ }
121
+ start.focus({
122
+ preventScroll: true
123
+ });
124
+ }, WALK_START);
125
+ const tabThrough = async (page, maxStops)=>{
126
+ const stops = [];
127
+ let first;
128
+ for(let pressed = 0; pressed < maxStops; pressed += 1){
129
+ await page.keyboard.press('Tab');
130
+ await settled(page);
131
+ const stop = await page.evaluate(readStop);
132
+ if (stop === null) break;
133
+ const identity = `${stop.label}@${stop.rect.x},${stop.rect.y}`;
134
+ // Focus wrapped back to where it started: the walk is complete.
135
+ if (identity === first) break;
136
+ first != null ? first : first = identity;
137
+ stops.push(stop);
138
+ }
139
+ return stops;
140
+ };
141
+ /**
142
+ * Tabs through the page from the top and fails on what a keyboard user would
143
+ * hit (ADR 0024): no skip link first when `skipLink` is set, the first stop
144
+ * inside `main` past `mainIndexMax`, a stop with no visible indicator, a stop
145
+ * something else covers, and a stop that jumps back more than a row in its
146
+ * column.
147
+ */ export async function walkKeyboard(page, { maxStops = 120, skipLink = true, mainIndexMax = 3 } = {}) {
148
+ var _stops_;
149
+ await fromTheTop(page);
150
+ const stops = await tabThrough(page, maxStops);
151
+ let walk = {
152
+ stops
153
+ };
154
+ if (skipLink && ((_stops_ = stops[0]) == null ? void 0 : _stops_.isSkipLink) === true) {
155
+ await fromTheTop(page);
156
+ await page.keyboard.press('Tab');
157
+ await page.keyboard.press('Enter');
158
+ walk = {
159
+ stops,
160
+ afterSkip: await tabThrough(page, maxStops)
161
+ };
162
+ }
163
+ await page.evaluate((id)=>{
164
+ var _document_getElementById;
165
+ return (_document_getElementById = document.getElementById(id)) == null ? void 0 : _document_getElementById.remove();
166
+ }, WALK_START);
167
+ expect(assessWalk(walk, {
168
+ skipLink,
169
+ mainIndexMax
170
+ })).toEqual([]);
171
+ }
172
+ /**
173
+ * After a write — a save, a delete, a submitted step — focus must land on
174
+ * something, not fall back to the document, where a screen reader loses its
175
+ * place and the next Tab starts from the top (2.4.3).
176
+ */ export async function expectFocusKept(page, { lostUntil } = {}) {
177
+ await settled(page);
178
+ const kept = await page.evaluate(()=>document.activeElement !== null && document.activeElement !== document.body);
179
+ if (lostUntil === undefined) {
180
+ expect(kept, 'focus fell back to <body> after the write').toBe(true);
181
+ } else {
182
+ expect(kept, `focus is kept after this write now: delete the lostUntil for ${lostUntil}`).toBe(false);
183
+ }
184
+ }
185
+
186
+ //# sourceMappingURL=keyboard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/a11y/keyboard.ts"],"sourcesContent":["// `readStop` and the blur helpers are serialized by `page.evaluate` and run in\n// the browser, so this file is checked against the DOM's types as well.\n/// <reference lib=\"dom\" />\nimport { expect, type Page } from '@playwright/test';\n\nimport { settled } from './settle.js';\nimport {\n assessWalk,\n type FocusStop,\n type FocusWalk,\n type WalkExpectations,\n} from './walk.js';\n\nexport interface WalkOptions extends Partial<WalkExpectations> {\n /** How many Tab presses to make before giving up on reaching the end. */\n readonly maxStops?: number;\n}\n\n/** Reads the focused element in the page. Runs in the browser. */\nconst readStop = (): FocusStop | null => {\n const element = document.activeElement as HTMLElement | null;\n if (element === null || element === document.body) return null;\n\n const rect = element.getBoundingClientRect();\n const style = getComputedStyle(element);\n\n // Where the stop sits in the content it scrolls with, not in the viewport:\n // focusing a stop scrolls its container, so viewport positions taken at\n // different stops are not comparable — a sidebar link further down read as\n // a row *above* the one before it once the sidebar had scrolled. The nearest\n // scrolling ancestor names the content, and the position is taken inside it.\n let scroller: HTMLElement | null = element.parentElement;\n while (\n scroller !== null &&\n scroller !== document.body &&\n !(\n /auto|scroll/.test(getComputedStyle(scroller).overflowY) &&\n scroller.scrollHeight > scroller.clientHeight\n )\n ) {\n scroller = scroller.parentElement;\n }\n if (scroller === document.body) scroller = null;\n const origin =\n scroller === null\n ? { x: -window.scrollX, y: -window.scrollY }\n : (() => {\n const box = scroller.getBoundingClientRect();\n return {\n x: box.x - scroller.scrollLeft,\n y: box.y - scroller.scrollTop,\n };\n })();\n const path = (node: Element | null): string =>\n node === null\n ? 'document'\n : `${path(node.parentElement === document.documentElement ? null : node.parentElement)} > ${node.tagName.toLowerCase()}:${[...(node.parentElement?.children ?? [])].indexOf(node)}`;\n\n const outline =\n style.outlineStyle !== 'none' && parseFloat(style.outlineWidth) > 0;\n const ring = style.boxShadow !== 'none' && style.boxShadow !== '';\n\n // WCAG 2.4.11 (AA) fails a focused control only when it is entirely hidden,\n // so the stop is covered when no sampled point of it — the centre and four\n // points just inside its corners — shows the element itself.\n const inset = Math.min(2, rect.width / 2, rect.height / 2);\n const points = [\n [rect.x + rect.width / 2, rect.y + rect.height / 2],\n [rect.x + inset, rect.y + inset],\n [rect.x + rect.width - inset, rect.y + inset],\n [rect.x + inset, rect.y + rect.height - inset],\n [rect.x + rect.width - inset, rect.y + rect.height - inset],\n ] as const;\n const obscured =\n rect.width > 0 &&\n rect.height > 0 &&\n points.every(([x, y]) => {\n const hit = document.elementFromPoint(x, y);\n return hit === null || (!element.contains(hit) && !hit.contains(element));\n });\n\n // The visible `main`, and the visible element an in-page link names: a\n // router that keeps the previous page mounted but hidden (React's\n // `<Activity>`) leaves two of each in the document, and the first in\n // document order may be the hidden one.\n const visible = (candidates: Iterable<Element>) =>\n [...candidates].find(candidate => candidate.checkVisibility()) ?? null;\n const href = element.getAttribute('href');\n const target =\n href?.startsWith('#') && href.length > 1\n ? visible(\n document.querySelectorAll(`[id=\"${CSS.escape(href.slice(1))}\"]`),\n )\n : null;\n const main = visible(document.querySelectorAll('main'));\n const isSkipLink =\n element.tagName === 'A' &&\n target !== null &&\n main !== null &&\n (target === main || main.contains(target));\n\n const name =\n element.getAttribute('aria-label') ??\n element.textContent?.trim().slice(0, 40) ??\n '';\n const role = element.getAttribute('role');\n return {\n label: `${element.tagName.toLowerCase()}${role ? `[role=${role}]` : ''} \"${name}\"`,\n rect: {\n x: rect.x - origin.x,\n y: rect.y - origin.y,\n width: rect.width,\n height: rect.height,\n },\n container: path(scroller),\n inMain: main !== null && main.contains(element),\n isSkipLink,\n indicatorVisible: outline || ring,\n obscured,\n };\n};\n\n/** The id of the walk's starting point, so it can be removed afterwards. */\nconst WALK_START = 'entifix-a11y-walk-start';\n\n/**\n * Puts the browser's sequential focus starting point at the top of the\n * document. Blurring is not enough: after a form posts and redirects, or a\n * control was clicked, the next Tab starts from where that happened, and a\n * walk from there skipped the whole header — or found nothing. A script-only\n * focusable element first in `<body>` is focused instead; `tabIndex = -1`\n * keeps it out of the walk itself.\n */\nconst fromTheTop = (page: Page) =>\n page.evaluate(id => {\n window.scrollTo(0, 0);\n let start = document.getElementById(id);\n if (start === null) {\n start = document.createElement('span');\n start.id = id;\n start.tabIndex = -1;\n document.body.prepend(start);\n }\n start.focus({ preventScroll: true });\n }, WALK_START);\n\nconst tabThrough = async (page: Page, maxStops: number) => {\n const stops: FocusStop[] = [];\n let first: string | undefined;\n for (let pressed = 0; pressed < maxStops; pressed += 1) {\n await page.keyboard.press('Tab');\n await settled(page);\n const stop = await page.evaluate(readStop);\n if (stop === null) break;\n const identity = `${stop.label}@${stop.rect.x},${stop.rect.y}`;\n // Focus wrapped back to where it started: the walk is complete.\n if (identity === first) break;\n first ??= identity;\n stops.push(stop);\n }\n return stops;\n};\n\n/**\n * Tabs through the page from the top and fails on what a keyboard user would\n * hit (ADR 0024): no skip link first when `skipLink` is set, the first stop\n * inside `main` past `mainIndexMax`, a stop with no visible indicator, a stop\n * something else covers, and a stop that jumps back more than a row in its\n * column.\n */\nexport async function walkKeyboard(\n page: Page,\n { maxStops = 120, skipLink = true, mainIndexMax = 3 }: WalkOptions = {},\n): Promise<void> {\n await fromTheTop(page);\n const stops = await tabThrough(page, maxStops);\n\n let walk: FocusWalk = { stops };\n if (skipLink && stops[0]?.isSkipLink === true) {\n await fromTheTop(page);\n await page.keyboard.press('Tab');\n await page.keyboard.press('Enter');\n walk = { stops, afterSkip: await tabThrough(page, maxStops) };\n }\n\n await page.evaluate(id => document.getElementById(id)?.remove(), WALK_START);\n expect(assessWalk(walk, { skipLink, mainIndexMax })).toEqual([]);\n}\n\nexport interface FocusKeptOptions {\n /**\n * The issue that stops this write dropping focus, while it still does. The\n * check then expects focus on `<body>` and fails once it is not, so the fix\n * has to delete the option — the same ratchet as an axe baseline entry.\n */\n readonly lostUntil?: string;\n}\n\n/**\n * After a write — a save, a delete, a submitted step — focus must land on\n * something, not fall back to the document, where a screen reader loses its\n * place and the next Tab starts from the top (2.4.3).\n */\nexport async function expectFocusKept(\n page: Page,\n { lostUntil }: FocusKeptOptions = {},\n): Promise<void> {\n await settled(page);\n const kept = await page.evaluate(\n () =>\n document.activeElement !== null &&\n document.activeElement !== document.body,\n );\n if (lostUntil === undefined) {\n expect(kept, 'focus fell back to <body> after the write').toBe(true);\n } else {\n expect(\n kept,\n `focus is kept after this write now: delete the lostUntil for ${lostUntil}`,\n ).toBe(false);\n }\n}\n"],"names":["expect","settled","assessWalk","readStop","element","document","activeElement","body","rect","getBoundingClientRect","style","getComputedStyle","scroller","parentElement","test","overflowY","scrollHeight","clientHeight","origin","x","window","scrollX","y","scrollY","box","scrollLeft","scrollTop","path","node","documentElement","tagName","toLowerCase","children","indexOf","outline","outlineStyle","parseFloat","outlineWidth","ring","boxShadow","inset","Math","min","width","height","points","obscured","every","hit","elementFromPoint","contains","visible","candidates","find","candidate","checkVisibility","href","getAttribute","target","startsWith","length","querySelectorAll","CSS","escape","slice","main","isSkipLink","name","textContent","trim","role","label","container","inMain","indicatorVisible","WALK_START","fromTheTop","page","evaluate","id","scrollTo","start","getElementById","createElement","tabIndex","prepend","focus","preventScroll","tabThrough","maxStops","stops","first","pressed","keyboard","press","stop","identity","push","walkKeyboard","skipLink","mainIndexMax","walk","afterSkip","remove","toEqual","expectFocusKept","lostUntil","kept","undefined","toBe"],"mappings":"AAAA,+EAA+E;AAC/E,wEAAwE;AACxE,2BAA2B;AAC3B,SAASA,MAAM,QAAmB,mBAAmB;AAErD,SAASC,OAAO,QAAQ,cAAc;AACtC,SACEC,UAAU,QAIL,YAAY;AAOnB,gEAAgE,GAChE,MAAMC,WAAW;QAmFbC,MAAAA;QACAA;IAnFF,MAAMA,UAAUC,SAASC,aAAa;IACtC,IAAIF,YAAY,QAAQA,YAAYC,SAASE,IAAI,EAAE,OAAO;IAE1D,MAAMC,OAAOJ,QAAQK,qBAAqB;IAC1C,MAAMC,QAAQC,iBAAiBP;IAE/B,2EAA2E;IAC3E,wEAAwE;IACxE,2EAA2E;IAC3E,6EAA6E;IAC7E,6EAA6E;IAC7E,IAAIQ,WAA+BR,QAAQS,aAAa;IACxD,MACED,aAAa,QACbA,aAAaP,SAASE,IAAI,IAC1B,CACE,CAAA,cAAcO,IAAI,CAACH,iBAAiBC,UAAUG,SAAS,KACvDH,SAASI,YAAY,GAAGJ,SAASK,YAAY,AAAD,EAE9C;QACAL,WAAWA,SAASC,aAAa;IACnC;IACA,IAAID,aAAaP,SAASE,IAAI,EAAEK,WAAW;IAC3C,MAAMM,SACJN,aAAa,OACT;QAAEO,GAAG,CAACC,OAAOC,OAAO;QAAEC,GAAG,CAACF,OAAOG,OAAO;IAAC,IACzC,AAAC,CAAA;QACC,MAAMC,MAAMZ,SAASH,qBAAqB;QAC1C,OAAO;YACLU,GAAGK,IAAIL,CAAC,GAAGP,SAASa,UAAU;YAC9BH,GAAGE,IAAIF,CAAC,GAAGV,SAASc,SAAS;QAC/B;IACF,CAAA;IACN,MAAMC,OAAO,CAACC;;YAGqHA;eAFjIA,SAAS,OACL,aACA,GAAGD,KAAKC,KAAKf,aAAa,KAAKR,SAASwB,eAAe,GAAG,OAAOD,KAAKf,aAAa,EAAE,GAAG,EA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EX;IAAM;IAC9B,IAAIS,YAAYT,EAAAA,UAAAA,KAAK,CAAC,EAAE,qBAARA,QAAUxB,UAAU,MAAK,MAAM;QAC7C,MAAMU,WAAWC;QACjB,MAAMA,KAAKgB,QAAQ,CAACC,KAAK,CAAC;QAC1B,MAAMjB,KAAKgB,QAAQ,CAACC,KAAK,CAAC;QAC1BO,OAAO;YAAEX;YAAOY,WAAW,MAAMd,WAAWX,MAAMY;QAAU;IAC9D;IAEA,MAAMZ,KAAKC,QAAQ,CAACC,CAAAA;YAAM1E;gBAAAA,2BAAAA,SAAS6E,cAAc,CAACH,wBAAxB1E,yBAA6BkG,MAAM;OAAI5B;IACjE3E,OAAOE,WAAWmG,MAAM;QAAEF;QAAUC;IAAa,IAAII,OAAO,CAAC,EAAE;AACjE;AAWA;;;;CAIC,GACD,OAAO,eAAeC,gBACpB5B,IAAU,EACV,EAAE6B,SAAS,EAAoB,GAAG,CAAC,CAAC;IAEpC,MAAMzG,QAAQ4E;IACd,MAAM8B,OAAO,MAAM9B,KAAKC,QAAQ,CAC9B,IACEzE,SAASC,aAAa,KAAK,QAC3BD,SAASC,aAAa,KAAKD,SAASE,IAAI;IAE5C,IAAImG,cAAcE,WAAW;QAC3B5G,OAAO2G,MAAM,6CAA6CE,IAAI,CAAC;IACjE,OAAO;QACL7G,OACE2G,MACA,CAAC,6DAA6D,EAAED,WAAW,EAC3EG,IAAI,CAAC;IACT;AACF"}
@@ -0,0 +1,4 @@
1
+ import type { Page } from '@playwright/test';
2
+ /** Resolves once the page's animations and transitions have finished. */
3
+ export declare const settled: (page: Page) => Promise<void>;
4
+ //# sourceMappingURL=settle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settle.d.ts","sourceRoot":"","sources":["../../src/a11y/settle.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAW7C,yEAAyE;AACzE,eAAO,MAAM,OAAO,GAAU,MAAM,IAAI,kBAavC,CAAC"}
@@ -0,0 +1,19 @@
1
+ // Serialized by `page.evaluate` and run in the browser.
2
+ /// <reference lib="dom" />
3
+ /**
4
+ * WCAG judges what is on screen once it has settled. A focus ring animates in,
5
+ * and a palette applied after hydration transitions every colour — axe
6
+ * measuring contrast mid-transition reports a ratio no user ever sees. So a
7
+ * read waits for every finite animation to finish, and never happens sooner
8
+ * than `SETTLE_MS` after whatever moved.
9
+ */ const SETTLE_MS = 200;
10
+ /** Resolves once the page's animations and transitions have finished. */ export const settled = async (page)=>{
11
+ await page.waitForTimeout(SETTLE_MS);
12
+ await page.evaluate(()=>Promise.all(document.getAnimations()// A spinner never finishes; only what eventually settles is awaited.
13
+ .filter((animation)=>{
14
+ var _animation_effect;
15
+ return ((_animation_effect = animation.effect) == null ? void 0 : _animation_effect.getTiming().iterations) !== Infinity;
16
+ }).map((animation)=>animation.finished)));
17
+ };
18
+
19
+ //# sourceMappingURL=settle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/a11y/settle.ts"],"sourcesContent":["// Serialized by `page.evaluate` and run in the browser.\n/// <reference lib=\"dom\" />\nimport type { Page } from '@playwright/test';\n\n/**\n * WCAG judges what is on screen once it has settled. A focus ring animates in,\n * and a palette applied after hydration transitions every colour — axe\n * measuring contrast mid-transition reports a ratio no user ever sees. So a\n * read waits for every finite animation to finish, and never happens sooner\n * than `SETTLE_MS` after whatever moved.\n */\nconst SETTLE_MS = 200;\n\n/** Resolves once the page's animations and transitions have finished. */\nexport const settled = async (page: Page) => {\n await page.waitForTimeout(SETTLE_MS);\n await page.evaluate(() =>\n Promise.all(\n document\n .getAnimations()\n // A spinner never finishes; only what eventually settles is awaited.\n .filter(\n animation => animation.effect?.getTiming().iterations !== Infinity,\n )\n .map(animation => animation.finished),\n ),\n );\n};\n"],"names":["SETTLE_MS","settled","page","waitForTimeout","evaluate","Promise","all","document","getAnimations","filter","animation","effect","getTiming","iterations","Infinity","map","finished"],"mappings":"AAAA,wDAAwD;AACxD,2BAA2B;AAG3B;;;;;;CAMC,GACD,MAAMA,YAAY;AAElB,uEAAuE,GACvE,OAAO,MAAMC,UAAU,OAAOC;IAC5B,MAAMA,KAAKC,cAAc,CAACH;IAC1B,MAAME,KAAKE,QAAQ,CAAC,IAClBC,QAAQC,GAAG,CACTC,SACGC,aAAa,EACd,qEAAqE;SACpEC,MAAM,CACLC,CAAAA;gBAAaA;mBAAAA,EAAAA,oBAAAA,UAAUC,MAAM,qBAAhBD,kBAAkBE,SAAS,GAAGC,UAAU,MAAKC;WAE3DC,GAAG,CAACL,CAAAA,YAAaA,UAAUM,QAAQ;AAG5C,EAAE"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The deterministic part of what axe cannot see, as data: the stops a Tab walk
3
+ * visited, judged against focus order, a visible indicator and nothing
4
+ * covering the focused control (WCAG 2.4.1, 2.4.3, 2.4.7 and 2.4.11).
5
+ */
6
+ /**
7
+ * Where a stop sits in the content it scrolls with, in CSS pixels — inside
8
+ * its nearest scrolling container, or the document — so two stops read before
9
+ * and after that container scrolled can be compared.
10
+ */
11
+ export interface FocusRect {
12
+ readonly x: number;
13
+ readonly y: number;
14
+ readonly width: number;
15
+ readonly height: number;
16
+ }
17
+ /** One element focus rested on during the walk. */
18
+ export interface FocusStop {
19
+ /** A short description for the failure message: tag, role and name. */
20
+ readonly label: string;
21
+ readonly rect: FocusRect;
22
+ /**
23
+ * The content `rect` is measured in: the nearest scrolling ancestor, or
24
+ * `document`. Positions in two different contents are not comparable, so
25
+ * visual order is only judged between stops that share one.
26
+ */
27
+ readonly container: string;
28
+ readonly inMain: boolean;
29
+ /** An in-page link to `main`, or to something inside it. */
30
+ readonly isSkipLink: boolean;
31
+ /** An outline or a ring could be seen once the focus transition settled. */
32
+ readonly indicatorVisible: boolean;
33
+ /** Entirely hidden: no sampled point of the stop shows the stop (2.4.11). */
34
+ readonly obscured: boolean;
35
+ }
36
+ /** A walk's stops: from the top, and after activating the skip link. */
37
+ export interface FocusWalk {
38
+ readonly stops: readonly FocusStop[];
39
+ /** Present when the walk activated a skip link and kept going. */
40
+ readonly afterSkip?: readonly FocusStop[];
41
+ }
42
+ export interface WalkExpectations {
43
+ /** The first stop must be a skip link, and activating it must reach `main`. */
44
+ readonly skipLink: boolean;
45
+ /**
46
+ * The highest 1-based position the first stop inside `main` may have —
47
+ * counted after the skip link when there is one, from the top otherwise.
48
+ */
49
+ readonly mainIndexMax: number;
50
+ }
51
+ /** Every failure the walk shows, one message per failure; empty is a pass. */
52
+ export declare const assessWalk: (walk: FocusWalk, expectations: WalkExpectations) => string[];
53
+ //# sourceMappingURL=walk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walk.d.ts","sourceRoot":"","sources":["../../src/a11y/walk.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,mDAAmD;AACnD,MAAM,WAAW,SAAS;IACxB,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,4DAA4D;IAC5D,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,4EAA4E;IAC5E,QAAQ,CAAC,gBAAgB,EAAE,OAAO,CAAC;IACnC,6EAA6E;IAC7E,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC5B;AAED,wEAAwE;AACxE,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,KAAK,EAAE,SAAS,SAAS,EAAE,CAAC;IACrC,kEAAkE;IAClE,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;CAC3C;AAED,MAAM,WAAW,gBAAgB;IAC/B,+EAA+E;IAC/E,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC/B;AAsBD,8EAA8E;AAC9E,eAAO,MAAM,UAAU,GACrB,MAAM,SAAS,EACf,cAAc,gBAAgB,KAC7B,MAAM,EAwCR,CAAC"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The deterministic part of what axe cannot see, as data: the stops a Tab walk
3
+ * visited, judged against focus order, a visible indicator and nothing
4
+ * covering the focused control (WCAG 2.4.1, 2.4.3, 2.4.7 and 2.4.11).
5
+ */ /**
6
+ * Where a stop sits in the content it scrolls with, in CSS pixels — inside
7
+ * its nearest scrolling container, or the document — so two stops read before
8
+ * and after that container scrolled can be compared.
9
+ */ const describe = (stop, position)=>`stop ${position} (${stop.label})`;
10
+ /** The stops are in an order a sighted keyboard user can follow (2.4.3). */ const outOfOrder = (stops)=>stops.slice(1).flatMap((stop, index)=>{
11
+ const previous = stops[index];
12
+ if (stop.container !== previous.container) return [];
13
+ const sameColumn = stop.rect.x < previous.rect.x + previous.rect.width && previous.rect.x < stop.rect.x + stop.rect.width;
14
+ const rowAbove = stop.rect.y + stop.rect.height <= previous.rect.y;
15
+ const moreThanARow = stop.rect.y < previous.rect.y - previous.rect.height;
16
+ return sameColumn && rowAbove && moreThanARow ? [
17
+ `${describe(stop, index + 2)} sits more than a row above ${describe(previous, index + 1)} in the same column`
18
+ ] : [];
19
+ });
20
+ /** Every failure the walk shows, one message per failure; empty is a pass. */ export const assessWalk = (walk, expectations)=>{
21
+ const failures = [];
22
+ const first = walk.stops[0];
23
+ if (first === undefined) {
24
+ return [
25
+ 'the walk reached no focusable element'
26
+ ];
27
+ }
28
+ let counted = walk.stops;
29
+ if (expectations.skipLink) {
30
+ if (!first.isSkipLink) {
31
+ failures.push(`the first stop is ${first.label}, not a skip link`);
32
+ } else if (walk.afterSkip === undefined) {
33
+ failures.push('the skip link was found but not activated');
34
+ } else {
35
+ counted = walk.afterSkip;
36
+ }
37
+ }
38
+ const mainAt = counted.findIndex((stop)=>stop.inMain) + 1;
39
+ if (mainAt === 0) {
40
+ failures.push(`no stop inside main in the first ${counted.length}`);
41
+ } else if (mainAt > expectations.mainIndexMax) {
42
+ failures.push(`the first stop inside main is number ${mainAt}, over the limit of ${expectations.mainIndexMax}`);
43
+ }
44
+ walk.stops.forEach((stop, index)=>{
45
+ if (!stop.indicatorVisible) {
46
+ failures.push(`${describe(stop, index + 1)} shows no focus indicator`);
47
+ }
48
+ if (stop.obscured) {
49
+ failures.push(`${describe(stop, index + 1)} is covered by another element`);
50
+ }
51
+ });
52
+ return [
53
+ ...failures,
54
+ ...outOfOrder(walk.stops)
55
+ ];
56
+ };
57
+
58
+ //# sourceMappingURL=walk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/a11y/walk.ts"],"sourcesContent":["/**\n * The deterministic part of what axe cannot see, as data: the stops a Tab walk\n * visited, judged against focus order, a visible indicator and nothing\n * covering the focused control (WCAG 2.4.1, 2.4.3, 2.4.7 and 2.4.11).\n */\n\n/**\n * Where a stop sits in the content it scrolls with, in CSS pixels — inside\n * its nearest scrolling container, or the document — so two stops read before\n * and after that container scrolled can be compared.\n */\nexport interface FocusRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** One element focus rested on during the walk. */\nexport interface FocusStop {\n /** A short description for the failure message: tag, role and name. */\n readonly label: string;\n readonly rect: FocusRect;\n /**\n * The content `rect` is measured in: the nearest scrolling ancestor, or\n * `document`. Positions in two different contents are not comparable, so\n * visual order is only judged between stops that share one.\n */\n readonly container: string;\n readonly inMain: boolean;\n /** An in-page link to `main`, or to something inside it. */\n readonly isSkipLink: boolean;\n /** An outline or a ring could be seen once the focus transition settled. */\n readonly indicatorVisible: boolean;\n /** Entirely hidden: no sampled point of the stop shows the stop (2.4.11). */\n readonly obscured: boolean;\n}\n\n/** A walk's stops: from the top, and after activating the skip link. */\nexport interface FocusWalk {\n readonly stops: readonly FocusStop[];\n /** Present when the walk activated a skip link and kept going. */\n readonly afterSkip?: readonly FocusStop[];\n}\n\nexport interface WalkExpectations {\n /** The first stop must be a skip link, and activating it must reach `main`. */\n readonly skipLink: boolean;\n /**\n * The highest 1-based position the first stop inside `main` may have —\n * counted after the skip link when there is one, from the top otherwise.\n */\n readonly mainIndexMax: number;\n}\n\nconst describe = (stop: FocusStop, position: number) =>\n `stop ${position} (${stop.label})`;\n\n/** The stops are in an order a sighted keyboard user can follow (2.4.3). */\nconst outOfOrder = (stops: readonly FocusStop[]): string[] =>\n stops.slice(1).flatMap((stop, index) => {\n const previous = stops[index] as FocusStop;\n if (stop.container !== previous.container) return [];\n const sameColumn =\n stop.rect.x < previous.rect.x + previous.rect.width &&\n previous.rect.x < stop.rect.x + stop.rect.width;\n const rowAbove = stop.rect.y + stop.rect.height <= previous.rect.y;\n const moreThanARow = stop.rect.y < previous.rect.y - previous.rect.height;\n return sameColumn && rowAbove && moreThanARow\n ? [\n `${describe(stop, index + 2)} sits more than a row above ${describe(previous, index + 1)} in the same column`,\n ]\n : [];\n });\n\n/** Every failure the walk shows, one message per failure; empty is a pass. */\nexport const assessWalk = (\n walk: FocusWalk,\n expectations: WalkExpectations,\n): string[] => {\n const failures: string[] = [];\n const first = walk.stops[0];\n\n if (first === undefined) {\n return ['the walk reached no focusable element'];\n }\n\n let counted = walk.stops;\n if (expectations.skipLink) {\n if (!first.isSkipLink) {\n failures.push(`the first stop is ${first.label}, not a skip link`);\n } else if (walk.afterSkip === undefined) {\n failures.push('the skip link was found but not activated');\n } else {\n counted = walk.afterSkip;\n }\n }\n\n const mainAt = counted.findIndex(stop => stop.inMain) + 1;\n if (mainAt === 0) {\n failures.push(`no stop inside main in the first ${counted.length}`);\n } else if (mainAt > expectations.mainIndexMax) {\n failures.push(\n `the first stop inside main is number ${mainAt}, over the limit of ${expectations.mainIndexMax}`,\n );\n }\n\n walk.stops.forEach((stop, index) => {\n if (!stop.indicatorVisible) {\n failures.push(`${describe(stop, index + 1)} shows no focus indicator`);\n }\n if (stop.obscured) {\n failures.push(\n `${describe(stop, index + 1)} is covered by another element`,\n );\n }\n });\n\n return [...failures, ...outOfOrder(walk.stops)];\n};\n"],"names":["describe","stop","position","label","outOfOrder","stops","slice","flatMap","index","previous","container","sameColumn","rect","x","width","rowAbove","y","height","moreThanARow","assessWalk","walk","expectations","failures","first","undefined","counted","skipLink","isSkipLink","push","afterSkip","mainAt","findIndex","inMain","length","mainIndexMax","forEach","indicatorVisible","obscured"],"mappings":"AAAA;;;;CAIC,GAED;;;;CAIC,GA6CD,MAAMA,WAAW,CAACC,MAAiBC,WACjC,CAAC,KAAK,EAAEA,SAAS,EAAE,EAAED,KAAKE,KAAK,CAAC,CAAC,CAAC;AAEpC,0EAA0E,GAC1E,MAAMC,aAAa,CAACC,QAClBA,MAAMC,KAAK,CAAC,GAAGC,OAAO,CAAC,CAACN,MAAMO;QAC5B,MAAMC,WAAWJ,KAAK,CAACG,MAAM;QAC7B,IAAIP,KAAKS,SAAS,KAAKD,SAASC,SAAS,EAAE,OAAO,EAAE;QACpD,MAAMC,aACJV,KAAKW,IAAI,CAACC,CAAC,GAAGJ,SAASG,IAAI,CAACC,CAAC,GAAGJ,SAASG,IAAI,CAACE,KAAK,IACnDL,SAASG,IAAI,CAACC,CAAC,GAAGZ,KAAKW,IAAI,CAACC,CAAC,GAAGZ,KAAKW,IAAI,CAACE,KAAK;QACjD,MAAMC,WAAWd,KAAKW,IAAI,CAACI,CAAC,GAAGf,KAAKW,IAAI,CAACK,MAAM,IAAIR,SAASG,IAAI,CAACI,CAAC;QAClE,MAAME,eAAejB,KAAKW,IAAI,CAACI,CAAC,GAAGP,SAASG,IAAI,CAACI,CAAC,GAAGP,SAASG,IAAI,CAACK,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AG,8BAA8B,CAAC;QAEhE;IACF;IAEA,OAAO;WAAIc;WAAalB,WAAWgB,KAAKf,KAAK;KAAE;AACjD,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/testing-e2e",
3
- "version": "0.18.0",
3
+ "version": "0.18.2",
4
4
  "description": "End-to-end testing with one set of journeys and two profiles: mocked backends by default, real infrastructure on demand.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,6 +41,11 @@
41
41
  "types": "./dist/playwright/index.d.ts",
42
42
  "import": "./dist/playwright/index.js",
43
43
  "default": "./dist/playwright/index.js"
44
+ },
45
+ "./a11y": {
46
+ "types": "./dist/a11y/index.d.ts",
47
+ "import": "./dist/a11y/index.js",
48
+ "default": "./dist/a11y/index.js"
44
49
  }
45
50
  },
46
51
  "nx": {
@@ -67,11 +72,12 @@
67
72
  },
68
73
  "dependencies": {
69
74
  "@swc/helpers": "0.5.23",
70
- "@entifix/business": "0.18.0",
71
- "@entifix/core": "0.18.0",
72
- "@entifix/testing-unit": "0.18.0"
75
+ "@entifix/business": "0.18.2",
76
+ "@entifix/core": "0.18.2",
77
+ "@entifix/testing-unit": "0.18.2"
73
78
  },
74
79
  "peerDependencies": {
80
+ "@axe-core/playwright": ">=4.14 <5",
75
81
  "@msw/playwright": ">=0.7",
76
82
  "@nx/devkit": ">=24 <25",
77
83
  "@nx/playwright": ">=24 <25",
@@ -80,30 +86,33 @@
80
86
  "effect": "^4.0.7",
81
87
  "msw": ">=3",
82
88
  "vitest": "*",
83
- "@entifix/amqp": "0.18.0",
84
- "@entifix/mongo": "0.18.0",
85
- "@entifix/redis": "0.18.0"
89
+ "@entifix/amqp": "0.18.2",
90
+ "@entifix/mongo": "0.18.2",
91
+ "@entifix/redis": "0.18.2"
86
92
  },
87
93
  "peerDependenciesMeta": {
88
- "@msw/playwright": {
94
+ "@axe-core/playwright": {
89
95
  "optional": true
90
96
  },
91
- "@nx/devkit": {
97
+ "@entifix/amqp": {
92
98
  "optional": true
93
99
  },
94
- "@nx/playwright": {
100
+ "@entifix/mongo": {
95
101
  "optional": true
96
102
  },
97
- "@playwright/test": {
103
+ "@entifix/redis": {
98
104
  "optional": true
99
105
  },
100
- "@entifix/amqp": {
106
+ "@msw/playwright": {
101
107
  "optional": true
102
108
  },
103
- "@entifix/mongo": {
109
+ "@nx/devkit": {
104
110
  "optional": true
105
111
  },
106
- "@entifix/redis": {
112
+ "@nx/playwright": {
113
+ "optional": true
114
+ },
115
+ "@playwright/test": {
107
116
  "optional": true
108
117
  },
109
118
  "axios": {
@@ -120,8 +129,8 @@
120
129
  "@nx/devkit": "24.0.3",
121
130
  "@nx/playwright": "24.0.3",
122
131
  "effect": "4.0.7",
123
- "@entifix/amqp": "0.18.0",
124
- "@entifix/mongo": "0.18.0",
125
- "@entifix/redis": "0.18.0"
132
+ "@entifix/amqp": "0.18.2",
133
+ "@entifix/mongo": "0.18.2",
134
+ "@entifix/redis": "0.18.2"
126
135
  }
127
136
  }