a11y.e2e.ts
This file
Path
apps/web/e2e/a11y.e2e.ts
682 lines · 20.3 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
1import { expect, test } from "@playwright/test";2import type { Browser, BrowserContext, Page } from "@playwright/test";3import { Brand } from "@repo/brand";4import { Config, Effect, Option } from "effect";56import { axeOn, sideways } from "./axe.ts";78const settings = Effect.runSync(9 Effect.gen(function* () {10 return {11 project: yield* Config.NonEmptyString("A11Y_PROJECT").pipe(12 Config.withDefault("oscabriel/vellum")13 ),14 web: Option.map(15 yield* Config.option(Config.NonEmptyString("WEB_URL")),16 (url) => url.replace(/\/+$/u, "")17 ),18 };19 })20);2122const { project } = settings;2324const at = (path: string) =>25 `${Option.getOrElse(settings.web, () => "")}${path}`;2627const DECIDER = "ines-v";2829interface Visit {30 readonly name: string;31 readonly path: string;32 readonly signedIn?: boolean;33 readonly status?: number;34}3536// Its SHA is the dev world's, so it is found at run time from the landings page.37const COMMIT = "<the newest ask opening>";3839const VISITS: readonly Visit[] = [40 { name: "landing", path: "/" },41 { name: "front", path: "/asks" },42 { name: "front, signed in", path: "/asks", signedIn: true },43 { name: "inbox", path: "/inbox", signedIn: true },44 { name: "inbox, signed out", path: "/inbox" },45 { name: "project home", path: `/${project}` },46 { name: "project home, examples", path: "/oscabriel/burrow" },47 { name: "project home, no open asks", path: "/lin-h/mossgate" },48 { name: "ask, open", path: `/${project}/asks/lint-heading-levels` },49 {50 name: "ask, held for newcomers",51 path: `/${project}/asks/document-cli-flags`,52 },53 { name: "ask, claimed", path: `/${project}/asks/number-footnotes` },54 { name: "ask, a family", path: `/${project}/asks/retire-old-tokenizer` },55 {56 name: "answer, checking",57 path: `/${project}/answers/retire-old-tokenizer-vellum-lint`,58 },59 {60 name: "answer, waiting on a finish",61 path: `/${project}/answers/wrap-long-table-cells`,62 },63 {64 name: "answer, refused",65 path: `/${project}/answers/trim-trailing-spaces`,66 },67 {68 name: "answer, held back",69 path: `/${project}/answers/retire-old-tokenizer-vellum-parser`,70 },71 {72 name: "answer, landed",73 path: `/${project}/answers/carry-footnotes-to-epub`,74 },75 {76 name: "answer, unclaimed",77 path: `/${project}/answers/lint-heading-levels`,78 },79 { name: "visibility", path: `/${project}/visibility` },80 { name: "policy", path: `/${project}/people` },81 { name: "refs", path: `/${project}/refs` },82 { name: "tree", path: `/${project}/tree/main` },83 { name: "folder", path: `/${project}/tree/main/packages/render/src` },84 { name: "blob", path: `/${project}/blob/main/packages/render/src/page.ts` },85 { name: "why", path: `/${project}/why/main/packages/render/src/page.ts` },86 { name: "landings", path: `/${project}/commits/main` },87 { name: "commit", path: COMMIT },88 {89 name: "decision",90 path: `/${project}/decisions/dec-000002`,91 signedIn: true,92 },93 {94 name: "decision, signed out",95 path: `/${project}/decisions/dec-000002`,96 },97 { name: "finish", path: `/${project}/decisions/dec-000004`, signedIn: true },98 { name: "proposal, ready", path: `/${project}/proposals/prop-000002` },99 { name: "proposal, failed", path: `/${project}/proposals/prop-000003` },100 {101 name: "propose",102 path: `/${project}/proposals/new`,103 signedIn: true,104 },105 { name: "propose, signed out", path: `/${project}/proposals/new` },106 { name: "person", path: `/people/${DECIDER}` },107 { name: "install", path: "/install" },108 { name: "unknown project", path: "/no-such-project", status: 404 },109 {110 name: "unknown ask",111 path: `/${project}/asks/no-such-ask`,112 status: 404,113 },114 {115 name: "unknown path",116 path: `/${project}/blob/main/no/such/file.ts`,117 status: 404,118 },119];120121const SCHEMES = ["light", "dark"] as const;122123const WIDTHS = [1440, 390] as const;124125// Matched whole and in any case: "merged tree" passes, "merge" does not.126const FORBIDDEN =127 /\b(?:review|reviewer|approve|approval|PR|pull request|issue|merge|lease|reputation|inbox|queue|dashboard|explore|trending|nit)\b/iu;128129// Text a repository or a person wrote, which its view marks; the forbidden words are not looked for there.130const NOT_OURS =131 "[data-readme], [data-code], [data-diff], [data-said], [data-refusal], [data-term], script, style, noscript";132133const contextFor = (134 browser: Browser,135 scheme: (typeof SCHEMES)[number],136 width: number,137 signedIn: boolean138) =>139 Effect.gen(function* () {140 const context = yield* Effect.promise(() =>141 browser.newContext({142 colorScheme: scheme,143 viewport: { height: width > 800 ? 900 : 844, width },144 })145 );146147 if (signedIn) {148 const page = yield* Effect.promise(() => context.newPage());149150 yield* Effect.promise(() => page.goto(at(`/auth/dev?handle=${DECIDER}`)));151152 yield* Effect.promise(() => page.close());153 }154155 return context;156 });157158const commitPath = (context: BrowserContext) =>159 Effect.gen(function* () {160 const page = yield* Effect.promise(() => context.newPage());161162 yield* Effect.promise(() => page.goto(at(`/${project}/commits/main`)));163164 const href = yield* Effect.promise(() =>165 page166 .locator(`a[href^="/${project}/commit/"]`, { hasText: "Open ask" })167 .first()168 .getAttribute("href")169 );170171 yield* Effect.promise(() => page.close());172173 return href ?? `/${project}/commits/main`;174 });175176const open = (page: Page, path: string) =>177 Effect.gen(function* () {178 const response = yield* Effect.promise(() =>179 page.goto(at(path), { waitUntil: "load" })180 );181182 // The page hydrates, then its client reads settle.183 yield* Effect.promise(() => page.waitForTimeout(1500));184185 return response?.status();186 });187188const forbiddenOn = (page: Page) =>189 Effect.promise(() =>190 page.evaluate(191 ({ forbidden, notOurs }) => {192 const pattern = new RegExp(forbidden, "iu");193194 const walker = document.createTreeWalker(195 document.body,196 NodeFilter.SHOW_TEXT197 );198199 const found: string[] = [];200201 for (202 let node = walker.nextNode();203 node !== null;204 node = walker.nextNode()205 ) {206 const parent = node.parentElement;207 const text = node.textContent ?? "";208209 if (210 parent !== null &&211 parent.closest(notOurs) === null &&212 parent.checkVisibility() &&213 pattern.test(text)214 ) {215 found.push(text.trim().slice(0, 80));216 }217 }218219 return found;220 },221 { forbidden: FORBIDDEN.source, notOurs: NOT_OURS }222 )223 );224225test.describe("every page, by axe, at two widths, in both schemes", () => {226 test.skip(227 Option.isNone(settings.web),228 "WEB_URL is not set: point it at the web's dev world, with its fixtures"229 );230231 for (const visit of VISITS) {232 test(`${visit.name}: no serious violation, no sideways scroll, no forbidden word`, ({233 browser,234 }) =>235 Effect.runPromise(236 Effect.gen(function* () {237 const problems: string[] = [];238239 for (const scheme of SCHEMES) {240 for (const width of WIDTHS) {241 const context = yield* contextFor(242 browser,243 scheme,244 width,245 visit.signedIn === true246 );247248 const path =249 visit.path === COMMIT ? yield* commitPath(context) : visit.path;250251 const page = yield* Effect.promise(() => context.newPage());252 const status = yield* open(page, path);253 const where = `${scheme} ${width} ${path}`;254255 if (status !== (visit.status ?? 200)) {256 problems.push(`${where}: answered ${status}`);257 }258259 for (const violation of yield* axeOn(page)) {260 problems.push(`${where}: ${violation}`);261 }262263 const over = yield* sideways(page);264265 if (over > 0) {266 problems.push(`${where}: scrolls ${over}px sideways`);267 }268269 if (width === 390) {270 yield* Effect.promise(() =>271 page.setViewportSize({ height: 780, width: 360 })272 );273274 const narrow = yield* sideways(page);275276 if (narrow > 0) {277 problems.push(278 `${where} at 360: scrolls ${narrow}px sideways`279 );280 }281 }282283 for (const words of yield* forbiddenOn(page)) {284 problems.push(`${where}: forbidden word in "${words}"`);285 }286287 yield* Effect.promise(() => context.close());288 }289 }290291 expect(problems).toStrictEqual([]);292 })293 ));294 }295});296297const focused = (page: Page) =>298 Effect.promise(() =>299 page.evaluate(() => {300 // Focus inside a drawing's shadow root (a code box, the file tree) is301 // the inner element's own; where it sits is its host's place.302 const { activeElement: host } = document;303304 let element = host;305306 while (element?.shadowRoot?.activeElement) {307 element = element.shadowRoot.activeElement;308 }309310 if (!(element instanceof HTMLElement) || element === document.body) {311 return null;312 }313314 const style = getComputedStyle(element);315 const after = getComputedStyle(element, "::after");316317 const places = [318 ["[role=dialog]", "dialog"],319 ["nav[aria-label=Site]", "rail"],320 ["[data-toolbar]", "toolbar"],321 ["aside[aria-label=Facts]", "facts"],322 ["main li", "row"],323 ] as const;324325 return {326 id: element.id,327 inside:328 places.find(([selector]) => host?.closest(selector) !== null)?.[1] ??329 "main",330 label: (element.getAttribute("aria-label") ?? element.textContent ?? "")331 .trim()332 .slice(0, 60),333 tag: element.tagName.toLowerCase(),334 visible:335 (style.outlineStyle !== "none" && style.outlineWidth !== "0px") ||336 (after.outlineStyle !== "none" && after.outlineWidth !== "0px") ||337 style.boxShadow !== "none",338 };339 })340 );341342// `settle` waits after each press: a sheet's focus trap moves focus in the next frame.343const tabStops = (page: Page, limit: number, settle = 0) =>344 Effect.gen(function* () {345 const stops: NonNullable<Effect.Success<ReturnType<typeof focused>>>[] = [];346347 for (let index = 0; index < limit; index += 1) {348 yield* Effect.promise(() => page.keyboard.press("Tab"));349350 if (settle > 0) {351 yield* Effect.promise(() => page.waitForTimeout(settle));352 }353354 const stop = yield* focused(page);355356 if (stop === null) {357 break;358 }359360 stops.push(stop);361 }362363 return stops;364 });365366const keyboardPage = (367 browser: Browser,368 path: string,369 width: number,370 signedIn = false371) =>372 Effect.gen(function* () {373 const context = yield* contextFor(browser, "light", width, signedIn);374375 yield* Effect.promise(() =>376 context.grantPermissions(["clipboard-read", "clipboard-write"], {377 origin: at("/"),378 })379 );380381 const page = yield* Effect.promise(() => context.newPage());382383 yield* open(page, path === COMMIT ? yield* commitPath(context) : path);384385 return { context, page };386 });387388const searchOf = (page: Page) => new URL(page.url()).searchParams;389390test.describe("the keyboard", () => {391 test.skip(392 Option.isNone(settings.web),393 "WEB_URL is not set: point it at the web's dev world, with its fixtures"394 );395396 test("the skip link comes first, lands on main, and every stop shows its focus", ({397 browser,398 }) => {399 test.setTimeout(VISITS.length * 30_000);400401 return Effect.runPromise(402 Effect.gen(function* () {403 const problems: string[] = [];404405 for (const visit of VISITS) {406 const { context, page } = yield* keyboardPage(407 browser,408 visit.path,409 1440,410 visit.signedIn === true411 );412413 yield* Effect.promise(() => page.keyboard.press("Tab"));414415 const first = yield* focused(page);416417 if (first?.label !== "Skip to content") {418 problems.push(`${visit.name}: first stop is ${first?.label}`);419 }420421 yield* Effect.promise(() => page.keyboard.press("Enter"));422423 const landed = yield* Effect.promise(() =>424 page.evaluate(() => {425 const active = document.activeElement;426427 return (428 active?.id === "main" ||429 (active !== null && active.closest("#main") !== null)430 );431 })432 );433434 if (!landed || !page.url().endsWith("#main")) {435 problems.push(`${visit.name}: the skip link does not land on main`);436 }437438 const stops = yield* tabStops(page, 80);439440 for (const stop of stops.filter(({ visible }) => !visible)) {441 problems.push(442 `${visit.name}: no visible focus on ${stop.tag} "${stop.label}"`443 );444 }445446 yield* Effect.promise(() => context.close());447 }448449 expect(problems).toStrictEqual([]);450 })451 );452 });453454 test("the rail, the toolbar's filters, a row's copy button and the inspector's commands come in order", ({455 browser,456 }) =>457 Effect.runPromise(458 Effect.gen(function* () {459 const { context, page } = yield* keyboardPage(browser, "/asks", 1440);460461 yield* Effect.promise(() => page.keyboard.press("j"));462 yield* Effect.promise(() => page.waitForTimeout(500));463 yield* open(464 page,465 new URL(page.url()).pathname + new URL(page.url()).search466 );467468 const stops = yield* tabStops(page, 200);469470 const first = (inside: string) =>471 stops.findIndex((stop) => stop.inside === inside);472473 const copy = stops.findIndex(474 (stop) => stop.inside === "row" && stop.label.startsWith("Copy")475 );476477 const order = {478 facts: first("facts"),479 rail: first("rail"),480 rowCopy: copy,481 toolbar: first("toolbar"),482 };483484 expect(Object.values(order).every((index) => index >= 0)).toBe(true);485 expect(order.rail).toBeLessThan(order.toolbar);486 expect(order.toolbar).toBeLessThan(order.rowCopy);487 expect(order.rowCopy).toBeLessThan(order.facts);488489 yield* Effect.promise(() => context.close());490 })491 ));492493 test("? opens the keys, whose switch turns j and k off; j and k move the selection", ({494 browser,495 }) =>496 Effect.runPromise(497 Effect.gen(function* () {498 for (const [path, param, signedIn] of [499 ["/asks", "ask", false],500 ["/inbox", "decision", true],501 ] as const) {502 const { context, page } = yield* keyboardPage(503 browser,504 path,505 1440,506 signedIn507 );508509 yield* Effect.promise(() => page.keyboard.press("j"));510 yield* Effect.promise(() => page.waitForTimeout(400));511512 const firstSelected = searchOf(page).get(param);513514 expect(firstSelected).not.toBeNull();515516 yield* Effect.promise(() => page.keyboard.press("j"));517 yield* Effect.promise(() => page.waitForTimeout(400));518519 const second = searchOf(page).get(param);520521 expect(second).not.toBe(firstSelected);522523 yield* Effect.promise(() => page.keyboard.press("k"));524 yield* Effect.promise(() => page.waitForTimeout(400));525526 expect(searchOf(page).get(param)).toBe(firstSelected);527528 yield* Effect.promise(() => page.keyboard.press("?"));529530 const dialog = page.getByRole("dialog", { name: "Keys" });531532 yield* Effect.promise(() => expect(dialog).toBeVisible());533 yield* Effect.promise(() =>534 dialog.getByRole("button", { name: "Off" }).click()535 );536 yield* Effect.promise(() => page.keyboard.press("Escape"));537 yield* Effect.promise(() => expect(dialog).toBeHidden());538539 yield* Effect.promise(() => page.keyboard.press("j"));540 yield* Effect.promise(() => page.waitForTimeout(400));541542 expect(searchOf(page).get(param)).toBe(firstSelected);543544 yield* Effect.promise(() => page.keyboard.press("?"));545 yield* Effect.promise(() => expect(dialog).toBeVisible());546 yield* Effect.promise(() =>547 dialog.getByRole("button", { name: "On" }).click()548 );549 yield* Effect.promise(() => page.keyboard.press("Escape"));550 yield* Effect.promise(() => context.close());551 }552 })553 ));554555 test("1 copies the inspector's first command", ({ browser }) =>556 Effect.runPromise(557 Effect.gen(function* () {558 const { context, page } = yield* keyboardPage(browser, "/asks", 1440);559560 yield* Effect.promise(() => page.keyboard.press("j"));561 yield* Effect.promise(() => page.waitForTimeout(500));562 yield* Effect.promise(() => page.keyboard.press("1"));563 yield* Effect.promise(() => page.waitForTimeout(300));564565 const copied = yield* Effect.promise(() =>566 page.evaluate(() => navigator.clipboard.readText())567 );568569 const ask = searchOf(page).get("ask") ?? "";570571 const command = yield* Effect.promise(() =>572 page573 .locator(`li[data-ask="${ask}"] button code`)574 .first()575 .textContent()576 );577578 expect(copied).toMatch(new RegExp(`^${Brand.cli} claim ${ask} `, "u"));579 expect(copied).toBe(command);580581 yield* Effect.promise(() => context.close());582 })583 ));584585 test("J and K move between files on a commit and a finish", ({ browser }) =>586 Effect.runPromise(587 Effect.gen(function* () {588 for (const [path, signedIn] of [589 [COMMIT, false],590 [`/${project}/decisions/dec-000004`, true],591 ] as const) {592 const { context, page } = yield* keyboardPage(593 browser,594 path,595 1440,596 signedIn597 );598599 yield* Effect.promise(() => page.keyboard.press("Shift+J"));600 yield* Effect.promise(() => page.waitForTimeout(400));601602 const first = new URL(page.url()).hash;603604 expect(first).not.toBe("");605606 yield* Effect.promise(() => page.keyboard.press("Shift+J"));607 yield* Effect.promise(() => page.waitForTimeout(400));608609 const second = new URL(page.url()).hash;610611 expect(second).not.toBe(first);612613 yield* Effect.promise(() => page.keyboard.press("Shift+K"));614 yield* Effect.promise(() => page.waitForTimeout(400));615616 expect(new URL(page.url()).hash).toBe(first);617618 yield* Effect.promise(() => context.close());619 }620 })621 ));622623 test("each sheet keeps focus inside, and Escape gives it back to its button", ({624 browser,625 }) =>626 Effect.runPromise(627 Effect.gen(function* () {628 const sheets = [629 { button: "Menu", path: `/${project}`, width: 800 },630 {631 button: "Files",632 path: `/${project}/blob/main/packages/render/src/page.ts`,633 width: 390,634 },635 { button: "Projects", path: "/asks", width: 390 },636 { button: "More", path: `/${project}`, width: 390 },637 ] as const;638639 const problems: string[] = [];640641 for (const sheet of sheets) {642 const { context, page } = yield* keyboardPage(643 browser,644 sheet.path,645 sheet.width646 );647648 const button = page649 .getByRole("button", { exact: true, name: sheet.button })650 .first();651652 yield* Effect.promise(() => button.focus());653 yield* Effect.promise(() => page.keyboard.press("Enter"));654655 const dialog = page.getByRole("dialog");656657 yield* Effect.promise(() => expect(dialog).toBeVisible());658659 const stops = yield* tabStops(page, 30, 120);660661 if (stops.some(({ inside }) => inside !== "dialog")) {662 problems.push(`${sheet.button}: focus leaves the sheet`);663 }664665 yield* Effect.promise(() => page.keyboard.press("Escape"));666 yield* Effect.promise(() => expect(dialog).toBeHidden());667668 const back = yield* focused(page);669670 if (back?.label !== sheet.button) {671 problems.push(672 `${sheet.button}: focus returns to ${back?.label ?? "nothing"}`673 );674 }675676 yield* Effect.promise(() => context.close());677 }678679 expect(problems).toStrictEqual([]);680 })681 ));682});