/** * Accessibilità da tastiera (brief §9.5, §11.3): link «salta al contenuto», sottomenu e menu * mobile usabili con la tastiera, focus sempre visibile, testo ridimensionabile, reflow a 320 px. */ import { expect, test, type Page } from '@playwright/test'; import { ALL_PAGES, SERVICE_PAGES } from '../helpers/site'; /** * Indicatore di focus dell'elemento attivo: deve esserci (outline su sé o su ::after, oppure un * box-shadow) e l'outline deve avere un contrasto di almeno 3:1 con il fondo su cui si trova * (WCAG 1.4.11). Con outline-offset l'anello sta fuori dall'elemento: il fondo è quello del primo * antenato con un colore di sfondo, composto con i fondi semitrasparenti sopra di esso; per i * gradienti vale il colore meno favorevole. */ async function focusIsVisible( page: Page, ): Promise<{ ok: boolean; what: string; contrast: number | null }> { return page.evaluate(() => { type Rgba = [number, number, number, number]; const el = document.activeElement as HTMLElement | null; if (!el || el === document.body) { return { ok: false, what: 'nessun elemento con il focus', contrast: null }; } const what = `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}.${String(el.className).split(' ')[0]} «${(el.textContent ?? '').trim().slice(0, 40)}»`; const colors = (css: string): Rgba[] => [...css.matchAll(/rgba?\(([^)]+)\)/g)].map((m) => { const p = m[1] .split(/[\s,/]+/) .filter(Boolean) .map(Number); return [p[0], p[1], p[2], p.length > 3 ? p[3] : 1]; }); const over = (top: Rgba, under: Rgba): Rgba => [ top[0] * top[3] + under[0] * (1 - top[3]), top[1] * top[3] + under[1] * (1 - top[3]), top[2] * top[3] + under[2] * (1 - top[3]), 1, ]; const luminance = ([r, g, b]: Rgba) => { const [lr, lg, lb] = [r, g, b].map((v) => { const c = v / 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }); return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb; }; const ratio = (a: Rgba, b: Rgba) => { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); return (hi + 0.05) / (lo + 0.05); }; /** Colori possibili del fondo dietro `start` (più di uno con un gradiente). */ const backgrounds = (start: Element | null): Rgba[] => { const layers: Rgba[] = []; // fondi semitrasparenti, dal più vicino al più lontano let base: Rgba[] | null = null; for (let n = start; n && !base; n = n.parentElement) { const s = getComputedStyle(n); const stops = s.backgroundImage === 'none' ? [] : colors(s.backgroundImage); if (stops.length) { base = stops.map((c) => over(c, [255, 255, 255, 1])); break; } const c = colors(s.backgroundColor)[0]; if (c && c[3] >= 1) base = [c]; else if (c && c[3] > 0) layers.push(c); } return (base ?? [[255, 255, 255, 1]]).map((b) => layers.reduceRight((acc, l) => over(l, acc), b), ); }; const self = getComputedStyle(el); const after = getComputedStyle(el, '::after'); const hasOutline = (s: CSSStyleDeclaration) => s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0; let ring: Rgba | undefined; let start: Element | null = null; if (hasOutline(self)) { ring = colors(self.outlineColor)[0]; start = el.parentElement; } else if (hasOutline(after)) { // ::after in posizione assoluta (card): l'anello circonda il contenitore posizionato ring = colors(after.outlineColor)[0]; start = (el.offsetParent ?? el).parentElement; } else if (self.boxShadow !== 'none' && self.boxShadow !== '') { return { ok: true, what, contrast: null }; // indicatore con ombra: contrasto non misurato } if (!ring) return { ok: false, what, contrast: null }; const contrast = Math.min(...backgrounds(start).map((b) => ratio(ring, b))); return { ok: contrast >= 3, what, contrast: Math.round(contrast * 100) / 100 }; }); } test('il primo Tab porta al link «Vai al contenuto principale»', async ({ page }) => { await page.goto('/studio/'); await page.keyboard.press('Tab'); const skip = page.locator('.skip-link'); await expect(skip).toBeFocused(); await expect(skip).toBeInViewport(); await expect(skip).toHaveText('Vai al contenuto principale'); await page.keyboard.press('Enter'); await expect(page.locator('main#contenuto')).toBeFocused(); // il Tab successivo prosegue all'interno del contenuto principale await page.keyboard.press('Tab'); const insideMain = await page.evaluate( () => document.querySelector('main')?.contains(document.activeElement) ?? false, ); expect(insideMain, 'dopo il salto il focus prosegue nel contenuto').toBe(true); }); test('sottomenu desktop: apertura con Invio, navigazione con Tab, chiusura con Esc', async ({ page, }) => { await page.setViewportSize({ width: 1440, height: 900 }); await page.goto('/'); const toggle = page.locator('.nav [data-submenu-toggle]'); const submenu = page.locator('#sottomenu-servizi'); // raggiunge il pulsante del sottomenu solo con la tastiera for (let i = 0; i < 30; i++) { await page.keyboard.press('Tab'); if (await toggle.evaluate((el) => el === document.activeElement)) break; } await expect(toggle).toBeFocused(); await expect(toggle).toHaveAttribute('aria-expanded', 'false'); await page.keyboard.press('Enter'); await expect(toggle).toHaveAttribute('aria-expanded', 'true'); await expect(submenu).toBeVisible(); await page.keyboard.press('Tab'); await expect(submenu.getByRole('link').first()).toBeFocused(); await page.keyboard.press('Escape'); await expect(submenu).toBeHidden(); await expect(toggle).toBeFocused(); await expect(toggle).toHaveAttribute('aria-expanded', 'false'); // uscendo dal sottomenu con Tab il sottomenu si chiude (qualunque sia il numero di servizi) await page.keyboard.press('Enter'); await expect(submenu).toBeVisible(); let tabs = 0; for (; tabs < SERVICE_PAGES.length + 5; tabs++) { await page.keyboard.press('Tab'); const inside = await page.evaluate(() => { const a = document.activeElement; return ( !!a && (a.closest('#sottomenu-servizi') !== null || a.matches('[data-submenu-toggle]')) ); }); if (!inside) break; } expect(tabs, 'un Tab per ogni servizio del sottomenu, poi si esce').toBe(SERVICE_PAGES.length); await expect(submenu).toBeHidden(); }); test('sottomenu aperto al passaggio del mouse: Esc lo chiude (WCAG 1.4.13)', async ({ page }) => { await page.setViewportSize({ width: 1440, height: 900 }); await page.goto('/'); const item = page.locator('.nav [data-submenu]'); const submenu = page.locator('#sottomenu-servizi'); await item.locator('a').first().hover(); await expect(submenu).toBeVisible(); await page.keyboard.press('Escape'); await expect(submenu).toBeHidden(); // uscendo e tornando con il puntatore il sottomenu si riapre await page.mouse.move(5, 600); await item.locator('a').first().hover(); await expect(submenu).toBeVisible(); // con il focus su un link del sottomenu, Esc lo chiude e porta il focus sul pulsante await submenu.getByRole('link').first().focus(); await page.keyboard.press('Escape'); await expect(submenu).toBeHidden(); await expect(item.locator('[data-submenu-toggle]')).toBeFocused(); }); test('menu mobile: apertura con Invio, focus intrappolato nel menu, chiusura con Esc', async ({ page, }) => { await page.setViewportSize({ width: 390, height: 844 }); await page.goto('/'); const toggle = page.locator('[data-menu-open]'); const menu = page.locator('#menu-mobile'); for (let i = 0; i < 10; i++) { await page.keyboard.press('Tab'); if (await toggle.evaluate((el) => el === document.activeElement)) break; } await expect(toggle).toBeFocused(); await page.keyboard.press('Enter'); await expect(menu).toBeVisible(); await expect(toggle).toHaveAttribute('aria-expanded', 'true'); await expect(page.locator('[data-menu-close]')).toBeFocused(); for (let i = 0; i < 25; i++) { await page.keyboard.press('Tab'); const inside = await menu.evaluate((m) => m.contains(document.activeElement)); expect(inside, `il focus resta nel menu aperto (Tab n. ${i + 1})`).toBe(true); } // il sottomenu si apre con la tastiera await page.locator('#menu-mobile [data-submenu-toggle]').focus(); await page.keyboard.press('Enter'); await expect(page.locator('#menu-mobile-servizi')).toBeVisible(); await page.keyboard.press('Escape'); await expect(menu).toBeHidden(); await expect(toggle).toBeFocused(); await expect(toggle).toHaveAttribute('aria-expanded', 'false'); }); for (const path of ['/', '/servizi/', SERVICE_PAGES[0], '/contatti/', '/dove-siamo/']) { test(`focus visibile e contrastato su ogni elemento raggiungibile con Tab in ${path}`, async ({ page, }) => { await page.setViewportSize({ width: 1440, height: 900 }); await page.goto(path); const total = await page .locator('a[href], button:not([disabled]), input, textarea, select, [tabindex="0"]') .evaluateAll( (els) => els.filter((e) => { const r = (e as HTMLElement).getBoundingClientRect(); return r.width > 0 && r.height > 0 && (e as HTMLElement).tabIndex >= 0; }).length, ); expect(total).toBeGreaterThan(5); const seen: string[] = []; for (let i = 0; i < total; i++) { await page.keyboard.press('Tab'); const { ok, what, contrast } = await focusIsVisible(page); seen.push(what); expect( ok, `focus non visibile o poco contrastato (${contrast ?? '—'}:1, minimo 3:1) su ${what} (Tab n. ${i + 1}) in ${path}`, ).toBe(true); } }); } test('testo ingrandito al 200 % dalle impostazioni del browser: nessun contenuto tagliato', async ({ page, }) => { await page.setViewportSize({ width: 1280, height: 900 }); // equivale a impostare «Dimensione carattere» a 32 px (il doppio di 16) nelle preferenze const cdp = await page.context().newCDPSession(page); await cdp.send('Page.enable'); await cdp.send('Page.setFontSizes', { fontSizes: { standard: 32, fixed: 26 } }); for (const path of ['/', '/servizi/contenzioso-tributario/', '/contatti/', '/note-legali/']) { await page.goto(path); const { overflow, fontSize } = await page.evaluate(() => ({ overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, fontSize: parseFloat(getComputedStyle(document.body).fontSize), })); expect(fontSize, `dimensione del testo raddoppiata in ${path}`).toBeGreaterThanOrEqual(32); expect(overflow, `scorrimento orizzontale con testo al 200 % in ${path}`).toBeLessThanOrEqual( 0, ); } }); test('reflow a 320 px: nessuno scorrimento orizzontale in tutte le pagine', async ({ page }) => { await page.setViewportSize({ width: 320, height: 640 }); for (const path of ALL_PAGES) { await page.goto(path); const overflow = await page.evaluate( () => document.documentElement.scrollWidth - document.documentElement.clientWidth, ); expect(overflow, `scorrimento orizzontale a 320 px in ${path}`).toBeLessThanOrEqual(0); } }); test('preferenza «riduci movimento»: nessuna transizione', async ({ browser }) => { const context = await browser.newContext({ reducedMotion: 'reduce' }); const page = await context.newPage(); await page.goto('/'); const duration = await page .locator('.card') .first() .evaluate((el) => getComputedStyle(el).transitionDuration); expect( duration.split(',').every((d) => parseFloat(d) <= 0.001), `durata transizioni con movimento ridotto: ${duration}`, ).toBe(true); await context.close(); });