@rgaa-audit/cli 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +62 -2
- package/bin/rgaa-audit.js +141 -0
- package/bin/rgaa-fill-grid.js +75 -0
- package/package.json +49 -4
- package/src/aggregate.js +77 -0
- package/src/audit.js +836 -0
- package/src/browser.js +61 -0
- package/src/captures.js +75 -0
- package/src/html-validation.js +71 -0
- package/src/logger.js +18 -0
- package/src/page-prep.js +100 -0
- package/src/reporters/index.js +59 -0
- package/src/reporters/ods-grid.js +240 -0
- package/src/rules/index.js +144 -0
- package/src/shared.js +33 -0
- package/src/simulator.js +656 -0
- package/vendor/rgaa-criteria.js +139 -0
- package/vendor/rgaa-guide-fiches.js +296 -0
- package/vendor/rgaa-guide-page.js +441 -0
- package/vendor/rgaa-rules.js +2830 -0
- package/vendor/vulgarized-report-template.js +779 -0
package/src/simulator.js
ADDED
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/simulator.js — Simulation d'actions humaines (CLI uniquement)
|
|
3
|
+
*
|
|
4
|
+
* Reproduit des gestes d'auditeur que l'analyse statique du DOM ne peut pas faire :
|
|
5
|
+
* - parcours au clavier : focus visible (10.7), piège clavier (12.9), contraste du texte
|
|
6
|
+
* au focus et au survol (3.2), contraste de l'indicateur de focus (3.3)
|
|
7
|
+
* - lien d'évitement : visible au focus et fonctionnel (12.7)
|
|
8
|
+
* - zoom 200 % (10.4), affichage à 320 px (10.11), espacement du texte (10.12)
|
|
9
|
+
* - page sans feuilles de styles (10.3), animations rapides (13.7)
|
|
10
|
+
* La page est rechargée à la fin pour ne pas fausser les mesures suivantes.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
'use strict';
|
|
14
|
+
|
|
15
|
+
const path = require('node:path');
|
|
16
|
+
const fs = require('node:fs');
|
|
17
|
+
const { log, success, warn } = require('./logger');
|
|
18
|
+
const { readSharedSource } = require('./shared');
|
|
19
|
+
const { waitForAnimations } = require('./rules');
|
|
20
|
+
|
|
21
|
+
const DEFAULT_SCREENSHOTS_DIR = './audit-screenshots';
|
|
22
|
+
const MAX_TABS = 40;
|
|
23
|
+
const FOCUS_SETTLE_MS = 120;
|
|
24
|
+
const DESKTOP_VIEWPORT = { width: 1280, height: 720 };
|
|
25
|
+
const MAX_HOVERED = 25;
|
|
26
|
+
|
|
27
|
+
/** Évalue une expression dans la page après y avoir chargé le moteur partagé. */
|
|
28
|
+
function withEngine(page, expression) {
|
|
29
|
+
return page.evaluate(`(() => {\n${readSharedSource('rgaa-rules.js')}\n;return ${expression};\n})()`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function createFindings() {
|
|
33
|
+
const findings = [];
|
|
34
|
+
const add = (id, status, resultType, message, extra = {}) => {
|
|
35
|
+
findings.push({
|
|
36
|
+
id,
|
|
37
|
+
status,
|
|
38
|
+
resultType,
|
|
39
|
+
message,
|
|
40
|
+
source: 'simulation',
|
|
41
|
+
severity: status === 'NC' ? 'high' : status === 'C' ? 'low' : 'medium',
|
|
42
|
+
confidence: extra.confidence || (status === 'NT' ? 'medium' : 'high'),
|
|
43
|
+
manualReviewRecommended: status !== 'NC',
|
|
44
|
+
snippet: null,
|
|
45
|
+
count: 1,
|
|
46
|
+
examples: [],
|
|
47
|
+
rationale: '',
|
|
48
|
+
remediationHint: '',
|
|
49
|
+
...extra,
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
findings,
|
|
54
|
+
error: (id, message, extra) => add(id, 'NC', 'probable_error', message, extra),
|
|
55
|
+
warn: (id, message, extra) => add(id, 'NT', 'heuristic_warning', message, extra),
|
|
56
|
+
pass: (id, message, extra) => add(id, 'C', 'good_signal', message, extra),
|
|
57
|
+
manual: (id, message, extra) => add(id, 'NT', 'manual_only', message, extra),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function simulateHumanActions(page, options = {}) {
|
|
62
|
+
const screenshotsDir = options.screenshotsDir || DEFAULT_SCREENSHOTS_DIR;
|
|
63
|
+
const reload = options.reload || (() => page.reload({ waitUntil: 'load' }));
|
|
64
|
+
fs.mkdirSync(screenshotsDir, { recursive: true });
|
|
65
|
+
|
|
66
|
+
const out = createFindings();
|
|
67
|
+
const screenshots = [];
|
|
68
|
+
const shoot = async (name, opts) => {
|
|
69
|
+
const file = await screenshot(page, screenshotsDir, name, opts);
|
|
70
|
+
if (file) screenshots.push(file);
|
|
71
|
+
return file;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
await page.setViewportSize(DESKTOP_VIEWPORT);
|
|
75
|
+
log(' 📸 État initial…');
|
|
76
|
+
await shoot('initial');
|
|
77
|
+
|
|
78
|
+
const focusStats = await runStep('parcours clavier', () => testKeyboardPath(page, out, shoot));
|
|
79
|
+
await runStep('lien d’évitement', async () => {
|
|
80
|
+
await reload();
|
|
81
|
+
await testSkipLink(page, out);
|
|
82
|
+
});
|
|
83
|
+
await runStep('zoom 200 %', async () => {
|
|
84
|
+
await reload();
|
|
85
|
+
await testTextZoom(page, out, shoot);
|
|
86
|
+
});
|
|
87
|
+
await runStep('affichage 320 px', async () => {
|
|
88
|
+
await testReflow(page, out, shoot);
|
|
89
|
+
});
|
|
90
|
+
await runStep('espacement du texte', async () => {
|
|
91
|
+
await reload();
|
|
92
|
+
await testTextSpacing(page, out);
|
|
93
|
+
});
|
|
94
|
+
await runStep('sans feuilles de styles', async () => {
|
|
95
|
+
await testWithoutCss(page, out, shoot);
|
|
96
|
+
});
|
|
97
|
+
await runStep('animations', async () => {
|
|
98
|
+
await reload();
|
|
99
|
+
await testAnimations(page, out);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
await page.setViewportSize(DESKTOP_VIEWPORT);
|
|
103
|
+
await runStep('rechargement final', () => reload());
|
|
104
|
+
|
|
105
|
+
const nc = out.findings.filter((f) => f.status === 'NC').length;
|
|
106
|
+
const c = out.findings.filter((f) => f.status === 'C').length;
|
|
107
|
+
return {
|
|
108
|
+
findings: out.findings,
|
|
109
|
+
screenshots,
|
|
110
|
+
summary: {
|
|
111
|
+
tested: out.findings.length,
|
|
112
|
+
nc,
|
|
113
|
+
c,
|
|
114
|
+
screenshotsDir,
|
|
115
|
+
focusElementsTested: focusStats ? focusStats.tested : 0,
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
async function runStep(label, fn) {
|
|
120
|
+
try {
|
|
121
|
+
return await fn();
|
|
122
|
+
} catch (err) {
|
|
123
|
+
warn(` Simulation « ${label} » interrompue : ${String(err?.message || err).split('\n')[0]}`);
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ── Parcours clavier ─────────────────────────
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Le focus est jugé visible si la zone autour de l'élément change à l'écran entre l'état
|
|
133
|
+
* focalisé et l'état non focalisé. La comparaison d'images couvre tous les styles
|
|
134
|
+
* possibles (outline, box-shadow, fond, soulignement…) et aussi le cas d'un focus posé
|
|
135
|
+
* sur un élément masqué ou hors écran.
|
|
136
|
+
*/
|
|
137
|
+
async function testKeyboardPath(page, out, shoot) {
|
|
138
|
+
log(` ⌨️ Parcours clavier (jusqu’à ${MAX_TABS} tabulations)…`);
|
|
139
|
+
await page.evaluate(() => {
|
|
140
|
+
if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur();
|
|
141
|
+
window.scrollTo(0, 0);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const seen = [];
|
|
145
|
+
const invisible = [];
|
|
146
|
+
const covered = [];
|
|
147
|
+
const weakIndicator = [];
|
|
148
|
+
const focusContrast = [];
|
|
149
|
+
let stuck = 0;
|
|
150
|
+
let previousKey = null;
|
|
151
|
+
|
|
152
|
+
for (let i = 0; i < MAX_TABS; i++) {
|
|
153
|
+
await page.keyboard.press('Tab');
|
|
154
|
+
await page.waitForTimeout(FOCUS_SETTLE_MS);
|
|
155
|
+
|
|
156
|
+
const info = await page.evaluate((index) => {
|
|
157
|
+
const el = document.activeElement;
|
|
158
|
+
if (!el || el === document.body || el === document.documentElement) return null;
|
|
159
|
+
if (el.localName === 'iframe') return { key: 'iframe', tag: 'iframe', skip: true };
|
|
160
|
+
const rect = el.getBoundingClientRect();
|
|
161
|
+
if (!el.hasAttribute('data-rgaa-focus')) el.setAttribute('data-rgaa-focus', String(index));
|
|
162
|
+
const label = (el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('title') || '')
|
|
163
|
+
.replace(/\s+/g, ' ').trim().slice(0, 60);
|
|
164
|
+
return {
|
|
165
|
+
key: el.getAttribute('data-rgaa-focus'),
|
|
166
|
+
tag: el.localName,
|
|
167
|
+
label,
|
|
168
|
+
rect: { x: rect.left, y: rect.top, width: rect.width, height: rect.height },
|
|
169
|
+
viewport: { width: window.innerWidth, height: window.innerHeight },
|
|
170
|
+
outerHTML: el.outerHTML.replace(/\s+/g, ' ').replace(/ data-rgaa-focus="\d+"/, '').slice(0, 180),
|
|
171
|
+
};
|
|
172
|
+
}, i);
|
|
173
|
+
|
|
174
|
+
if (!info) {
|
|
175
|
+
if (seen.length) break; // fin du document : le focus repart dans l'interface du navigateur
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (info.skip) continue;
|
|
179
|
+
|
|
180
|
+
if (info.key === previousKey) {
|
|
181
|
+
stuck++;
|
|
182
|
+
if (stuck >= 2) {
|
|
183
|
+
out.error('12.9', `Piège clavier : le focus reste bloqué sur <${info.tag}> « ${info.label} ».`, {
|
|
184
|
+
snippet: info.outerHTML,
|
|
185
|
+
rationale: 'L’utilisateur clavier ne peut plus quitter le composant avec Tab.',
|
|
186
|
+
remediationHint: 'Ne pas intercepter Tab, ou proposer une sortie documentée (Échap).',
|
|
187
|
+
});
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
stuck = 0;
|
|
193
|
+
previousKey = info.key;
|
|
194
|
+
if (seen.some((s) => s.key === info.key)) break; // retour au début : boucle normale de la page
|
|
195
|
+
seen.push(info);
|
|
196
|
+
|
|
197
|
+
await waitForAnimations(page, 800);
|
|
198
|
+
const contrast = await withEngine(page, 'globalThis.RgaaRules.measureContrast(document.activeElement)').catch(() => null);
|
|
199
|
+
if (contrast && contrast.pass === false) focusContrast.push({ ...info, contrast });
|
|
200
|
+
|
|
201
|
+
const { state, coveredBy, indicator } = await isFocusVisible(page);
|
|
202
|
+
if (state === 'invisible') invisible.push(info);
|
|
203
|
+
if (state === 'covered') covered.push({ ...info, coveredBy });
|
|
204
|
+
if (state === 'visible' && indicator && indicator.weak) weakIndicator.push({ ...info, indicator });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (!seen.length) {
|
|
208
|
+
out.warn('10.7', 'Aucun élément n’a reçu le focus au clavier.', {
|
|
209
|
+
remediationHint: 'Vérifier que les liens et contrôles sont atteignables avec Tab.',
|
|
210
|
+
});
|
|
211
|
+
return { tested: 0 };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (invisible.length) {
|
|
215
|
+
for (const info of invisible.slice(0, 3)) {
|
|
216
|
+
await page.evaluate((key) => {
|
|
217
|
+
const el = document.querySelector(`[data-rgaa-focus="${key}"]`);
|
|
218
|
+
if (!el) return;
|
|
219
|
+
el.focus({ preventScroll: true });
|
|
220
|
+
el.scrollIntoView({ block: 'center', behavior: 'instant' });
|
|
221
|
+
}, info.key).catch(() => {});
|
|
222
|
+
await shoot(`focus-invisible-${invisible.indexOf(info)}`);
|
|
223
|
+
}
|
|
224
|
+
out.error('10.7', `Focus non visible sur ${invisible.length} des ${seen.length} éléments parcourus au clavier.`, {
|
|
225
|
+
count: invisible.length,
|
|
226
|
+
confidence: 'medium',
|
|
227
|
+
snippet: invisible[0].outerHTML,
|
|
228
|
+
examples: invisible.slice(0, 5).map((i) => ({ selector: `<${i.tag}> « ${i.label} »`, snippet: i.outerHTML })),
|
|
229
|
+
rationale: 'Aucune différence visuelle n’apparaît autour de ces éléments quand ils reçoivent le focus.',
|
|
230
|
+
remediationHint: 'Définir un style :focus-visible contrasté (outline de 2 px minimum, par exemple).',
|
|
231
|
+
});
|
|
232
|
+
warn(` ✗ Focus invisible sur ${invisible.length}/${seen.length} élément(s)`);
|
|
233
|
+
} else {
|
|
234
|
+
out.pass('10.7', `Focus visible sur les ${seen.length - covered.length} éléments parcourus et mesurables au clavier.`, {
|
|
235
|
+
confidence: 'medium',
|
|
236
|
+
remediationHint: 'Vérifier aussi le contraste de l’indicateur de focus.',
|
|
237
|
+
});
|
|
238
|
+
success(` ✓ Focus visible sur ${seen.length - covered.length} élément(s)`);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (covered.length) {
|
|
242
|
+
out.warn('10.7', `Focus masqué par un élément superposé sur ${covered.length} élément(s) (ex. ${covered[0].coveredBy}).`, {
|
|
243
|
+
count: covered.length,
|
|
244
|
+
snippet: covered[0].outerHTML,
|
|
245
|
+
examples: covered.slice(0, 5).map((i) => ({ selector: `<${i.tag}> « ${i.label} » sous ${i.coveredBy}`, snippet: i.outerHTML })),
|
|
246
|
+
rationale: 'Un bandeau ou une barre fixe recouvre l’élément focalisé : l’utilisateur clavier ne voit pas où il se trouve.',
|
|
247
|
+
remediationHint: 'Éviter qu’un contenu fixe recouvre le focus (scroll-padding, bandeau non bloquant ou fermé au clavier).',
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (weakIndicator.length) {
|
|
252
|
+
const best = Math.max(...weakIndicator.map((w) => w.indicator.max));
|
|
253
|
+
out.warn('3.3', `Indicateur de focus peu contrasté sur ${weakIndicator.length} élément(s) (meilleur écart mesuré ${best.toFixed(2)}:1, attendu 3:1).`, {
|
|
254
|
+
count: weakIndicator.length,
|
|
255
|
+
snippet: weakIndicator[0].outerHTML,
|
|
256
|
+
examples: weakIndicator.slice(0, 5).map((i) => ({ selector: `<${i.tag}> « ${i.label} » (${i.indicator.max.toFixed(2)}:1)`, snippet: i.outerHTML })),
|
|
257
|
+
rationale: 'Le changement visuel à la prise de focus existe mais se distingue mal de l’état normal.',
|
|
258
|
+
remediationHint: 'Utiliser un contour ou un soulignement contrasté (3:1 avec l’état non focalisé et avec le fond).',
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
reportStateContrast(out, focusContrast, 'au focus');
|
|
263
|
+
const hovered = await testHoverContrast(page, seen);
|
|
264
|
+
reportStateContrast(out, hovered, 'au survol');
|
|
265
|
+
|
|
266
|
+
out.manual('12.8', `Ordre de tabulation sur ${seen.length} éléments : vérifier qu’il suit l’ordre de lecture.`, {
|
|
267
|
+
details: { sequence: seen.map((s) => s.label || s.tag).slice(0, MAX_TABS) },
|
|
268
|
+
});
|
|
269
|
+
return { tested: seen.length };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function reportStateContrast(out, failures, stateLabel) {
|
|
273
|
+
if (!failures.length) return;
|
|
274
|
+
const worst = failures.reduce((a, b) => (a.contrast.ratio <= b.contrast.ratio ? a : b));
|
|
275
|
+
out.error('3.2', `Contraste insuffisant ${stateLabel} sur ${failures.length} élément(s) (jusqu’à ${worst.contrast.ratio}:1, texte ${worst.contrast.foreground} sur ${worst.contrast.background}).`, {
|
|
276
|
+
count: failures.length,
|
|
277
|
+
snippet: worst.outerHTML,
|
|
278
|
+
details: { ratio: worst.contrast.ratio, required: worst.contrast.required, foreground: worst.contrast.foreground, background: worst.contrast.background },
|
|
279
|
+
examples: failures.slice(0, 5).map((f) => ({ selector: `<${f.tag}> « ${f.label} » (${f.contrast.ratio}:1, requis ${f.contrast.required}:1)`, snippet: f.outerHTML })),
|
|
280
|
+
rationale: `Les couleurs appliquées ${stateLabel} rendent le texte difficile à lire.`,
|
|
281
|
+
remediationHint: `Vérifier les styles :hover/:focus : le texte doit rester à 4,5:1 (3:1 pour le gros texte) ${stateLabel}.`,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Survole les éléments interactifs parcourus au clavier et mesure le contraste de leur texte. */
|
|
286
|
+
async function testHoverContrast(page, seen) {
|
|
287
|
+
const failures = [];
|
|
288
|
+
await page.evaluate(() => document.activeElement && document.activeElement.blur && document.activeElement.blur());
|
|
289
|
+
for (const info of seen.slice(0, MAX_HOVERED)) {
|
|
290
|
+
const selector = `[data-rgaa-focus="${info.key}"]`;
|
|
291
|
+
try {
|
|
292
|
+
await page.hover(selector, { timeout: 1500 });
|
|
293
|
+
await page.waitForTimeout(FOCUS_SETTLE_MS);
|
|
294
|
+
await waitForAnimations(page, 800);
|
|
295
|
+
const contrast = await withEngine(page, `globalThis.RgaaRules.measureContrast(document.querySelector('${selector}'))`);
|
|
296
|
+
if (contrast && contrast.pass === false) failures.push({ ...info, contrast });
|
|
297
|
+
} catch {
|
|
298
|
+
// élément masqué, recouvert ou retiré du DOM : on passe au suivant
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
await page.mouse.move(0, 0);
|
|
302
|
+
return failures;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Retourne 'visible', 'invisible', 'covered' (élément focalisé caché sous un autre, par
|
|
307
|
+
* exemple un bandeau cookies) ou null si la mesure est impossible.
|
|
308
|
+
*/
|
|
309
|
+
async function isFocusVisible(page) {
|
|
310
|
+
const margin = 8;
|
|
311
|
+
const box = await page.evaluate(() => {
|
|
312
|
+
const el = document.activeElement;
|
|
313
|
+
if (!el || el === document.body) return null;
|
|
314
|
+
// Défilement instantané : avec scroll-behavior: smooth, l'élément n'est pas encore à l'écran.
|
|
315
|
+
el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
|
|
316
|
+
const r = el.getBoundingClientRect();
|
|
317
|
+
const cx = Math.min(window.innerWidth - 1, Math.max(0, r.left + r.width / 2));
|
|
318
|
+
const cy = Math.min(window.innerHeight - 1, Math.max(0, r.top + r.height / 2));
|
|
319
|
+
const top = document.elementFromPoint(cx, cy);
|
|
320
|
+
const covered = top && top !== el && !el.contains(top) && !top.contains(el);
|
|
321
|
+
return {
|
|
322
|
+
rect: { x: r.left, y: r.top, width: r.width, height: r.height },
|
|
323
|
+
viewport: { width: window.innerWidth, height: window.innerHeight },
|
|
324
|
+
coveredBy: covered ? `<${top.localName}${top.id ? `#${top.id}` : ''}${top.classList.length ? `.${[...top.classList].slice(0, 2).join('.')}` : ''}>` : null,
|
|
325
|
+
};
|
|
326
|
+
});
|
|
327
|
+
if (!box) return { state: null };
|
|
328
|
+
const { rect, viewport } = box;
|
|
329
|
+
if (rect.width === 0 && rect.height === 0) return { state: 'invisible' };
|
|
330
|
+
if (box.coveredBy) return { state: 'covered', coveredBy: box.coveredBy };
|
|
331
|
+
const x = Math.max(0, Math.floor(rect.x - margin));
|
|
332
|
+
const y = Math.max(0, Math.floor(rect.y - margin));
|
|
333
|
+
const right = Math.min(viewport.width, Math.ceil(rect.x + rect.width + margin));
|
|
334
|
+
const bottom = Math.min(viewport.height, Math.ceil(rect.y + rect.height + margin));
|
|
335
|
+
if (right - x < 1 || bottom - y < 1) return { state: 'invisible' };
|
|
336
|
+
const clip = { x, y, width: right - x, height: bottom - y };
|
|
337
|
+
|
|
338
|
+
try {
|
|
339
|
+
const focused = await page.screenshot({ clip, animations: 'disabled', caret: 'hide' });
|
|
340
|
+
const restore = await page.evaluate(() => {
|
|
341
|
+
const el = document.activeElement;
|
|
342
|
+
if (!el || el === document.body) return false;
|
|
343
|
+
window.__rgaaLastFocus = el;
|
|
344
|
+
el.blur();
|
|
345
|
+
return true;
|
|
346
|
+
});
|
|
347
|
+
if (!restore) return { state: null };
|
|
348
|
+
await page.waitForTimeout(FOCUS_SETTLE_MS);
|
|
349
|
+
const blurred = await page.screenshot({ clip, animations: 'disabled', caret: 'hide' });
|
|
350
|
+
await page.evaluate(() => {
|
|
351
|
+
const el = window.__rgaaLastFocus;
|
|
352
|
+
delete window.__rgaaLastFocus;
|
|
353
|
+
if (el && el.isConnected) el.focus({ preventScroll: true });
|
|
354
|
+
});
|
|
355
|
+
if (focused.equals(blurred)) return { state: 'invisible' };
|
|
356
|
+
return { state: 'visible', indicator: await measureIndicator(page, focused, blurred, rect) };
|
|
357
|
+
} catch {
|
|
358
|
+
return { state: null };
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Contraste de l'indicateur de focus : pour chaque pixel modifié par la prise de focus,
|
|
364
|
+
* rapport de contraste entre sa couleur focalisée et sa couleur d'origine. L'indicateur est
|
|
365
|
+
* jugé faible si moins de pixels qu'une ligne de la largeur de l'élément atteignent 3:1
|
|
366
|
+
* (un soulignement suffit, un léger changement de fond non).
|
|
367
|
+
*/
|
|
368
|
+
async function measureIndicator(page, focused, blurred, rect) {
|
|
369
|
+
return page.evaluate(async ({ a, b, width }) => {
|
|
370
|
+
const decode = async (b64) => {
|
|
371
|
+
const img = new Image();
|
|
372
|
+
img.src = `data:image/png;base64,${b64}`;
|
|
373
|
+
await img.decode();
|
|
374
|
+
const canvas = document.createElement('canvas');
|
|
375
|
+
canvas.width = img.width;
|
|
376
|
+
canvas.height = img.height;
|
|
377
|
+
const ctx = canvas.getContext('2d');
|
|
378
|
+
ctx.drawImage(img, 0, 0);
|
|
379
|
+
return ctx.getImageData(0, 0, img.width, img.height).data;
|
|
380
|
+
};
|
|
381
|
+
const lum = (r, g, bl) => [r, g, bl].map((v) => {
|
|
382
|
+
const c = v / 255;
|
|
383
|
+
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
384
|
+
}).reduce((acc, v, i) => acc + v * [0.2126, 0.7152, 0.0722][i], 0);
|
|
385
|
+
const [pa, pb] = await Promise.all([decode(a), decode(b)]);
|
|
386
|
+
let changed = 0;
|
|
387
|
+
let strong = 0;
|
|
388
|
+
let max = 1;
|
|
389
|
+
for (let i = 0; i < pa.length; i += 4) {
|
|
390
|
+
if (Math.abs(pa[i] - pb[i]) + Math.abs(pa[i + 1] - pb[i + 1]) + Math.abs(pa[i + 2] - pb[i + 2]) < 24) continue;
|
|
391
|
+
changed++;
|
|
392
|
+
const la = lum(pa[i], pa[i + 1], pa[i + 2]);
|
|
393
|
+
const lb = lum(pb[i], pb[i + 1], pb[i + 2]);
|
|
394
|
+
const ratio = (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
|
|
395
|
+
if (ratio >= 3) strong++;
|
|
396
|
+
if (ratio > max) max = ratio;
|
|
397
|
+
}
|
|
398
|
+
return { changed, strong, max, weak: strong < Math.max(20, Math.min(width, 200)) };
|
|
399
|
+
}, { a: focused.toString('base64'), b: blurred.toString('base64'), width: Math.round(rect.width) });
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ── Lien d'évitement ─────────────────────────
|
|
403
|
+
|
|
404
|
+
async function testSkipLink(page, out) {
|
|
405
|
+
log(' 🎯 Lien d’évitement…');
|
|
406
|
+
await page.keyboard.press('Tab');
|
|
407
|
+
await page.waitForTimeout(FOCUS_SETTLE_MS);
|
|
408
|
+
|
|
409
|
+
const first = await page.evaluate(() => {
|
|
410
|
+
const el = document.activeElement;
|
|
411
|
+
if (!el || el === document.body) return null;
|
|
412
|
+
const text = (el.innerText || el.getAttribute('aria-label') || el.textContent || '').replace(/\s+/g, ' ').trim();
|
|
413
|
+
const href = el.getAttribute('href') || '';
|
|
414
|
+
const rect = el.getBoundingClientRect();
|
|
415
|
+
const style = window.getComputedStyle(el);
|
|
416
|
+
const onScreen = rect.width > 2 && rect.height > 2 && rect.bottom > 0 && rect.right > 0
|
|
417
|
+
&& rect.top < window.innerHeight && rect.left < window.innerWidth
|
|
418
|
+
&& style.visibility !== 'hidden' && parseFloat(style.opacity) > 0.1
|
|
419
|
+
&& !/rect\(\s*0/.test(style.clip);
|
|
420
|
+
return { tag: el.localName, text, href, onScreen, outerHTML: el.outerHTML.replace(/\s+/g, ' ').slice(0, 180) };
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
const isSkip = first && first.tag === 'a' && first.href.startsWith('#')
|
|
424
|
+
&& /aller|acc[eè]s|contenu|skip|passer|[ée]viter|main/i.test(first.text);
|
|
425
|
+
if (!isSkip) {
|
|
426
|
+
out.manual('12.7', `Le premier élément atteint au clavier n’est pas un lien d’évitement (${first ? `<${first.tag}> « ${first.text.slice(0, 40)} »` : 'aucun'}).`, {
|
|
427
|
+
remediationHint: 'Placer un lien « Aller au contenu » en tout premier élément focusable.',
|
|
428
|
+
});
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
if (!first.onScreen) {
|
|
433
|
+
out.error('12.7', `Le lien d’évitement « ${first.text} » reste invisible quand il reçoit le focus.`, {
|
|
434
|
+
snippet: first.outerHTML,
|
|
435
|
+
rationale: 'Test 12.7.2 : le lien doit être visible, ou au moins visible à la prise de focus.',
|
|
436
|
+
remediationHint: 'Rendre le lien visible au :focus (retirer le masquage sr-only à la prise de focus).',
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const target = decodeURIComponentSafe(first.href.slice(1));
|
|
441
|
+
await page.keyboard.press('Enter');
|
|
442
|
+
await page.waitForTimeout(300);
|
|
443
|
+
const result = await page.evaluate((id) => {
|
|
444
|
+
const targetEl = document.getElementById(id) || document.querySelector(`[name="${CSS.escape(id)}"]`);
|
|
445
|
+
if (!targetEl) return { exists: false };
|
|
446
|
+
const active = document.activeElement;
|
|
447
|
+
const rect = targetEl.getBoundingClientRect();
|
|
448
|
+
return {
|
|
449
|
+
exists: true,
|
|
450
|
+
focusMoved: Boolean(active && (active === targetEl || targetEl.contains(active))),
|
|
451
|
+
inView: rect.top < window.innerHeight && rect.bottom > 0,
|
|
452
|
+
};
|
|
453
|
+
}, target);
|
|
454
|
+
|
|
455
|
+
if (!result.exists) {
|
|
456
|
+
out.error('12.7', `Lien d’évitement non fonctionnel : la cible #${target} n’existe pas.`, { snippet: first.outerHTML });
|
|
457
|
+
} else if (!result.inView && !result.focusMoved) {
|
|
458
|
+
out.error('12.7', `Lien d’évitement non fonctionnel : l’activation n’amène pas sur #${target}.`, { snippet: first.outerHTML });
|
|
459
|
+
} else {
|
|
460
|
+
out.pass('12.7', `Lien d’évitement « ${first.text} » en premier, ${first.onScreen ? 'visible au focus' : 'mais invisible au focus'}, fonctionnel.`, {
|
|
461
|
+
confidence: 'high',
|
|
462
|
+
});
|
|
463
|
+
success(' ✓ Lien d’évitement visible et fonctionnel');
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function decodeURIComponentSafe(value) {
|
|
468
|
+
try {
|
|
469
|
+
return decodeURIComponent(value);
|
|
470
|
+
} catch {
|
|
471
|
+
return value;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// ── Zoom, reflow, espacement ─────────────────
|
|
476
|
+
|
|
477
|
+
/** Repère les blocs dont le texte est tronqué par leur conteneur (overflow masqué). */
|
|
478
|
+
async function findClippedText(page) {
|
|
479
|
+
return page.evaluate(() => {
|
|
480
|
+
const clipped = [];
|
|
481
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
482
|
+
if (!el.firstChild || !el.innerText || !el.innerText.trim()) continue;
|
|
483
|
+
const s = window.getComputedStyle(el);
|
|
484
|
+
const hidesX = /hidden|clip/.test(s.overflowX);
|
|
485
|
+
const hidesY = /hidden|clip/.test(s.overflowY);
|
|
486
|
+
if (!hidesX && !hidesY) continue;
|
|
487
|
+
const rect = el.getBoundingClientRect();
|
|
488
|
+
if (rect.width <= 2 || rect.height <= 2) continue; // texte masqué volontairement (sr-only)
|
|
489
|
+
const overflowY = hidesY && el.scrollHeight > el.clientHeight + 2;
|
|
490
|
+
const overflowX = hidesX && el.scrollWidth > el.clientWidth + 2 && s.whiteSpace !== 'normal';
|
|
491
|
+
if (overflowY || overflowX) {
|
|
492
|
+
let path = el.localName;
|
|
493
|
+
if (el.id) path += `#${el.id}`;
|
|
494
|
+
else if (el.classList.length) path += `.${[...el.classList].slice(0, 2).join('.')}`;
|
|
495
|
+
clipped.push({ selector: path, snippet: el.outerHTML.replace(/\s+/g, ' ').slice(0, 160) });
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return clipped;
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function testTextZoom(page, out, shoot) {
|
|
503
|
+
log(' 🔍 Zoom 200 % (fenêtre équivalente 640 × 360)…');
|
|
504
|
+
const before = new Set((await findClippedText(page)).map((c) => c.snippet));
|
|
505
|
+
await page.setViewportSize({ width: DESKTOP_VIEWPORT.width / 2, height: DESKTOP_VIEWPORT.height / 2 });
|
|
506
|
+
await page.waitForTimeout(400);
|
|
507
|
+
const after = (await findClippedText(page)).filter((c) => !before.has(c.snippet));
|
|
508
|
+
const shot = await shoot('zoom-200');
|
|
509
|
+
if (after.length) {
|
|
510
|
+
out.warn('10.4', `Zoom 200 % : ${after.length} bloc(s) de texte tronqué(s).`, {
|
|
511
|
+
count: after.length,
|
|
512
|
+
examples: after.slice(0, 5),
|
|
513
|
+
snippet: after[0].snippet,
|
|
514
|
+
screenshot: shot,
|
|
515
|
+
remediationHint: 'Éviter les hauteurs fixes et overflow:hidden sur les blocs de texte.',
|
|
516
|
+
});
|
|
517
|
+
warn(` ✗ ${after.length} bloc(s) tronqué(s) au zoom 200 %`);
|
|
518
|
+
} else {
|
|
519
|
+
out.pass('10.4', 'Zoom 200 % : aucun texte tronqué détecté.', {
|
|
520
|
+
confidence: 'medium', screenshot: shot,
|
|
521
|
+
remediationHint: 'Vérifier visuellement les chevauchements de texte sur la capture.',
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async function testReflow(page, out, shoot) {
|
|
527
|
+
log(' 📱 Affichage à 320 px de large…');
|
|
528
|
+
await page.setViewportSize({ width: 320, height: 568 });
|
|
529
|
+
await page.waitForTimeout(400);
|
|
530
|
+
const overflow = await page.evaluate(() => {
|
|
531
|
+
const doc = document.documentElement;
|
|
532
|
+
const width = window.innerWidth;
|
|
533
|
+
if (Math.max(doc.scrollWidth, document.body.scrollWidth) <= width + 1) return null;
|
|
534
|
+
const exempt = (el) => el.closest('table, pre, code, [role="grid"], [role="application"], .map, iframe, canvas, video');
|
|
535
|
+
const offenders = [];
|
|
536
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
537
|
+
const rect = el.getBoundingClientRect();
|
|
538
|
+
if (rect.right <= width + 1 || rect.width === 0) continue;
|
|
539
|
+
const s = window.getComputedStyle(el);
|
|
540
|
+
if (s.position === 'fixed' || s.visibility === 'hidden') continue;
|
|
541
|
+
const parentRect = el.parentElement ? el.parentElement.getBoundingClientRect() : null;
|
|
542
|
+
if (parentRect && parentRect.right > width + 1) continue; // ne garder que les débordements « racines »
|
|
543
|
+
let scroller = el.parentElement;
|
|
544
|
+
let clipped = false;
|
|
545
|
+
while (scroller && scroller !== document.body) {
|
|
546
|
+
const ps = window.getComputedStyle(scroller);
|
|
547
|
+
if (/auto|scroll|hidden|clip/.test(ps.overflowX)) { clipped = true; break; }
|
|
548
|
+
scroller = scroller.parentElement;
|
|
549
|
+
}
|
|
550
|
+
if (clipped) continue;
|
|
551
|
+
offenders.push({
|
|
552
|
+
selector: el.localName + (el.id ? `#${el.id}` : el.classList.length ? `.${[...el.classList].slice(0, 2).join('.')}` : ''),
|
|
553
|
+
snippet: el.outerHTML.replace(/\s+/g, ' ').slice(0, 160),
|
|
554
|
+
width: Math.round(rect.width),
|
|
555
|
+
exempt: Boolean(exempt(el)),
|
|
556
|
+
});
|
|
557
|
+
if (offenders.length >= 20) break;
|
|
558
|
+
}
|
|
559
|
+
return { scrollWidth: Math.max(doc.scrollWidth, document.body.scrollWidth), offenders };
|
|
560
|
+
});
|
|
561
|
+
const shot = await shoot('reflow-320');
|
|
562
|
+
|
|
563
|
+
if (!overflow) {
|
|
564
|
+
out.pass('10.11', 'À 320 px de large : pas de défilement horizontal.', { screenshot: shot });
|
|
565
|
+
success(' ✓ Pas de défilement horizontal à 320 px');
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
const real = overflow.offenders.filter((o) => !o.exempt);
|
|
569
|
+
const entry = {
|
|
570
|
+
count: Math.max(1, real.length),
|
|
571
|
+
examples: (real.length ? real : overflow.offenders).slice(0, 5),
|
|
572
|
+
snippet: (real[0] || overflow.offenders[0] || {}).snippet || null,
|
|
573
|
+
screenshot: shot,
|
|
574
|
+
details: { scrollWidth: overflow.scrollWidth },
|
|
575
|
+
remediationHint: 'Rendre la mise en page fluide (max-width:100 %, flex-wrap, media queries).',
|
|
576
|
+
};
|
|
577
|
+
if (real.length || !overflow.offenders.length) {
|
|
578
|
+
out.error('10.11', `À 320 px de large : défilement horizontal (contenu de ${overflow.scrollWidth} px).`, entry);
|
|
579
|
+
warn(` ✗ Défilement horizontal à 320 px (${overflow.scrollWidth} px)`);
|
|
580
|
+
} else {
|
|
581
|
+
out.warn('10.11', 'À 320 px : seul un contenu à deux dimensions (tableau, code, carte) déborde — exception possible.', entry);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
async function testTextSpacing(page, out) {
|
|
586
|
+
log(' ↔️ Espacement du texte (10.12)…');
|
|
587
|
+
const before = new Set((await findClippedText(page)).map((c) => c.snippet));
|
|
588
|
+
await page.addStyleTag({
|
|
589
|
+
content: `*, *::before, *::after { line-height: 1.5 !important; letter-spacing: 0.12em !important; word-spacing: 0.16em !important; }
|
|
590
|
+
p { margin-bottom: 2em !important; }`,
|
|
591
|
+
});
|
|
592
|
+
await page.waitForTimeout(300);
|
|
593
|
+
const after = (await findClippedText(page)).filter((c) => !before.has(c.snippet));
|
|
594
|
+
if (after.length) {
|
|
595
|
+
out.error('10.12', `Espacement du texte augmenté : ${after.length} bloc(s) de texte tronqué(s).`, {
|
|
596
|
+
count: after.length,
|
|
597
|
+
confidence: 'medium',
|
|
598
|
+
examples: after.slice(0, 5),
|
|
599
|
+
snippet: after[0].snippet,
|
|
600
|
+
rationale: 'Avec les espacements du test 10.12, ces blocs masquent une partie de leur texte.',
|
|
601
|
+
remediationHint: 'Supprimer les hauteurs fixes ; laisser les conteneurs s’adapter au texte.',
|
|
602
|
+
});
|
|
603
|
+
warn(` ✗ ${after.length} bloc(s) tronqué(s) avec l’espacement augmenté`);
|
|
604
|
+
} else {
|
|
605
|
+
out.pass('10.12', 'Espacement du texte augmenté : aucun texte tronqué détecté.', { confidence: 'medium' });
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
async function testWithoutCss(page, out, shoot) {
|
|
610
|
+
log(' 🎨 Page sans feuilles de styles…');
|
|
611
|
+
await page.setViewportSize(DESKTOP_VIEWPORT);
|
|
612
|
+
await page.evaluate(() => {
|
|
613
|
+
for (const sheet of document.styleSheets) {
|
|
614
|
+
try { sheet.disabled = true; } catch { /* feuille non modifiable */ }
|
|
615
|
+
}
|
|
616
|
+
document.querySelectorAll('[style]').forEach((el) => el.setAttribute('data-rgaa-style', el.getAttribute('style')));
|
|
617
|
+
document.querySelectorAll('[style]').forEach((el) => el.removeAttribute('style'));
|
|
618
|
+
});
|
|
619
|
+
await page.waitForTimeout(300);
|
|
620
|
+
const shot = await shoot('sans-css', { fullPage: true });
|
|
621
|
+
out.manual('10.3', 'Page sans feuilles de styles : vérifier sur la capture que l’information reste compréhensible et ordonnée.', {
|
|
622
|
+
screenshot: shot,
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async function testAnimations(page, out) {
|
|
627
|
+
log(' 🎬 Animations rapides…');
|
|
628
|
+
const fast = await page.evaluate(() => {
|
|
629
|
+
let count = 0;
|
|
630
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
631
|
+
const s = window.getComputedStyle(el);
|
|
632
|
+
if (s.animationName === 'none') continue;
|
|
633
|
+
const durations = s.animationDuration.split(',').map((d) => parseFloat(d) * (d.trim().endsWith('ms') ? 0.001 : 1));
|
|
634
|
+
const infinite = /infinite/.test(s.animationIterationCount);
|
|
635
|
+
if (infinite && durations.some((d) => d > 0 && d < 0.34)) count++;
|
|
636
|
+
}
|
|
637
|
+
return count;
|
|
638
|
+
});
|
|
639
|
+
if (fast) {
|
|
640
|
+
out.warn('13.7', `${fast} animation(s) en boucle plus rapide(s) que 3 cycles par seconde : risque de flash.`, {
|
|
641
|
+
remediationHint: 'Vérifier qu’aucun flash n’excède 3 par seconde ; ralentir ou supprimer l’animation.',
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async function screenshot(page, dir, name, opts = {}) {
|
|
647
|
+
const filepath = path.join(dir, `${name}-${Date.now()}.png`);
|
|
648
|
+
try {
|
|
649
|
+
await page.screenshot({ path: filepath, fullPage: false, ...opts });
|
|
650
|
+
return filepath;
|
|
651
|
+
} catch {
|
|
652
|
+
return null;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
module.exports = { simulateHumanActions, _internals: { findClippedText, isFocusVisible } };
|