@surea11y/playwright 1.4.2 → 1.5.0
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 +150 -4
- package/package.json +3 -3
- package/src/A11yCoreBuilder.d.ts +92 -11
- package/src/A11yCoreBuilder.js +136 -2
- package/src/index.js +2 -2
package/README.md
CHANGED
|
@@ -114,7 +114,7 @@ const results = await new A11yCoreBuilder({ page })
|
|
|
114
114
|
|
|
115
115
|
A batch job that writes `getScanGaps(results)` into its own report can pass `.logger(() => {})` to keep its output to the report, and `.logger(null)` brings `console.warn` back. Anything other than a function or `null` throws a `TypeError` at the call, and a later call replaces the logger. Either way, `getScanGaps(results)` still lists every gap.
|
|
116
116
|
|
|
117
|
-
`getScanNotes(results)` says how the page was scanned, which a gap doesn't cover, and nothing was left out: `'forced-colors'` when the page was shown in [forced colors](#forced-colors),
|
|
117
|
+
`getScanNotes(results)` says how the page was scanned, which a gap doesn't cover, and nothing was left out: `'forced-colors'` when the page was shown in [forced colors](#forced-colors), `'internals-hook'` when the scan asked about web components it could have read with the [internals hook](#web-components-the-internals-hook), and `'listener-hook'` or `'live-region-hook'` when findings that the [listener hook](#click-handlers-added-from-script-the-listener-hook) or the [live-region hook](#live-regions-the-live-region-hook-and-announcements) would have decided were judged without it (with `findingCount` and the `rules`). `.analyze()` also prints each hook note, once per scan, and a `.logger()` receives it (check `kind` to tell a note from a gap).
|
|
118
118
|
|
|
119
119
|
### Errors from the engine
|
|
120
120
|
|
|
@@ -163,9 +163,23 @@ To also fail when the scan left something out (an `.include()` that matched noth
|
|
|
163
163
|
|
|
164
164
|
See `examples/playwright-test-example.spec.js` for a fuller, runnable version (`npm run example:e2e`) — one test proving real violations get caught (unlabeled button, missing `alt`), one proving a well-formed page passes cleanly.
|
|
165
165
|
|
|
166
|
+
### Failing only on serious problems
|
|
167
|
+
|
|
168
|
+
Every rule result has a severity: `critical`, `serious`, `moderate` or `minor` (a profile can set its own). To start by blocking on serious problems while the rest are still reported, gate on `getGatingFailures(results, { failOnSeverity })` (`@surea11y/binding-base` 1.6.0 and later): the failing rules at that level or above, the same ones `surea11y scan --fail-on-severity` counts for the page. `formatFailures()` takes the same option and still lists the failures below the level, marked as ones that don't fail the test.
|
|
169
|
+
|
|
170
|
+
```js
|
|
171
|
+
const { A11yCoreBuilder, formatFailures, getGatingFailures } = require('@surea11y/playwright');
|
|
172
|
+
|
|
173
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
174
|
+
const gate = { failOnSeverity: 'serious' };
|
|
175
|
+
expect(getGatingFailures(results, gate), formatFailures(results, gate)).toEqual([]);
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`fail` keeps its meaning, a definite violation; the level only picks which failures stop the test, and every failure stays in `results`. A level that isn't one of the four throws a `TypeError`. `SEVERITIES` lists them, least to most severe.
|
|
179
|
+
|
|
166
180
|
### Readable console/CI output on failure
|
|
167
181
|
|
|
168
|
-
`expect(x).toEqual([])` alone gets you a *working* gate, but the failure message is a raw, deeply-nested object diff — hundreds of lines for a handful of violations. `formatFailures(results)` turns that into a short, scannable block (one entry per occurrence, numbered, with rule ID/severity/selector/hint) that you hand to your assertion library's own failure-message parameter, as above. A real failure then prints:
|
|
182
|
+
`expect(x).toEqual([])` alone gets you a *working* gate, but the failure message is a raw, deeply-nested object diff — hundreds of lines for a handful of violations. `formatFailures(results)` turns that into a short, scannable block (one entry per occurrence, numbered, with rule ID/severity/selector/hint) that you hand to your assertion library's own failure-message parameter, as above. Each occurrence is read by its own outcome, and the list follows the order a review takes: failures first, then the [questions](#findings-that-need-review-leans-and-how-to-check) that likely fail, those that likely pass, and those only a person can answer. A real failure then prints:
|
|
169
183
|
|
|
170
184
|
```
|
|
171
185
|
Error: 1) button-name-present (serious): This button has no accessible name.
|
|
@@ -182,7 +196,7 @@ Scanned with @surea11y/core 1.12.0.
|
|
|
182
196
|
|
|
183
197
|
Given the whole result, as here, it also lists what the scan left out (see `getScanGaps()` above; a scan whose `.include()` matched nothing never reads as "No accessibility violations found.") and its notes (`getScanNotes()`, such as a page shown in forced colors), and ends with the core release that produced the result. It still accepts `results.checksResults` alone, without those two parts. A finding inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img` (`formatOccurrenceLocation(occurrence)` gives that line on its own); that notation is for reading, not a selector `document.querySelector()` takes. For a `.frames(true)` scan, format `results.topFrame` and each frame on its own: both functions throw a `TypeError` for the `{ topFrame, frames }` shape rather than report it as clean.
|
|
184
198
|
|
|
185
|
-
...with Playwright's own raw diff still printed underneath (unavoidable — `toEqual` always includes it), but the readable summary now comes first, where it's actually useful. Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with Playwright's `expect`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report findings; a `notApplicable` rule can carry one occurrence saying why it had nothing to judge, which is left out); pass `{ outcomes: [...] }` to narrow further. A thrown rule (`occurrences: []`, `error` set) is still surfaced using its `error` message rather than silently dropped.
|
|
199
|
+
...with Playwright's own raw diff still printed underneath (unavoidable — `toEqual` always includes it), but the readable summary now comes first, where it's actually useful. Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with Playwright's `expect`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report findings; a `notApplicable` rule can carry one occurrence saying why it had nothing to judge, which is left out); pass `{ outcomes: [...] }` to narrow further, by outcome or by review group (`'leanFail'`, `'leanPass'`, `'open'`), and `{ howToCheck: true }` to list each question's steps (see [below](#findings-that-need-review-leans-and-how-to-check)). An outcome it doesn't know throws a `TypeError`. A thrown rule (`occurrences: []`, `error` set) is still surfaced using its `error` message rather than silently dropped.
|
|
186
200
|
|
|
187
201
|
### Scanning every frame, including cross-origin iframes
|
|
188
202
|
|
|
@@ -274,6 +288,46 @@ first.occurrences[0].screenshot;
|
|
|
274
288
|
|
|
275
289
|
The pictures are taken right after each frame's scan, before `.reportOnly()` trims the result, and combine with `.elementRef(true)`. Focus, hover, animations or content that loads late can still differ from what the scan saw. An option it can't use throws a `TypeError` with `code: 'INVALID_ENGINE_OPTIONS'` at the call, and so does `.analyze()` with `options({ output: { includeSelector: false } })`, since each element is found by its selector. Works in Chromium, Firefox and WebKit.
|
|
276
290
|
|
|
291
|
+
### Findings that need review: leans and how to check
|
|
292
|
+
|
|
293
|
+
A `cantTell` is a question for a person: the engine couldn't prove the answer from the page. With `@surea11y/core` 1.14, a question says more:
|
|
294
|
+
|
|
295
|
+
- **Which way it leans.** Where the page's evidence points one way, the occurrence has a `lean`: `toward` (`'fail'` or `'pass'`), `why`, and sometimes a `caution` saying what could make it wrong. A skipped heading level leans fail; `aria-checked` on a native checkbox leans pass. A lean counted against the W3C ACT test cases on five cases or more also says how often it was right (`measured`). The outcome stays `cantTell` either way. See core's [`LEANS.md`](https://github.com/SureA11y/core/blob/main/docs/LEANS.md).
|
|
296
|
+
- **How to check it.** Each question of a core rule carries `howToCheck`: `steps` starting from the element it names, and what a person sees if it passes (`passWhen`) or fails (`failWhen`), in the scan's locale. The engine in the page leaves them out; `.analyze()` adds them, with the steps of your packs' rules too.
|
|
297
|
+
|
|
298
|
+
`formatFailures()` shows both: each question says beside its severity whether it likely fails, likely passes or needs review, then why, the caution, and with `{ howToCheck: true }` the steps:
|
|
299
|
+
|
|
300
|
+
```
|
|
301
|
+
2) heading-order (minor, likely fails): This heading jumps from level 1 to level 3, skipping a level.
|
|
302
|
+
at html > body > main > h3
|
|
303
|
+
Go down one level at a time, so an <h2> is followed by an <h3> rather than an <h4>, and the outline of the page stays easy to follow.
|
|
304
|
+
Why it likely fails: The heading skips a level after the one before it.
|
|
305
|
+
How to check:
|
|
306
|
+
1. Find the heading the report names and note its level and the previous heading's level (from the report or the Accessibility pane).
|
|
307
|
+
...
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
To gate a test on the questions that likely fail as well as the failures, use `@surea11y/core`'s `leaningFailures(results)`, which works on this binding's results (a `.frames(true)` tree included). It leaves out the rules whose criteria are outside the scan's target, and with `{ wcagOnly: true }` the best-practice rules too:
|
|
311
|
+
|
|
312
|
+
```js
|
|
313
|
+
const { test, expect } = require('@playwright/test');
|
|
314
|
+
const { leaningFailures } = require('@surea11y/core');
|
|
315
|
+
const { A11yCoreBuilder, formatFailures } = require('@surea11y/playwright');
|
|
316
|
+
|
|
317
|
+
test('no failures, and no questions that likely fail', async ({ page }) => {
|
|
318
|
+
await page.goto('https://example.com/');
|
|
319
|
+
|
|
320
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
321
|
+
const failures = results.checksResults.filter((r) => r.outcome === 'fail');
|
|
322
|
+
expect(
|
|
323
|
+
[...failures, ...leaningFailures(results)],
|
|
324
|
+
formatFailures(results, { outcomes: ['fail', 'leanFail'] })
|
|
325
|
+
).toEqual([]);
|
|
326
|
+
});
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Don't trim such a result with `.reportOnly(['fail'])` first: it drops the `cantTell` rules, and their leans with them. `.reportOnly()` filters whole rules by their outcome, while a rule's occurrences can sit in different tiers (`occurrenceOutcome`), which `formatFailures()` reads one by one. For CI reports, core's `renderJunitReport(results, { leanFailAs: 'failure' })` and `renderSarifReport(results, { leanFailAs: 'error' })` gate on the same findings, and both carry the steps.
|
|
330
|
+
|
|
277
331
|
### Web components: the internals hook
|
|
278
332
|
|
|
279
333
|
Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
|
|
@@ -311,6 +365,57 @@ With it, the checkbox above passes, an unnamed component that attaches internals
|
|
|
311
365
|
- **For test and audit runs.** The hook wraps `HTMLElement.prototype.attachInternals` (components get the same internals back), adds a stack frame to errors thrown through it, and keeps its record under a global symbol, where any script on the page can read every component's internals. That's why it's opt-in.
|
|
312
366
|
- **Without it**, `.analyze()` says so once per scan when it asked about such components (`1 custom element was asked about because the scan could not read...`), and `getScanNotes()` gives that note as `kind: 'internals-hook'`.
|
|
313
367
|
|
|
368
|
+
### Click handlers added from script: the listener hook
|
|
369
|
+
|
|
370
|
+
Most pages add their click handlers from script, where no page script can list them afterwards:
|
|
371
|
+
|
|
372
|
+
```html
|
|
373
|
+
<div class="save" role="button" tabindex="0">Save</div>
|
|
374
|
+
<script>
|
|
375
|
+
document.querySelector('.save').addEventListener('click', save);
|
|
376
|
+
</script>
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
Enter and Space don't fire `click` on a `<div>`, so this button does nothing from the keyboard. Without help the scan can't see the listener, so `click-handler-keyboard-operable` doesn't report the element at all. `A11yCoreBuilder.installListenerHook(pageOrContext)` installs `@surea11y/core`'s opt-in listener hook (core 1.14.0 and later), which records the click, key, focus and mouse listeners a page adds, so the keyboard rules judge them. Call it **before** `page.goto()`, on the page or its browser context, as the internals hook:
|
|
380
|
+
|
|
381
|
+
```js
|
|
382
|
+
const context = await browser.newContext();
|
|
383
|
+
await A11yCoreBuilder.installListenerHook(context); // before any page navigates
|
|
384
|
+
const page = await context.newPage();
|
|
385
|
+
await page.goto('https://example.com/');
|
|
386
|
+
|
|
387
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
388
|
+
results.engine.environment.listenerHook; // 'early'
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
With `@playwright/test`, install it in a `beforeEach` on the `context` fixture, or on `page` before the test navigates.
|
|
392
|
+
|
|
393
|
+
With it, the button above fails (`CLICK_HANDLER_NO_KEY_LISTENER`: no key listener anywhere a key event from it goes), and `mouse-only-event-handlers` and `widget-keyboard-focusable` count the listeners too. Only a hook installed before the page's scripts (`'early'`) proves a listener is missing; one installed later is `'late'`, and the rules then only ask. It wraps `addEventListener`, `removeEventListener` and the `on…` setters, with the page getting the same results and errors, and keeps its record under a global symbol: install it for test and audit runs. Without it, `getScanNotes()` gives a `'listener-hook'` note when findings it would have decided were judged without it. Core's [`INTEGRATION.md`](https://github.com/SureA11y/core/blob/main/docs/INTEGRATION.md#seeing-listeners-added-from-script-the-listener-hook) has the details, and its binding authors' guide the reason codes each hook decides.
|
|
394
|
+
|
|
395
|
+
### Live regions: the live-region hook and announcements()
|
|
396
|
+
|
|
397
|
+
`A11yCoreBuilder.installLiveRegionHook(pageOrContext)` installs `@surea11y/core`'s opt-in live-region hook (core 1.14.0 and later), which records what the page's live regions are given while it runs. The scan then asks about a region added with its text already in it, and one shown and filled at once, which screen readers commonly don't announce. And `A11yCoreBuilder.announcements(page)` returns what the page made available to announce, so a test can check that an action told the user something:
|
|
398
|
+
|
|
399
|
+
```js
|
|
400
|
+
const { test, expect } = require('@playwright/test');
|
|
401
|
+
const { A11yCoreBuilder } = require('@surea11y/playwright');
|
|
402
|
+
|
|
403
|
+
test.beforeEach(async ({ context }) => {
|
|
404
|
+
await A11yCoreBuilder.installLiveRegionHook(context); // before the test navigates
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
test('saving says so', async ({ page }) => {
|
|
408
|
+
await page.goto('https://example.com/settings');
|
|
409
|
+
await page.getByRole('button', { name: 'Save' }).click();
|
|
410
|
+
|
|
411
|
+
const said = await A11yCoreBuilder.announcements(page);
|
|
412
|
+
// [{ text: 'Saved', politeness: 'polite', time: 1234.5, order: 7, behindModal: false, selector: '#status' }]
|
|
413
|
+
expect(said.map((a) => a.text)).toContain('Saved');
|
|
414
|
+
});
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Each entry names its region by `selector` (and `shadowHostSelectors` inside a shadow root; `null` for a region that has since left the page, such as a toast). It's `null` without the hook. A text given to a region behind an open modal dialog, which assistive technology did not get, is left out unless you pass `{ includeBehindModal: true }`, and comes marked `behindModal: true`. This is what the page made available to announce, not what a screen reader said. `announcements()` reads the page's top frame. The hook only observes, with one `MutationObserver`; see core's [`INTEGRATION.md`](https://github.com/SureA11y/core/blob/main/docs/INTEGRATION.md#seeing-what-live-regions-are-given-the-live-region-hook).
|
|
418
|
+
|
|
314
419
|
### Forced colors
|
|
315
420
|
|
|
316
421
|
A page shown in forced colors (Windows high contrast) draws in the user's colors, not its own. `results.engine.environment.forcedColors` says which it was: `'active'` or `'none'`. To check a page under forced colors on purpose, emulate it before scanning, in Chromium, Firefox or WebKit:
|
|
@@ -323,6 +428,24 @@ results.engine.environment.forcedColors; // 'active'
|
|
|
323
428
|
|
|
324
429
|
`browser.newContext({ forcedColors: 'active' })` does the same for a whole context, and `@playwright/test` takes it as a `use` option. The contrast rules still measure the page's own colors under forced colors, since WCAG judges contrast in those, so results match a scan with forced colors off; a contrast finding the engine couldn't measure that way carries `details.forcedColors: true`. When forced colors were active, `formatFailures()` adds a line saying so, since it's easy to miss on a CI agent with high contrast turned on.
|
|
325
430
|
|
|
431
|
+
### Dark mode and phone width: scans under conditions
|
|
432
|
+
|
|
433
|
+
A page can fail differently in dark mode or at phone width: text that reads well on white fails contrast on a dark background, and a target big enough at 1280 pixels shrinks at 320. `.conditions()` scans the page as it is, then under each condition, and returns one result:
|
|
434
|
+
|
|
435
|
+
```js
|
|
436
|
+
const results = await new A11yCoreBuilder({ page })
|
|
437
|
+
.conditions([{ colorScheme: 'dark' }, { width: 320 }, { colorScheme: 'dark', width: 320 }])
|
|
438
|
+
.analyze();
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
A condition sets a color scheme (`'light'` or `'dark'`, with `page.emulateMedia()`), a viewport width in CSS pixels (with `page.setViewportSize()`, keeping the height), or both. The viewport and color scheme are put back after the last scan, even when one throws.
|
|
442
|
+
|
|
443
|
+
- A rule's outcome is its worst across the scans, so a contrast failure only in dark mode fails the rule.
|
|
444
|
+
- An occurrence is listed once per element, rule and reason code, with the `conditions` it appeared under (`['default', 'dark']`); `formatFailures()` prints them as `seen in: default, dark`.
|
|
445
|
+
- `results.conditionRuns` lists each scan's condition and `engine.environment`.
|
|
446
|
+
|
|
447
|
+
Each condition is a full scan, so three conditions take about four times as long as one scan. `.frames(true)` can't be combined with `.conditions()` yet. A picture taken with `.screenshots()` under a condition has the condition in its file name.
|
|
448
|
+
|
|
326
449
|
### Registering a custom rule at runtime
|
|
327
450
|
|
|
328
451
|
`@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
|
|
@@ -409,13 +532,36 @@ A pack's own rules appear in `checksResults` like core's, with ids that start wi
|
|
|
409
532
|
|
|
410
533
|
**When a pack doesn't run.** `.withPacks()` builds the page's script with the `@surea11y/core` this binding loads, and checks each pack as it does: `.analyze()` throws before scanning for a pack that core can't run, such as one whose `core` range leaves out the installed core, or whose profile names a rule that doesn't exist. A pack the page then doesn't run (one named with a raw `.options({ packs })` and never registered, or a page running another core version, when two copies of core are installed) is listed in `results.skippedPacks` with the reason. `getScanGaps()` reports that as `'pack-skipped'`, and `.analyze()` warns about it, so a test gate that asserts on `getScanGaps(results)` fails rather than passing with the pack's checks never run.
|
|
411
534
|
|
|
535
|
+
### Style sheets from another origin
|
|
536
|
+
|
|
537
|
+
A page's script can't read the rules of a style sheet served from another origin (a CDN, a fonts service), so a check that reads the CSS, such as `css-orientation-lock`, can't tell whether it holds an orientation lock and asks about it. With `@surea11y/core` 1.14.0 or later, `.analyze()` asks the page which sheets it can't read, fetches them from Node with the page's own request API (so the page's cookies go with them), and gives core their text, which it then checks. It's on by default, as axe fetches such sheets; each request is given up after five seconds, and a sheet that can't be fetched leaves the check asking as before. To send no request but the page's own:
|
|
538
|
+
|
|
539
|
+
```js
|
|
540
|
+
await new A11yCoreBuilder({ page }).fetchStyleSheets(false).analyze();
|
|
541
|
+
```
|
|
542
|
+
|
|
412
543
|
### Element addressing beyond a CSS selector
|
|
413
544
|
|
|
414
545
|
Every occurrence already carries `selector` and (with `.elementRef(true)`, above) a live `ElementHandle`. For an element inside a shadow tree, `selector` holds inside its shadow root, and `shadowHostSelectors` lists the shadow hosts that lead there, outermost first, each resolved in the tree that holds it. It also carries `structuralPath` — a sibling-index path from the document root down to the flagged element (e.g. `[1, 0, 2]`) — a more robust identity than a selector string alone, since it survives some DOM changes a selector wouldn't (an id/class rename, for instance). No opt-in needed; it's already on every `fail`/`cantTell` occurrence today. See [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) for the full field description.
|
|
415
546
|
|
|
416
547
|
## TypeScript
|
|
417
548
|
|
|
418
|
-
`src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API and the result (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result types are built on the ones `@surea11y/core` ships, so they carry every field the engine returns (`engine.version`, `engine.environment`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors`, `margin`, ...); this package adds `elementHandle`, `screenshot` (`OccurrenceScreenshot`) and the `.frames(true)` shape. `EngineError`/`EngineErrorCode`, `getScanGaps()`/`ScanGap`, `getScanNotes()`/`ScanNote` and `formatOccurrenceLocation()` are typed too, and so are `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`), the static `installInternalsHook()`, `withPacks()`, which takes a pack made with `definePack` (`PackLike`), and `.screenshots()` (`ScreenshotOptions`). Code that handles every `ScanGap` kind it knows and treats the rest in an `else` branch needs a branch for `'pack-skipped'`, which carries `pack` rather than `selectors`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `playwright` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `playwright` install for the types to resolve, same as they already do to construct a `Page` in the first place.
|
|
549
|
+
`src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API and the result (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result types are built on the ones `@surea11y/core` ships, so they carry every field the engine returns (`engine.version`, `engine.environment`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors`, `margin`, ...); this package adds `elementHandle`, `screenshot` (`OccurrenceScreenshot`) and the `.frames(true)` shape. `EngineError`/`EngineErrorCode`, `getScanGaps()`/`ScanGap`, `getScanNotes()`/`ScanNote` and `formatOccurrenceLocation()` are typed too, and so are `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`), the static `installInternalsHook()`, `installListenerHook()` and `installLiveRegionHook()` (each taking a `Page` or a `BrowserContext`) and `announcements(page)`, which resolves to `LocatedAnnouncement[] | null`, `formatFailures()`'s review groups (`ReviewGroup`) and `howToCheck` option, `withPacks()`, which takes a pack made with `definePack` (`PackLike`), and `.screenshots()` (`ScreenshotOptions`). Code that handles every `ScanGap` kind it knows and treats the rest in an `else` branch needs a branch for `'pack-skipped'`, which carries `pack` rather than `selectors`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `playwright` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `playwright` install for the types to resolve, same as they already do to construct a `Page` in the first place.
|
|
550
|
+
|
|
551
|
+
## What changes with `@surea11y/core` 1.14
|
|
552
|
+
|
|
553
|
+
With `@surea11y/core` 1.14.0, what a scan through this binding shows differently (core's [`CHANGELOG.md`](https://github.com/SureA11y/core/blob/main/CHANGELOG.md) has the full list):
|
|
554
|
+
|
|
555
|
+
- **No WCAG criterion passes yet.** A criterion's rollup passes only when its rules check everything it asks, and none is listed as checked in full yet, so where its rules all pass it is `cantTell` (`composite.rollup.cantTell.partialCheck`). A rollup whose rules all found nothing is `notApplicable` only for 2.4.3, 2.4.4, 2.4.7, 2.4.9, 2.5.3 and 4.1.1, whose rules find every case, and `cantTell` otherwise (`composite.rollup.cantTell.partialCoverage`). A gate that asserted a criterion `pass` or `notApplicable` now sees `cantTell`; gate on `fail`, as `getGatingFailures()` does.
|
|
556
|
+
- **More questions.** `page-title-patterns` asks about every page title, so 2.4.2 is `cantTell` on a page with one, and `duplicate-id` asks about 4.1.1 under WCAG 2.0 and 2.1 too.
|
|
557
|
+
- **Questions lean, and say how to answer them.** A `cantTell` occurrence can carry a `lean` (which way the evidence points, and why) and carries `howToCheck` (the steps to answer it), which `.analyze()` adds. `formatFailures()` lists findings in the order a review takes and shows both. [More](#findings-that-need-review-leans-and-how-to-check).
|
|
558
|
+
- **New rules.** `widget-keyboard-focusable` (2.1.1) asks about a widget Tab never reaches. `click-handler-keyboard-operable` (2.1.1, 2.1.3) fails a `role="button"`, `link`, `checkbox` or `switch` with a click handler that nothing can bring keyboard focus to, and asks about one with no key handler. `focus-not-removed-by-script` (2.1.1, 2.4.7) fails an element whose `onfocus` only blurs it. `moving-content-pausable` (2.2.2) asks about content an animation moves for more than five seconds. `invalid-field-error-message` (3.3.1) asks about a field marked `aria-invalid` whose error message can't be reached. `live-region-announcements` (4.1.3) asks about a live region hidden with `aria-hidden` or `inert`, or left `aria-busy`. `aria-owns-valid` (1.3.1, 4.1.2) fails an element owned twice. `aria-expanded-state-mismatch` (4.1.2) asks about `aria-expanded` that contradicts what its `aria-controls` names, `image-of-text` (1.4.5) whether text drawn in an image could be real text, and the best practices `label-for-valid` and `control-name-title-only` about a `<label for>` that labels nothing and a control named only by its `title`.
|
|
559
|
+
- **Two more opt-in hooks.** With [`installListenerHook()`](#click-handlers-added-from-script-the-listener-hook), the keyboard rules judge click listeners added with `addEventListener`, and fail a focusable control no key listener can reach (`CLICK_HANDLER_NO_KEY_LISTENER`). With [`installLiveRegionHook()`](#live-regions-the-live-region-hook-and-announcements), `live-region-announcements` also asks about a region added with its text or shown and filled at once, and `A11yCoreBuilder.announcements(page)` returns what the page made available to announce.
|
|
560
|
+
- **Style sheets from another origin are checked.** `.analyze()` fetches, from Node, the style sheets the page can't read and core checks them, so `css-orientation-lock` finds a lock in a CDN's CSS instead of asking (`.fetchStyleSheets(false)` turns it off). [More](#style-sheets-from-another-origin).
|
|
561
|
+
- **Contrast is measured on more of what the page draws:** text on a page with no background in each color scheme it can be drawn in, `::first-line` and `::first-letter`, `font-size-adjust`, outlined and shadowed text, solid background layers and drop shadows it used to ask about. A placeholder whose colors the page chose fails below the ratio; in the browser's own colors it isn't reported.
|
|
562
|
+
- **Roles, names and hidden content follow browsers more closely**, among them `aria-allowed-attr` on a text input with a `<datalist>` (a combobox) and on `<td>`, every associated `<label>` joined into a name, and `hidden` that the page's CSS displays again hiding nothing.
|
|
563
|
+
- **A selector at the top of a shadow root** is now written so it can't match a sibling outside it (`img:not(* > *)`), so the selector a result gives, and `elementRef(true)`, point at the right element.
|
|
564
|
+
- **Some reason codes are split by cause** (`LIST_ITEM_ROLE_OVERRIDDEN`, `LIST_ROLE_OVERRIDDEN`, `DUPLICATE_ID_IN_SHADOW_TREE`, `DEFAULT_LANG_INVALID`, `IMAGE_ONLY_CONTROL_CONTENT`, `HEADING_LIKE_NUMBER`, `HEADING_LIKE_LINK`). Core's baselines still match a 1.13 entry to its finding under the new code, and `migrateBaselineEntries()` rewrites a baseline; see core's [`BASELINE.md`](https://github.com/SureA11y/core/blob/main/docs/BASELINE.md#upgrading).
|
|
419
565
|
|
|
420
566
|
## What changes with `@surea11y/core` 1.12
|
|
421
567
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@surea11y/playwright",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Accessibility (a11y, WCAG) checks for Playwright tests: scan the live page with new A11yCoreBuilder({ page }).analyze() and get only proven violations, with findings that need human review listed separately.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"accessibility",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"LICENSE"
|
|
47
47
|
],
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@surea11y/binding-base": "^1.
|
|
50
|
-
"@surea11y/core": "^1.
|
|
49
|
+
"@surea11y/binding-base": "^1.6.0",
|
|
50
|
+
"@surea11y/core": "^1.14.0"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"playwright": ">=1.0.0"
|
package/src/A11yCoreBuilder.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Page, BrowserContext, ElementHandle } from 'playwright';
|
|
1
|
+
import type { Page, BrowserContext, ElementHandle, Frame } from 'playwright';
|
|
2
2
|
import type * as Core from '@surea11y/core';
|
|
3
3
|
|
|
4
4
|
// The result shapes are @surea11y/core's own types (shipped with it since
|
|
@@ -25,7 +25,9 @@ import type {
|
|
|
25
25
|
Margin,
|
|
26
26
|
MarginDeclaration,
|
|
27
27
|
ContextMatch,
|
|
28
|
-
CompositeResult
|
|
28
|
+
CompositeResult,
|
|
29
|
+
Lean,
|
|
30
|
+
HowToCheck
|
|
29
31
|
} from '@surea11y/core';
|
|
30
32
|
|
|
31
33
|
export type {
|
|
@@ -44,7 +46,9 @@ export type {
|
|
|
44
46
|
Margin,
|
|
45
47
|
MarginDeclaration,
|
|
46
48
|
ContextMatch,
|
|
47
|
-
CompositeResult
|
|
49
|
+
CompositeResult,
|
|
50
|
+
Lean,
|
|
51
|
+
HowToCheck
|
|
48
52
|
};
|
|
49
53
|
|
|
50
54
|
/**
|
|
@@ -67,9 +71,13 @@ export type {
|
|
|
67
71
|
ScreenshotOptions,
|
|
68
72
|
ScreenshotSkip,
|
|
69
73
|
ScreenshotBox,
|
|
70
|
-
OccurrenceScreenshot
|
|
74
|
+
OccurrenceScreenshot,
|
|
75
|
+
LocatedAnnouncement,
|
|
76
|
+
ReviewGroup
|
|
71
77
|
} from '@surea11y/binding-base';
|
|
72
78
|
import type {
|
|
79
|
+
LocatedAnnouncement,
|
|
80
|
+
ReviewGroup,
|
|
73
81
|
PackLike,
|
|
74
82
|
WcagVersion,
|
|
75
83
|
WcagLevelInput,
|
|
@@ -87,6 +95,8 @@ export type CheckResultMeta = Core.RuleMeta;
|
|
|
87
95
|
export type CompositeResultDetails = Core.CompositeResult['data']['details'];
|
|
88
96
|
|
|
89
97
|
export interface Occurrence extends Core.Occurrence {
|
|
98
|
+
/** With .conditions(): the conditions it was found under, 'default' for the page as it was. */
|
|
99
|
+
conditions?: string[];
|
|
90
100
|
/**
|
|
91
101
|
* Only present when `.elementRef(true)` was used. `null` when this
|
|
92
102
|
* occurrence has no single resolvable target element (e.g. `selector` was
|
|
@@ -107,6 +117,8 @@ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
|
|
|
107
117
|
|
|
108
118
|
/** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
|
|
109
119
|
export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
|
|
120
|
+
/** With .conditions(): each scan's condition ('default' first) and environment. */
|
|
121
|
+
conditionRuns?: Array<{ condition: string; environment: Record<string, unknown> | null }>;
|
|
110
122
|
checksResults: CheckResult[];
|
|
111
123
|
}
|
|
112
124
|
|
|
@@ -162,6 +174,30 @@ export class A11yCoreBuilder {
|
|
|
162
174
|
*/
|
|
163
175
|
static installInternalsHook(pageOrContext: Page | BrowserContext): Promise<void>;
|
|
164
176
|
|
|
177
|
+
/**
|
|
178
|
+
* Installs @surea11y/core's opt-in listener hook on a Page, or on a
|
|
179
|
+
* BrowserContext for every page it opens, so the keyboard rules see the
|
|
180
|
+
* event listeners the page adds from script. Call it before page.goto().
|
|
181
|
+
* Needs @surea11y/core 1.14.0 or later.
|
|
182
|
+
*/
|
|
183
|
+
static installListenerHook(pageOrContext: Page | BrowserContext): Promise<void>;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Installs @surea11y/core's opt-in live-region hook on a Page, or on a
|
|
187
|
+
* BrowserContext for every page it opens, which records what its live
|
|
188
|
+
* regions are given. Call it before page.goto(). Needs @surea11y/core
|
|
189
|
+
* 1.14.0 or later.
|
|
190
|
+
*/
|
|
191
|
+
static installLiveRegionHook(pageOrContext: Page | BrowserContext): Promise<void>;
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* What `page`'s live regions were given since it loaded, in order, each
|
|
195
|
+
* region named by its selector; null without the live-region hook. Texts
|
|
196
|
+
* given to a region behind an open modal dialog only with
|
|
197
|
+
* `includeBehindModal: true`.
|
|
198
|
+
*/
|
|
199
|
+
static announcements(page: Page, options?: { includeBehindModal?: boolean }): Promise<LocatedAnnouncement[] | null>;
|
|
200
|
+
|
|
165
201
|
/** Scope the scan to one region. Call multiple times for a multi-region union. */
|
|
166
202
|
include(selector: string): this;
|
|
167
203
|
/**
|
|
@@ -202,7 +238,8 @@ export class A11yCoreBuilder {
|
|
|
202
238
|
/**
|
|
203
239
|
* Where analyze() sends each scan gap instead of console.warn: called once
|
|
204
240
|
* per gap, with the result of the frame it came from, and once per scan
|
|
205
|
-
* for the internals-hook
|
|
241
|
+
* for each of the internals-hook and listener-hook notes (tell them apart
|
|
242
|
+
* by `kind`). `() => {}`
|
|
206
243
|
* silences them, `null` goes back to console.warn. A later call replaces it.
|
|
207
244
|
*/
|
|
208
245
|
logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
|
|
@@ -219,6 +256,15 @@ export class A11yCoreBuilder {
|
|
|
219
256
|
reportOnly(outcomes: Outcome | Outcome[]): this;
|
|
220
257
|
/** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
|
|
221
258
|
frames(enabled?: boolean): this;
|
|
259
|
+
/**
|
|
260
|
+
* Also scan the page under each condition after scanning it as it is
|
|
261
|
+
* (@surea11y/binding-base 1.6.0): a color scheme, a viewport width, or
|
|
262
|
+
* both. analyze() returns one merged result: a rule's outcome is its worst
|
|
263
|
+
* across the scans, each occurrence lists the `conditions` it appeared
|
|
264
|
+
* under, and `conditionRuns` gives each scan's environment. The viewport
|
|
265
|
+
* and scheme are put back afterwards. Not combined with frames(true) yet.
|
|
266
|
+
*/
|
|
267
|
+
conditions(list: ReadonlyArray<ScanCondition> | null): this;
|
|
222
268
|
/** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
|
|
223
269
|
elementRef(enabled?: boolean): this;
|
|
224
270
|
/**
|
|
@@ -228,6 +274,12 @@ export class A11yCoreBuilder {
|
|
|
228
274
|
* it can't use.
|
|
229
275
|
*/
|
|
230
276
|
screenshots(options?: ScreenshotOptions | boolean): this;
|
|
277
|
+
/**
|
|
278
|
+
* Fetch, from Node, the style sheets the page can't read (another origin's)
|
|
279
|
+
* and give core their text, so checks that read the CSS can check them. On
|
|
280
|
+
* by default; needs @surea11y/core 1.14.0 or later.
|
|
281
|
+
*/
|
|
282
|
+
fetchStyleSheets(enabled?: boolean): this;
|
|
231
283
|
/** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
|
|
232
284
|
plannedChecks(): PlannedCheck[];
|
|
233
285
|
/** The criteria this scan will report in rulesResults, worked out in Node with no page. */
|
|
@@ -249,15 +301,35 @@ export class A11yCoreBuilder {
|
|
|
249
301
|
* `expect(results.checksResults, formatFailures(results)).toEqual([])`.
|
|
250
302
|
* Given the whole result, it also lists what the scan left out
|
|
251
303
|
* (getScanGaps()) and ends with the @surea11y/core release that produced
|
|
252
|
-
* it.
|
|
253
|
-
*
|
|
254
|
-
*
|
|
304
|
+
* it. Occurrences are listed in the order a review takes: failures, then
|
|
305
|
+
* questions that likely fail, likely pass, and are open, each question
|
|
306
|
+
* with its lean. `outcomes` narrows by outcome or review group,
|
|
307
|
+
* `howToCheck: true` adds each question's steps. Throws a TypeError for a
|
|
308
|
+
* frames(true) result: format `topFrame` and each frame on its own.
|
|
309
|
+
* Deliberately framework-agnostic -- no dependency on any particular
|
|
310
|
+
* `expect` implementation.
|
|
255
311
|
*/
|
|
256
312
|
export function formatFailures(
|
|
257
313
|
input: A11yCoreResult | ReadonlyArray<CheckResult>,
|
|
258
|
-
opts?: { outcomes?: Outcome
|
|
314
|
+
opts?: { outcomes?: Array<Outcome | ReviewGroup>; howToCheck?: boolean; failOnSeverity?: Severity }
|
|
259
315
|
): string;
|
|
260
316
|
|
|
317
|
+
/** The four severities, least to most severe (@surea11y/binding-base 1.6.0 and later). */
|
|
318
|
+
export const SEVERITIES: ReadonlyArray<Severity>;
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The failing rule results that should fail a test: every `fail`, or with
|
|
322
|
+
* `failOnSeverity` only those whose severity is that level or above, as
|
|
323
|
+
* `surea11y scan --fail-on-severity` counts them. `fail` keeps its meaning;
|
|
324
|
+
* the level only picks which failures stop the test. Throws a TypeError for
|
|
325
|
+
* a level that is not a severity. From @surea11y/binding-base 1.6.0.
|
|
326
|
+
*/
|
|
327
|
+
export function getGatingFailures(
|
|
328
|
+
input: A11yCoreResult | ReadonlyArray<CheckResult>,
|
|
329
|
+
opts?: { failOnSeverity?: Severity }
|
|
330
|
+
): CheckResult[];
|
|
331
|
+
|
|
332
|
+
|
|
261
333
|
/**
|
|
262
334
|
* What a scan result says it left out, which its checksResults alone would
|
|
263
335
|
* pass over as clean: an include() scope that matched no element
|
|
@@ -273,8 +345,17 @@ export type { ScanGap, OccurrenceLocation } from '@surea11y/binding-base';
|
|
|
273
345
|
|
|
274
346
|
/**
|
|
275
347
|
* How the page was scanned, which a gap doesn't cover: `forced-colors` when
|
|
276
|
-
* the page was shown in forced colors,
|
|
277
|
-
* asked about web components it could have read with the internals hook
|
|
348
|
+
* the page was shown in forced colors, `internals-hook` when the scan
|
|
349
|
+
* asked about web components it could have read with the internals hook,
|
|
350
|
+
* and `listener-hook` when it asked about click or pointer handlers whose
|
|
351
|
+
* keyboard equivalent the listener hook would have let it see.
|
|
278
352
|
*/
|
|
279
353
|
export { getScanNotes } from '@surea11y/binding-base';
|
|
280
354
|
export type { ScanNote } from '@surea11y/binding-base';
|
|
355
|
+
|
|
356
|
+
/** A condition to scan the page under with .conditions(). */
|
|
357
|
+
export interface ScanCondition {
|
|
358
|
+
colorScheme?: 'light' | 'dark';
|
|
359
|
+
/** The viewport's width in CSS pixels; its height is kept. */
|
|
360
|
+
width?: number;
|
|
361
|
+
}
|
package/src/A11yCoreBuilder.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
3
|
+
const core = require('@surea11y/core');
|
|
4
|
+
|
|
5
|
+
const { runa11yCoreInPage, internalsHookScript } = core;
|
|
4
6
|
const {
|
|
5
7
|
A11yCoreBuilderBase,
|
|
6
8
|
createInPageScan,
|
|
@@ -176,6 +178,53 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
176
178
|
return pageOrContext.addInitScript({ content: internalsHookScript() });
|
|
177
179
|
}
|
|
178
180
|
|
|
181
|
+
/**
|
|
182
|
+
* Installs @surea11y/core's opt-in listener hook, so the keyboard rules
|
|
183
|
+
* see the event listeners the page adds from script (`addEventListener`,
|
|
184
|
+
* `el.onclick = fn`), which no page script can list. Without it a
|
|
185
|
+
* `<div role="button">` given a click listener from script goes
|
|
186
|
+
* unjudged. Takes a Page, or a BrowserContext to cover every page it
|
|
187
|
+
* opens. Call it before page.goto(), as installInternalsHook(). Needs
|
|
188
|
+
* @surea11y/core 1.14.0 or later. Resolves when the script is added.
|
|
189
|
+
* @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
|
|
190
|
+
*/
|
|
191
|
+
static installListenerHook(pageOrContext) {
|
|
192
|
+
return installHook(pageOrContext, 'installListenerHook', 'listenerHookScript');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Installs @surea11y/core's opt-in live-region hook, which records what
|
|
197
|
+
* the page's live regions are given while it runs: the scan then asks
|
|
198
|
+
* about a region added with its text already in it, and
|
|
199
|
+
* A11yCoreBuilder.announcements(page) returns what the page made
|
|
200
|
+
* available to announce. Takes a Page, or a BrowserContext to cover every
|
|
201
|
+
* page it opens. Call it before page.goto(), as installInternalsHook().
|
|
202
|
+
* Needs @surea11y/core 1.14.0 or later.
|
|
203
|
+
* @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
|
|
204
|
+
*/
|
|
205
|
+
static installLiveRegionHook(pageOrContext) {
|
|
206
|
+
return installHook(pageOrContext, 'installLiveRegionHook', 'liveRegionHookScript');
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* What `page`'s live regions were given since it loaded, as the
|
|
211
|
+
* live-region hook recorded it, in order: `[{ text, politeness, time,
|
|
212
|
+
* order, behindModal, selector }]`, each region named by its selector (and
|
|
213
|
+
* `shadowHostSelectors` inside a shadow root; null for a region that has
|
|
214
|
+
* since left the page). null where installLiveRegionHook() wasn't called
|
|
215
|
+
* before the page loaded. What the page made available to announce, not
|
|
216
|
+
* what a screen reader said. A text given to a region behind an open
|
|
217
|
+
* modal dialog, which assistive technology did not get, is listed only
|
|
218
|
+
* with `{ includeBehindModal: true }`, marked `behindModal`. Needs
|
|
219
|
+
* @surea11y/core 1.14.0 or later.
|
|
220
|
+
* @param {import('playwright').Page} page
|
|
221
|
+
* @param {{ includeBehindModal?: boolean }} [options]
|
|
222
|
+
* @returns {Promise<Array<object>|null>}
|
|
223
|
+
*/
|
|
224
|
+
static announcements(page, options) {
|
|
225
|
+
return new A11yCoreBuilder({ page })._announcementsIn(page, options);
|
|
226
|
+
}
|
|
227
|
+
|
|
179
228
|
/**
|
|
180
229
|
* @param {{ page: import('playwright').Page, url?: string }} opts
|
|
181
230
|
* `page` must already be navigated to and settled at the URL to scan --
|
|
@@ -211,10 +260,16 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
211
260
|
const runInFrame = async (frameOrPage, frameContextSelector) => {
|
|
212
261
|
const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
|
|
213
262
|
if (packScript) await frameOrPage.evaluate(packScript);
|
|
263
|
+
// The text of the style sheets the frame can't read, fetched from Node
|
|
264
|
+
// (binding-base 1.6.0 and core 1.14.0; nothing with older ones).
|
|
265
|
+
const frameEngineOptions =
|
|
266
|
+
typeof this._styleSheetEngineOptions === 'function'
|
|
267
|
+
? await this._styleSheetEngineOptions(frameOrPage, engineOptions)
|
|
268
|
+
: engineOptions;
|
|
214
269
|
const result = rethrowEngineError(await frameOrPage.evaluate(scanInPage, {
|
|
215
270
|
url: frameUrl,
|
|
216
271
|
contextSelector: frameContextSelector,
|
|
217
|
-
engineOptions,
|
|
272
|
+
engineOptions: frameEngineOptions,
|
|
218
273
|
runOnly
|
|
219
274
|
}));
|
|
220
275
|
this._warnScanGaps(result, '@surea11y/playwright');
|
|
@@ -224,6 +279,14 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
224
279
|
return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
|
|
225
280
|
};
|
|
226
281
|
|
|
282
|
+
// .conditions() (binding-base 1.6.0): the page as it is, then under each
|
|
283
|
+
// condition, merged into one result.
|
|
284
|
+
if (this._conditions) {
|
|
285
|
+
return this._applyReportOnly(
|
|
286
|
+
await this._scanUnderConditions(() => runInFrame(this._page, contextSelector), this._conditionDriver())
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
227
290
|
if (!this._scanFrames) {
|
|
228
291
|
return this._applyReportOnly(await runInFrame(this._page, contextSelector));
|
|
229
292
|
}
|
|
@@ -259,6 +322,51 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
259
322
|
return { topFrame, frames };
|
|
260
323
|
}
|
|
261
324
|
|
|
325
|
+
/**
|
|
326
|
+
* The driver steps .conditions() scans need: the viewport's width with
|
|
327
|
+
* page.setViewportSize() (its height kept) and the color scheme with
|
|
328
|
+
* page.emulateMedia(). Each condition sets both, from the page as it was,
|
|
329
|
+
* so one condition's width or scheme doesn't carry into the next; at the
|
|
330
|
+
* end the viewport goes back, and if a condition set a scheme, the page
|
|
331
|
+
* is left in the scheme it had before (a scheme emulated by the caller, or
|
|
332
|
+
* the system's). The scheme is set back by name, not cleared with null:
|
|
333
|
+
* WebKit keeps a dark emulation that null should clear.
|
|
334
|
+
*/
|
|
335
|
+
_conditionDriver() {
|
|
336
|
+
const page = this._page;
|
|
337
|
+
let schemeSet = false;
|
|
338
|
+
let viewport = null;
|
|
339
|
+
// The scheme a condition without one goes back to.
|
|
340
|
+
let baseScheme = 'light';
|
|
341
|
+
return {
|
|
342
|
+
save: async () => {
|
|
343
|
+
const before = await page.evaluate(() => ({
|
|
344
|
+
width: innerWidth,
|
|
345
|
+
height: innerHeight,
|
|
346
|
+
dark: matchMedia('(prefers-color-scheme: dark)').matches
|
|
347
|
+
}));
|
|
348
|
+
viewport = page.viewportSize() || { width: before.width, height: before.height };
|
|
349
|
+
baseScheme = before.dark ? 'dark' : 'light';
|
|
350
|
+
return { viewport };
|
|
351
|
+
},
|
|
352
|
+
apply: async (condition) => {
|
|
353
|
+
await page.setViewportSize({ width: condition.width || viewport.width, height: viewport.height });
|
|
354
|
+
if (condition.colorScheme) {
|
|
355
|
+
await page.emulateMedia({ colorScheme: condition.colorScheme });
|
|
356
|
+
schemeSet = true;
|
|
357
|
+
} else if (schemeSet) {
|
|
358
|
+
await page.emulateMedia({ colorScheme: baseScheme });
|
|
359
|
+
schemeSet = false;
|
|
360
|
+
}
|
|
361
|
+
},
|
|
362
|
+
restore: async (state) => {
|
|
363
|
+
if (!state) return;
|
|
364
|
+
await page.setViewportSize(state.viewport);
|
|
365
|
+
if (schemeSet) await page.emulateMedia({ colorScheme: baseScheme });
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
262
370
|
/**
|
|
263
371
|
* Resolves each occurrence to a live ElementHandle, scoped to
|
|
264
372
|
* frameOrPage's own document (a Playwright Page and Frame both expose the
|
|
@@ -309,6 +417,19 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
309
417
|
* array (an element handle inside it arrives as the element) and are
|
|
310
418
|
* spread in the page.
|
|
311
419
|
*/
|
|
420
|
+
/**
|
|
421
|
+
* For binding-base's style sheet step: fetch with the page's own request
|
|
422
|
+
* API, which carries its cookies, in the shape of fetch().
|
|
423
|
+
*/
|
|
424
|
+
get _styleSheetFetch() {
|
|
425
|
+
const request = this._page && typeof this._page.request === 'object' ? this._page.request : null;
|
|
426
|
+
if (!request || typeof request.get !== 'function') return null;
|
|
427
|
+
return async (url) => {
|
|
428
|
+
const res = await request.get(url, { timeout: 5000 });
|
|
429
|
+
return { ok: res.ok(), text: () => res.text() };
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
312
433
|
_evaluateInFrame(frameOrPage, fn, args) {
|
|
313
434
|
// eslint-disable-next-line no-new-func
|
|
314
435
|
return frameOrPage.evaluate(new Function('args', 'return (' + fn.toString() + ')(...args)'), args);
|
|
@@ -333,4 +454,17 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
333
454
|
}
|
|
334
455
|
}
|
|
335
456
|
|
|
457
|
+
// One of core's hook scripts (1.14.0 and later for the listener and
|
|
458
|
+
// live-region hooks), added as an init script, which runs before the page's
|
|
459
|
+
// own scripts.
|
|
460
|
+
function installHook(pageOrContext, method, scriptName) {
|
|
461
|
+
if (!pageOrContext || typeof pageOrContext.addInitScript !== 'function') {
|
|
462
|
+
throw new TypeError(`A11yCoreBuilder.${method}() requires a Playwright Page or BrowserContext (with an .addInitScript() method).`);
|
|
463
|
+
}
|
|
464
|
+
if (typeof core[scriptName] !== 'function') {
|
|
465
|
+
throw new Error(`A11yCoreBuilder.${method}() needs @surea11y/core 1.14.0 or later, which has ${scriptName}().`);
|
|
466
|
+
}
|
|
467
|
+
return pageOrContext.addInitScript({ content: core[scriptName]() });
|
|
468
|
+
}
|
|
469
|
+
|
|
336
470
|
module.exports = { A11yCoreBuilder };
|
package/src/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { EngineError, getScanGaps, getScanNotes, formatOccurrenceLocation } = require('@surea11y/binding-base');
|
|
3
|
+
const { EngineError, getScanGaps, getScanNotes, formatOccurrenceLocation, getGatingFailures, SEVERITIES } = require('@surea11y/binding-base');
|
|
4
4
|
const { A11yCoreBuilder } = require('./A11yCoreBuilder');
|
|
5
5
|
const { formatFailures } = require('./formatFailures');
|
|
6
6
|
|
|
7
|
-
module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps, getScanNotes };
|
|
7
|
+
module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps, getScanNotes, getGatingFailures, SEVERITIES };
|