@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.
@@ -0,0 +1,441 @@
1
+ /**
2
+ * Aides visuelles du guide manuel, exécutées dans la page auditée.
3
+ *
4
+ * Dépend de `globalThis.RgaaRules` (shared/rgaa-rules.js, injecté avant). Expose
5
+ * `globalThis.RgaaGuidePage` : inventaire des éléments à juger, surimpressions
6
+ * (alternatives, titres, zones, liens, ordre de tabulation, niveaux de gris) et mise en
7
+ * évidence d'un élément. Les surimpressions vivent dans un shadow DOM isolé, ignoré par
8
+ * les technologies d'assistance, et disparaissent avec clear().
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ (function (root) {
14
+ const VERSION = '1';
15
+ if (root.RgaaGuidePage && root.RgaaGuidePage.VERSION === VERSION) return;
16
+
17
+ const HOST_ID = 'rgaa-guide-overlay';
18
+ const GRAYSCALE_ID = 'rgaa-guide-grayscale';
19
+ const OFFICE_DOC_RE = /\.(pdf|docx?|xlsx?|pptx?|odt|ods|odp|rtf|epub)(\?|#|$)/i;
20
+ const MEDIA_EMBED_RE = /youtube|youtu\.be|vimeo|dailymotion|twitch|peertube|soundcloud|spotify/i;
21
+ const MAX_ITEMS = 200;
22
+
23
+ function dom() {
24
+ if (!root.RgaaRules || !root.RgaaRules.dom) throw new Error('Moteur RGAA non chargé dans la page.');
25
+ return root.RgaaRules.dom;
26
+ }
27
+
28
+ function item(el, label, detail) {
29
+ const d = dom();
30
+ return { key: d.cssPath(el), label: d.normalizedText(label).slice(0, 300), detail: detail ? d.normalizedText(detail).slice(0, 300) : '' };
31
+ }
32
+
33
+ function visible(el) {
34
+ const d = dom();
35
+ return d.isRendered(el) && !d.isVisuallyHidden(el);
36
+ }
37
+
38
+ // ── Inventaire ─────────────────────────────
39
+
40
+ /**
41
+ * Diapositive de carrousel masquée : une autre image est affichée par-dessus, au même
42
+ * endroit. Un simple calque transparent (lien étiré sur une carte) ne compte pas.
43
+ */
44
+ /** Transparent ou masqué, en tenant compte des ancêtres (diapositive inactive en fondu). */
45
+ function effectivelyInvisible(el) {
46
+ let node = el;
47
+ while (node && node.nodeType === 1) {
48
+ const s = window.getComputedStyle(node);
49
+ if (parseFloat(s.opacity) < 0.05 || s.visibility === 'hidden') return true;
50
+ node = node.parentElement;
51
+ }
52
+ return false;
53
+ }
54
+
55
+ function coveredByAnotherImage(el) {
56
+ if (effectivelyInvisible(el)) return true;
57
+ const r = el.getBoundingClientRect();
58
+ const x = r.left + r.width / 2;
59
+ const y = r.top + r.height / 2;
60
+ if (x < 0 || y < 0 || x >= window.innerWidth || y >= window.innerHeight) return false;
61
+ // Une diapositive transparente reste « au-dessus » pour le navigateur : on l'écarte.
62
+ const top = document.elementsFromPoint(x, y).find((n) => !effectivelyInvisible(n));
63
+ if (!top || top === el || el.contains(top) || top.contains(el)) return false;
64
+ const media = top.closest('img, picture, svg, video, canvas') || top.querySelector(':scope > img, :scope > picture');
65
+ return Boolean(media) && media !== el && !media.contains(el);
66
+ }
67
+
68
+ function collectImages() {
69
+ const d = dom();
70
+ const informative = [];
71
+ const decorative = [];
72
+ document.querySelectorAll('img, svg, [role="img"], input[type="image" i]').forEach((el) => {
73
+ if (el.localName === 'svg' && el.parentElement && el.parentElement.closest('svg')) return;
74
+ if (!visible(el)) return;
75
+ const rect = el.getBoundingClientRect();
76
+ if (rect.width < 8 || rect.height < 8) return;
77
+ if (coveredByAnotherImage(el)) return;
78
+ const role = d.explicitRole(el);
79
+ const hidden = d.isHiddenFromAT(el) || role === 'presentation' || role === 'none'
80
+ || (el.localName === 'img' && el.getAttribute('alt') === '');
81
+ if (hidden) {
82
+ decorative.push(item(el, el.getAttribute('src') ? el.getAttribute('src').split(/[?#]/)[0].split('/').pop() : `<${el.localName}>`, 'ignorée par les lecteurs d’écran'));
83
+ return;
84
+ }
85
+ if (el.localName === 'svg' && role !== 'img') return; // icône sans statut clair : traitée par l'audit automatique
86
+ const name = d.accessibleName(el);
87
+ if (name) informative.push(item(el, name, el.localName === 'img' ? 'alternative (alt)' : 'nom accessible'));
88
+ });
89
+ return { informative: informative.slice(0, MAX_ITEMS), decorative: decorative.slice(0, MAX_ITEMS) };
90
+ }
91
+
92
+ function collectLinks() {
93
+ const d = dom();
94
+ return [...document.querySelectorAll('a[href], [role="link"]')]
95
+ .filter((a) => visible(a) && !d.isHiddenFromAT(a))
96
+ .map((a) => item(a, d.accessibleName(a) || '(lien sans intitulé)', a.getAttribute('href') || ''))
97
+ .slice(0, MAX_ITEMS);
98
+ }
99
+
100
+ function collectTextLinks() {
101
+ const d = dom();
102
+ return [...document.querySelectorAll('p a[href], li a[href], td a[href], dd a[href], blockquote a[href]')]
103
+ .filter((a) => {
104
+ if (!visible(a) || a.closest('nav, [role="navigation"], [role="menu"], [role="menubar"]')) return false;
105
+ const container = a.closest('p, li, td, dd, blockquote');
106
+ const surrounding = [...container.childNodes]
107
+ .filter((n) => n.nodeType === 3 || (n.nodeType === 1 && !n.matches('a, button, ul, ol') && !n.querySelector('a, button')))
108
+ .map((n) => n.textContent).join(' ');
109
+ return d.normalizedText(surrounding).length >= 15;
110
+ })
111
+ .map((a) => item(a, d.accessibleName(a), 'lien au milieu du texte'))
112
+ .slice(0, MAX_ITEMS);
113
+ }
114
+
115
+ function collectHeadings() {
116
+ const d = dom();
117
+ return [...document.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"]')]
118
+ .filter((h) => !d.isHiddenFromAT(h))
119
+ .map((h) => {
120
+ const level = d.explicitRole(h) === 'heading' ? parseInt(h.getAttribute('aria-level'), 10) || 2 : parseInt(h.localName.slice(1), 10);
121
+ return { ...item(h, d.accessibleName(h) || '(titre vide)', `niveau ${level}`), level };
122
+ })
123
+ .slice(0, MAX_ITEMS);
124
+ }
125
+
126
+ const LANDMARKS = [
127
+ { selector: 'header, [role="banner"]', label: 'En-tête', test: (el) => el.getAttribute('role') === 'banner' || !el.closest('article, aside, main, nav, section') },
128
+ { selector: 'nav, [role="navigation"]', label: 'Navigation' },
129
+ { selector: 'main, [role="main"]', label: 'Contenu principal' },
130
+ { selector: 'aside, [role="complementary"]', label: 'Complémentaire' },
131
+ { selector: 'footer, [role="contentinfo"]', label: 'Pied de page', test: (el) => el.getAttribute('role') === 'contentinfo' || !el.closest('article, aside, main, nav, section') },
132
+ { selector: 'search, [role="search"]', label: 'Recherche' },
133
+ ];
134
+
135
+ function collectLandmarks() {
136
+ const d = dom();
137
+ const found = [];
138
+ for (const lm of LANDMARKS) {
139
+ document.querySelectorAll(lm.selector).forEach((el) => {
140
+ if (!visible(el) || d.isHiddenFromAT(el) || (lm.test && !lm.test(el))) return;
141
+ const name = d.normalizedText(el.getAttribute('aria-label'))
142
+ || (el.getAttribute('aria-labelledby') ? d.accessibleName(el) : '');
143
+ found.push(item(el, name ? `${lm.label} « ${name} »` : lm.label, `<${el.localName}>`));
144
+ });
145
+ }
146
+ return found;
147
+ }
148
+
149
+ /** Ordre de tabulation : tabindex positifs d'abord, puis l'ordre du document. */
150
+ function collectTabOrder() {
151
+ const d = dom();
152
+ const focusables = [...document.querySelectorAll('a[href], area[href], button, input:not([type="hidden"]), select, textarea, iframe, summary, [tabindex], [contenteditable=""], [contenteditable="true"], audio[controls], video[controls]')]
153
+ .filter((el) => d.isKeyboardFocusable(el));
154
+ const positive = focusables.filter((el) => parseInt(el.getAttribute('tabindex'), 10) > 0)
155
+ .sort((a, b) => parseInt(a.getAttribute('tabindex'), 10) - parseInt(b.getAttribute('tabindex'), 10));
156
+ const natural = focusables.filter((el) => !(parseInt(el.getAttribute('tabindex'), 10) > 0));
157
+ return [...positive, ...natural].slice(0, MAX_ITEMS)
158
+ .map((el, i) => ({ ...item(el, d.accessibleName(el) || d.visibleText(el) || `<${el.localName}>`, `<${el.localName}>`), order: i + 1 }));
159
+ }
160
+
161
+ function collectFrames() {
162
+ const d = dom();
163
+ return [...document.querySelectorAll('iframe, frame')]
164
+ .filter((f) => visible(f) && !d.isHiddenFromAT(f) && d.normalizedText(f.getAttribute('title')))
165
+ .map((f) => item(f, f.getAttribute('title'), f.getAttribute('src') || ''));
166
+ }
167
+
168
+ function collectFields() {
169
+ const d = dom();
170
+ return [...document.querySelectorAll('input:not([type="hidden" i]):not([type="submit" i]):not([type="button" i]):not([type="reset" i]):not([type="image" i]), select, textarea')]
171
+ .filter((f) => visible(f) && !d.isHiddenFromAT(f) && d.accessibleName(f))
172
+ .map((f) => item(f, d.accessibleName(f), f.localName === 'input' ? `champ ${f.type}` : f.localName === 'select' ? 'liste de choix' : 'zone de texte'))
173
+ .slice(0, MAX_ITEMS);
174
+ }
175
+
176
+ function collectButtons() {
177
+ const d = dom();
178
+ return [...document.querySelectorAll('button, input[type="submit" i], input[type="button" i], input[type="reset" i], [role="button"]')]
179
+ .filter((b) => visible(b) && !d.isHiddenFromAT(b) && d.accessibleName(b))
180
+ .map((b) => {
181
+ const shown = b.localName === 'input' ? b.value : d.visibleText(b);
182
+ return item(b, d.accessibleName(b), shown && d.normalizedText(shown) !== d.accessibleName(b) ? `affiché : « ${shown} »` : 'bouton');
183
+ })
184
+ .slice(0, MAX_ITEMS);
185
+ }
186
+
187
+ function collectMedia() {
188
+ const d = dom();
189
+ const media = [...document.querySelectorAll('video, audio')]
190
+ .filter((m) => m.localName === 'audio' || visible(m))
191
+ .map((m) => item(m, m.getAttribute('title') || m.getAttribute('aria-label') || (m.localName === 'video' ? 'Vidéo' : 'Son'),
192
+ m.querySelector('track[kind="captions"], track[kind="subtitles"]') ? 'piste de sous-titres présente' : 'aucune piste de sous-titres déclarée'));
193
+ const embeds = [...document.querySelectorAll('iframe')]
194
+ .filter((f) => MEDIA_EMBED_RE.test(f.src || f.getAttribute('data-src') || '') && visible(f))
195
+ .map((f) => item(f, f.getAttribute('title') || 'Média intégré', 'lecteur externe (YouTube, Vimeo…)'));
196
+ return [...media, ...embeds].slice(0, MAX_ITEMS);
197
+ }
198
+
199
+ function collectDocuments() {
200
+ const d = dom();
201
+ return [...document.querySelectorAll('a[href]')]
202
+ .filter((a) => OFFICE_DOC_RE.test(a.getAttribute('href')) && visible(a))
203
+ .map((a) => item(a, d.accessibleName(a), a.getAttribute('href').split(/[?#]/)[0].split('/').pop()))
204
+ .slice(0, MAX_ITEMS);
205
+ }
206
+
207
+ function inventory() {
208
+ const images = collectImages();
209
+ return {
210
+ url: location.href,
211
+ title: document.title,
212
+ lang: document.documentElement.getAttribute('lang') || '',
213
+ collections: {
214
+ imagesInformative: images.informative,
215
+ imagesDecorative: images.decorative,
216
+ frames: collectFrames(),
217
+ links: collectLinks(),
218
+ textLinks: collectTextLinks(),
219
+ headings: collectHeadings(),
220
+ landmarks: collectLandmarks(),
221
+ tabOrder: collectTabOrder(),
222
+ fields: collectFields(),
223
+ buttons: collectButtons(),
224
+ media: collectMedia(),
225
+ documents: collectDocuments(),
226
+ },
227
+ };
228
+ }
229
+
230
+ // ── Surimpressions ─────────────────────────
231
+
232
+ const OVERLAY_CSS = `
233
+ :host { all: initial; }
234
+ .layer { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 2147483646; }
235
+ .box { position: absolute; border: 3px solid #E6007E; box-shadow: 0 0 0 2px #FFFFFF, inset 0 0 0 1px #FFFFFF; border-radius: 3px; }
236
+ .box.soft { border-color: #0B5F73; }
237
+ .box.current { border-width: 4px; box-shadow: 0 0 0 3px #FFFFFF, 0 0 0 9999px rgba(0, 0, 0, 0.35); }
238
+ .tag { position: absolute; width: max-content; max-width: 320px; padding: 3px 7px; background: #111111; color: #FFFFFF; border: 2px solid #FFD400;
239
+ font: 600 13px/1.35 "Atkinson Hyperlegible", system-ui, sans-serif; border-radius: 4px; white-space: normal; overflow-wrap: anywhere; }
240
+ .tag.muted { background: #FFFFFF; color: #111111; border-color: #111111; font-style: italic; }
241
+ .num { position: absolute; min-width: 22px; height: 22px; padding: 0 4px; border-radius: 11px; background: #E6007E; color: #FFFFFF;
242
+ font: 700 12px/22px system-ui, sans-serif; text-align: center; border: 2px solid #FFFFFF; }
243
+ svg { position: absolute; left: 0; top: 0; overflow: visible; }
244
+ `;
245
+
246
+ let current = null;
247
+
248
+ function ensureLayer() {
249
+ let host = document.getElementById(HOST_ID);
250
+ if (!host) {
251
+ host = document.createElement('div');
252
+ host.id = HOST_ID;
253
+ host.setAttribute('aria-hidden', 'true');
254
+ host.style.cssText = 'position:absolute;left:0;top:0;width:0;height:0;z-index:2147483646;pointer-events:none;';
255
+ const shadow = host.attachShadow({ mode: 'open' });
256
+ const style = document.createElement('style');
257
+ style.textContent = OVERLAY_CSS;
258
+ shadow.appendChild(style);
259
+ const layer = document.createElement('div');
260
+ layer.className = 'layer';
261
+ shadow.appendChild(layer);
262
+ document.documentElement.appendChild(host);
263
+ }
264
+ const layer = host.shadowRoot.querySelector('.layer');
265
+ layer.replaceChildren();
266
+ return layer;
267
+ }
268
+
269
+ function pageRect(el) {
270
+ const r = el.getBoundingClientRect();
271
+ return { x: r.left + window.scrollX, y: r.top + window.scrollY, w: r.width, h: r.height };
272
+ }
273
+
274
+ function addBox(layer, el, { label = '', muted = false, soft = false, current: isCurrent = false } = {}) {
275
+ const r = pageRect(el);
276
+ if (r.w <= 0 && r.h <= 0) return null;
277
+ const box = document.createElement('div');
278
+ box.className = `box${soft ? ' soft' : ''}${isCurrent ? ' current' : ''}`;
279
+ box.style.cssText = `left:${r.x - 3}px;top:${r.y - 3}px;width:${r.w + 6}px;height:${r.h + 6}px;`;
280
+ layer.appendChild(box);
281
+ if (label) {
282
+ const tag = document.createElement('div');
283
+ tag.className = `tag${muted ? ' muted' : ''}`;
284
+ tag.textContent = label;
285
+ // L'étiquette reste dans la largeur de la page, même pour un élément collé au bord droit.
286
+ const maxLeft = Math.max(0, document.documentElement.scrollWidth - 340);
287
+ tag.style.cssText = `left:${Math.max(0, Math.min(r.x - 3, maxLeft))}px;top:${r.y + r.h + 6}px;`;
288
+ layer.appendChild(tag);
289
+ }
290
+ return r;
291
+ }
292
+
293
+ function query(key) {
294
+ try {
295
+ return document.querySelector(key);
296
+ } catch {
297
+ return null;
298
+ }
299
+ }
300
+
301
+ const AIDS = {
302
+ alternatives(layer) {
303
+ const { informative, decorative } = collectImages();
304
+ informative.forEach((i) => { const el = query(i.key); if (el) addBox(layer, el, { label: i.label }); });
305
+ decorative.forEach((i) => { const el = query(i.key); if (el) addBox(layer, el, { label: 'Décorative (ignorée)', muted: true, soft: true }); });
306
+ return informative.length + decorative.length;
307
+ },
308
+ headings(layer) {
309
+ const list = collectHeadings();
310
+ list.forEach((h) => { const el = query(h.key); if (el) addBox(layer, el, { label: `H${h.level} · ${h.label}`, soft: true }); });
311
+ return list.length;
312
+ },
313
+ landmarks(layer) {
314
+ const list = collectLandmarks();
315
+ list.forEach((l) => { const el = query(l.key); if (el) addBox(layer, el, { label: l.label, soft: true }); });
316
+ return list.length;
317
+ },
318
+ links(layer) {
319
+ const list = collectLinks();
320
+ list.forEach((l) => { const el = query(l.key); if (el) addBox(layer, el, { label: l.label }); });
321
+ return list.length;
322
+ },
323
+ taborder(layer) {
324
+ const list = collectTabOrder();
325
+ const points = [];
326
+ list.forEach((t) => {
327
+ const el = query(t.key);
328
+ if (!el) return;
329
+ const r = pageRect(el);
330
+ if (r.w <= 0 && r.h <= 0) return;
331
+ const num = document.createElement('div');
332
+ num.className = 'num';
333
+ num.textContent = String(t.order);
334
+ num.style.cssText = `left:${r.x - 10}px;top:${r.y - 10}px;`;
335
+ layer.appendChild(num);
336
+ points.push(`${r.x + 1},${r.y + 1}`);
337
+ });
338
+ if (points.length > 1) {
339
+ const ns = 'http://www.w3.org/2000/svg';
340
+ const svg = document.createElementNS(ns, 'svg');
341
+ svg.setAttribute('width', '1');
342
+ svg.setAttribute('height', '1');
343
+ const line = document.createElementNS(ns, 'polyline');
344
+ line.setAttribute('points', points.join(' '));
345
+ line.setAttribute('fill', 'none');
346
+ line.setAttribute('stroke', '#E6007E');
347
+ line.setAttribute('stroke-width', '2');
348
+ line.setAttribute('stroke-dasharray', '6 4');
349
+ svg.appendChild(line);
350
+ layer.insertBefore(svg, layer.firstChild);
351
+ }
352
+ return list.length;
353
+ },
354
+ grayscale() {
355
+ if (!document.getElementById(GRAYSCALE_ID)) {
356
+ const style = document.createElement('style');
357
+ style.id = GRAYSCALE_ID;
358
+ style.textContent = 'html { filter: grayscale(1) !important; }';
359
+ document.head.appendChild(style);
360
+ }
361
+ return 1;
362
+ },
363
+ };
364
+
365
+ const REFRESH_MS = 800;
366
+ let highlighted = null;
367
+ let timer = null;
368
+
369
+ function drawHighlight(layer) {
370
+ if (!highlighted) return;
371
+ const el = query(highlighted.key);
372
+ if (!el) return;
373
+ if (effectivelyInvisible(el) || coveredByAnotherImage(el) || !el.isConnected) {
374
+ const r = pageRect(el);
375
+ const tag = document.createElement('div');
376
+ tag.className = 'tag';
377
+ tag.textContent = 'Cet élément n’est plus affiché (carrousel ?) : mettez le défilement en pause.';
378
+ tag.style.cssText = `left:${Math.max(0, r.x)}px;top:${Math.max(0, r.y)}px;`;
379
+ layer.appendChild(tag);
380
+ return;
381
+ }
382
+ addBox(layer, el, { label: highlighted.caption || '', current: true });
383
+ }
384
+
385
+ /**
386
+ * Redessine les cadres d'après l'état actuel de la page : les carrousels et contenus
387
+ * animés changent après l'analyse, des cadres figés seraient faux.
388
+ */
389
+ function render() {
390
+ if (!current && !highlighted) return;
391
+ const layer = ensureLayer();
392
+ if (current && current.name !== 'grayscale') AIDS[current.name](layer);
393
+ drawHighlight(layer);
394
+ }
395
+
396
+ function startLive() {
397
+ if (timer) return;
398
+ timer = setInterval(render, REFRESH_MS);
399
+ window.addEventListener('resize', render);
400
+ }
401
+
402
+ function stopLive() {
403
+ if (timer) clearInterval(timer);
404
+ timer = null;
405
+ window.removeEventListener('resize', render);
406
+ }
407
+
408
+ function showAid(name) {
409
+ clear();
410
+ const aid = AIDS[name];
411
+ if (!aid) throw new Error(`Aide inconnue : ${name}`);
412
+ const count = aid(ensureLayer());
413
+ current = { type: 'aid', name };
414
+ startLive();
415
+ return count;
416
+ }
417
+
418
+ /** Met en évidence un élément (fait défiler jusqu'à lui) en gardant l'aide active. */
419
+ function highlight(key, caption) {
420
+ const el = query(key);
421
+ if (!el) return false;
422
+ el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
423
+ highlighted = { key, caption };
424
+ render();
425
+ startLive();
426
+ return true;
427
+ }
428
+
429
+ function clear() {
430
+ stopLive();
431
+ const host = document.getElementById(HOST_ID);
432
+ if (host) host.remove();
433
+ const gray = document.getElementById(GRAYSCALE_ID);
434
+ if (gray) gray.remove();
435
+ current = null;
436
+ highlighted = null;
437
+ return true;
438
+ }
439
+
440
+ root.RgaaGuidePage = { VERSION, inventory, showAid, highlight, clear, AIDS: Object.keys(AIDS) };
441
+ })(typeof globalThis !== 'undefined' ? globalThis : this);