app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

accessibility.spec.ts (7485B)


      1 import { test, expect } from '@playwright/test';
      2 import { encodeProductReference } from '../../src/lib/nostr/references.ts';
      3 import { createStaticHarness } from '../integration/harness/static.ts';
      4 
      5 // Actual product routes and keyboard, not a fabricated screen-reader result.
      6 const coordinate = encodeProductReference({
      7   kind: 30402,
      8   pubkey: '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
      9   identifier: 'HCP140_PUBLIC_LONG_REFERENCE_' + 'e\u0301菜'.repeat(32)
     10 });
     11 if (!coordinate) throw Error('supported public coordinate unavailable');
     12 const handle = '12345678-1234-4234-8234-123456789abc';
     13 const routes = [
     14   '/',
     15   '/search',
     16   '/products/' + coordinate,
     17   '/sell',
     18   '/selling',
     19   '/selling/drafts/' + handle,
     20   '/products/' + coordinate + '/edit',
     21   '/messages',
     22   '/messages/' + handle,
     23   '/about',
     24   '/privacy'
     25 ];
     26 
     27 for (const width of [320, 1024]) {
     28   test(`actual eleven guest pages keep keyboard landmarks, labels, contrast and reflow at ${width}px`, async ({
     29     browser
     30   }) => {
     31     const server = await createStaticHarness();
     32     const context = await browser.newContext({
     33       viewport: { width, height: 900 },
     34       reducedMotion: 'reduce'
     35     });
     36     const external: string[] = [],
     37       errors: string[] = [];
     38     try {
     39       await context.route('**/*', (route) => {
     40         if (new URL(route.request().url()).origin === server.url)
     41           return route.continue();
     42         external.push(route.request().url());
     43         return route.abort();
     44       });
     45       await context.addInitScript(() => {
     46         for (const name of ['nostr', 'WebSocket'])
     47           Object.defineProperty(window, name, {
     48             configurable: true,
     49             get() {
     50               throw Error('guest acquired ' + name);
     51             }
     52           });
     53       });
     54       for (const path of routes) {
     55         const page = await context.newPage();
     56         page.on('pageerror', (error) => errors.push(error.message));
     57         expect((await page.goto(server.url + path))?.status()).toBe(200);
     58         await expect(
     59           page.getByRole('navigation', { name: 'Primary', exact: true })
     60         ).toHaveCount(1);
     61         await expect(
     62           page.getByRole('navigation', { name: 'Footer', exact: true })
     63         ).toHaveCount(1);
     64         const main = page.getByRole('main');
     65         await expect(main).toHaveCount(1);
     66         await expect(main.getByRole('heading', { level: 1 })).toHaveCount(1);
     67         if (path === '/') {
     68           await expect(main.getByRole('heading', { level: 1 })).toHaveText(
     69             'Find food'
     70           );
     71           await expect(
     72             main.getByText(
     73               'Browse without connecting. Connect when you want to list food or send a message.',
     74               { exact: true }
     75             )
     76           ).toBeVisible();
     77         }
     78         await page.keyboard.press('Tab');
     79         const skip = page.getByRole('link', {
     80           name: 'Skip to main content',
     81           exact: true
     82         });
     83         await expect(skip).toBeFocused();
     84         await expect(skip).toHaveCSS('outline-style', 'solid');
     85         await page.keyboard.press('Enter');
     86         await expect(main).toBeFocused();
     87         const geometry = await page.evaluate(() => {
     88           function rgb(value: string) {
     89             const match =
     90               /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/.exec(value);
     91             if (!match || (match[4] !== undefined && Number(match[4]) !== 1))
     92               return undefined;
     93             return match.slice(1, 4).map(Number);
     94           }
     95           function luminance(color: number[]) {
     96             const linear = color.map((value) => {
     97               const s = value / 255;
     98               return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
     99             });
    100             return linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722;
    101           }
    102           const controls = Array.from(
    103             document.querySelectorAll(
    104               'button,input,textarea,select,summary,a.shell-link,a.button'
    105             )
    106           )
    107             .filter((element) => element.checkVisibility())
    108             .map((element) => {
    109               const box = element.getBoundingClientRect();
    110               return {
    111                 tag: element.tagName,
    112                 height: box.height,
    113                 left: box.left,
    114                 right: box.right
    115               };
    116             });
    117           const fields = Array.from(
    118             document.querySelectorAll('input,textarea,select')
    119           )
    120             .filter((element) => element.checkVisibility())
    121             .map((element) => {
    122               const field = element as HTMLInputElement;
    123               return {
    124                 id: field.id,
    125                 labelled: Boolean(
    126                   field.labels?.length ||
    127                   field.getAttribute('aria-label') ||
    128                   field.getAttribute('aria-labelledby')
    129                 )
    130               };
    131             });
    132           const contrast = Array.from(
    133             document.querySelectorAll(
    134               'main p,main h1,main h2,main label,main summary,main button,main a'
    135             )
    136           )
    137             .filter(
    138               (element) =>
    139                 element.checkVisibility() &&
    140                 Boolean(element.textContent?.trim())
    141             )
    142             .map((element) => {
    143               const foreground = rgb(getComputedStyle(element).color);
    144               let parent: Element | null = element,
    145                 background: number[] | undefined;
    146               while (parent && !background) {
    147                 background = rgb(getComputedStyle(parent).backgroundColor);
    148                 parent = parent.parentElement;
    149               }
    150               if (!foreground || !background)
    151                 throw Error('unmeasured rendered contrast');
    152               const a = luminance(foreground),
    153                 b = luminance(background);
    154               return {
    155                 tag: element.tagName,
    156                 ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)
    157               };
    158             });
    159           return {
    160             width: innerWidth,
    161             scroll: document.documentElement.scrollWidth,
    162             controls,
    163             fields,
    164             contrast
    165           };
    166         });
    167         expect(geometry.scroll).toBeLessThanOrEqual(geometry.width);
    168         expect(geometry.controls.length).toBeGreaterThan(0);
    169         for (const control of geometry.controls) {
    170           expect(control.height).toBeGreaterThanOrEqual(44);
    171           expect(control.left).toBeGreaterThanOrEqual(0);
    172           expect(control.right).toBeLessThanOrEqual(width);
    173         }
    174         for (const field of geometry.fields) expect(field.labelled).toBe(true);
    175         expect(geometry.contrast.length).toBeGreaterThan(0);
    176         for (const color of geometry.contrast)
    177           expect(color.ratio).toBeGreaterThanOrEqual(4.5);
    178         console.log(
    179           JSON.stringify({
    180             fixture: 'HCP140_ACTUAL_GUEST_ROUTES_ONLY',
    181             path,
    182             geometry,
    183             limits:
    184               'Actual viewport/keyboard/computed opaque text contrast; not manual screen reader, browser zoom, connected-account or participant qualification.'
    185           })
    186         );
    187         await page.close();
    188       }
    189       expect(errors).toEqual([]);
    190       expect(external).toEqual([]);
    191     } finally {
    192       await context.close();
    193       await server.close();
    194     }
    195     expect(context.pages()).toHaveLength(0);
    196     expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
    197   });
    198 }