Files
Studio_Grasso/tests/a11y/keyboard.spec.ts
T
Claude 601d13cfaf test: suite completa di §11 e npm run verify verde
- html-validate su tutte le pagine; linkinator su astro preview (link, asset,
  CSS e ancore), con modalità --external per i siti esterni
- e2e Playwright: struttura e metadati di ogni pagina, 404, navigazione,
  sottomenu, menu mobile, ancore del vecchio sito, nessuna richiesta esterna,
  nessun cookie, localStorage vuoto, mappa solo dopo il clic, funzionamento
  senza JavaScript, modulo di contatto
- a11y: axe su tutte le pagine a 1440 e 390 px e negli stati interattivi,
  tastiera (skip link, sottomenu, menu mobile), focus visibile, testo al 200 %,
  reflow a 320 px, movimento ridotto
- check-compliance.mjs: P.IVA, link legali, risorse sicure, segnaposto,
  JSON-LD, sitemap, robots, .htaccess, badge e servizi, uso di
  «commercialista», riferimento L. 4/2013, budget
- fix: punti di interruzione in em, focus ciclico nel menu mobile,
  rel="noopener" sui link esterni del Markdown, numeri di telefono non spezzabili

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016zJ9ZWGKvoKoxYwbmnRKdJ
2026-10-15 22:55:46 +00:00

177 lines
7.3 KiB
TypeScript

/**
* 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 } from '../helpers/site';
/** Vero se l'elemento attivo ha un indicatore di focus visibile (outline su sé o su ::after). */
async function focusIsVisible(page: Page): Promise<{ ok: boolean; what: string }> {
return page.evaluate(() => {
const el = document.activeElement as HTMLElement | null;
if (!el || el === document.body) return { ok: false, what: 'nessun elemento con il focus' };
const has = (s: CSSStyleDeclaration) =>
(s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0) ||
(s.boxShadow !== 'none' && s.boxShadow !== '');
const ok = has(getComputedStyle(el)) || has(getComputedStyle(el, '::after'));
const what = `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}.${String(el.className).split(' ')[0]} «${(el.textContent ?? '').trim().slice(0, 40)}»`;
return { ok, what };
});
}
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
await page.keyboard.press('Enter');
await expect(submenu).toBeVisible();
for (let i = 0; i < 7; i++) await page.keyboard.press('Tab');
await expect(submenu).toBeHidden();
});
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/', '/contatti/', '/dove-siamo/']) {
test(`focus visibile 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 } = await focusIsVisible(page);
seen.push(what);
expect(ok, `focus non visibile 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();
});