@kinti/a11y-toolkit 5.25.2 → 5.27.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/README.md +1 -1
- package/a11y_toolkit/a11y.py +31 -4
- package/a11y_toolkit/a11yact.py +9 -1
- package/a11y_toolkit/a11yannotate.py +185 -0
- package/a11y_toolkit/a11yaudit.py +903 -186
- package/a11y_toolkit/a11ybadge.py +24 -17
- package/a11y_toolkit/a11ybudget.py +145 -1
- package/a11y_toolkit/a11ycorpus.py +58 -24
- package/a11y_toolkit/a11ycrit.py +110 -53
- package/a11y_toolkit/a11ydiff.py +104 -34
- package/a11y_toolkit/a11ydisprove.py +15 -8
- package/a11y_toolkit/a11ydocx.py +8 -6
- package/a11y_toolkit/a11ydom.py +451 -96
- package/a11y_toolkit/a11yen301549.py +147 -0
- package/a11y_toolkit/a11yengines.py +157 -0
- package/a11y_toolkit/a11yevidence.py +182 -36
- package/a11y_toolkit/a11yfix.py +131 -52
- package/a11y_toolkit/a11yinit.py +30 -5
- package/a11y_toolkit/a11yjourney.py +110 -4
- package/a11y_toolkit/a11yledger.py +119 -12
- package/a11y_toolkit/a11ylocate.py +247 -0
- package/a11y_toolkit/a11yopenacr.py +28 -7
- package/a11y_toolkit/a11ypatches.py +154 -0
- package/a11y_toolkit/a11ypatterns.py +344 -0
- package/a11y_toolkit/a11ypdf.py +109 -53
- package/a11y_toolkit/a11yrgaa.py +60 -0
- package/a11y_toolkit/a11yroute.py +34 -12
- package/a11y_toolkit/a11ysarif.py +70 -21
- package/a11y_toolkit/a11yscope.py +296 -0
- package/a11y_toolkit/a11yscroll.py +7 -5
- package/a11y_toolkit/a11ystatement.py +30 -6
- package/a11y_toolkit/a11ytrace.py +293 -0
- package/a11y_toolkit/a11yvalidate.py +21 -15
- package/a11y_toolkit/a11yvpat.py +54 -11
- package/a11y_toolkit/a11yvtt.py +22 -6
- package/a11y_toolkit/a11ywiz.py +121 -0
- package/a11y_toolkit/contrast.py +62 -24
- package/a11y_toolkit/locales/en.json +222 -24
- package/a11y_toolkit/locales/es.json +223 -25
- package/a11y_toolkit/rgaa.json +2661 -0
- package/a11y_toolkit/server.py +247 -59
- package/package.json +2 -2
- package/a11y_toolkit/a11yplan.py +0 -214
- package/a11y_toolkit/a11ywcagem.py +0 -237
package/a11y_toolkit/a11ydom.py
CHANGED
|
@@ -22,6 +22,27 @@ import sys
|
|
|
22
22
|
from .a11yaudit import CRIT, T, compute_score
|
|
23
23
|
from .contrast import parse_color, decode_png, sample_rgb, hexs, luminance, ratio
|
|
24
24
|
|
|
25
|
+
# textos de las funciones renderizadas que NO viven en locales (errores de
|
|
26
|
+
# carga y limits): bilingües aquí, igual que el catálogo (invariante es/en)
|
|
27
|
+
_LOAD_ERR = {'es': 'no se pudo cargar: {e}',
|
|
28
|
+
'en': 'could not load: {e}'}
|
|
29
|
+
_LIMITS_HCM = {
|
|
30
|
+
'es': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
|
|
31
|
+
'coloreados hardcoded en SVG suelen caer al heredado con '
|
|
32
|
+
'forced-colors. La comprobación definitiva es visual con '
|
|
33
|
+
'Windows High Contrast — esto la prepara, no la sustituye.'),
|
|
34
|
+
'en': ('Review heuristic (1.4.3/1.4.11 under HCM): hardcoded SVG fills '
|
|
35
|
+
'usually fall back to inherited under forced-colors. The definitive '
|
|
36
|
+
'check is visual on Windows High Contrast — this prepares it, '
|
|
37
|
+
'it does not replace it.'),
|
|
38
|
+
}
|
|
39
|
+
_LIMITS_MOTION = {
|
|
40
|
+
'es': ('Mide CSS animations y video[autoplay]. No cubre animaciones '
|
|
41
|
+
'JS/WebGL ni parallax por scroll — revisión manual.'),
|
|
42
|
+
'en': ('Measures CSS animations and video[autoplay]. Does not cover '
|
|
43
|
+
'JS/WebGL animations or scroll parallax — manual review.'),
|
|
44
|
+
}
|
|
45
|
+
|
|
25
46
|
from . import a11yi18n
|
|
26
47
|
# browser pool: Chromium reutilizable entre llamadas consecutivas
|
|
27
48
|
_POOL = {'playwright': None, 'browser': None, 'type': None}
|
|
@@ -71,7 +92,7 @@ def _detect_browser(pw, preferred=None):
|
|
|
71
92
|
def _get_browser(pw, headless=True, preferred=None):
|
|
72
93
|
"""Devuelve un browser del pool (o crea uno si no existe)."""
|
|
73
94
|
if _POOL['browser'] is not None and _POOL['browser'].is_connected() and \
|
|
74
|
-
_POOL['type'] ==
|
|
95
|
+
(preferred in (None, 'auto') or _POOL['type'] == preferred):
|
|
75
96
|
return _POOL['browser']
|
|
76
97
|
_close_pool()
|
|
77
98
|
br, kind = _detect_browser(pw, preferred)
|
|
@@ -104,10 +125,51 @@ def _t(lang, key, n=None):
|
|
|
104
125
|
|
|
105
126
|
|
|
106
127
|
# ------------------------------------------------------------------- JS -----
|
|
128
|
+
# Accessible-name computation, spliced into _JS below. Module-level so the
|
|
129
|
+
# accname PRECEDENCE is pinnable by test_dom as a plain string (no browser
|
|
130
|
+
# needed): labelledby (multi-id list, texts joined in order) > aria-label >
|
|
131
|
+
# implicit <label> > content > title. Static string — no page data ever lands
|
|
132
|
+
# here.
|
|
133
|
+
_JS_NAMEOF = r'''
|
|
134
|
+
const nameOf = el => {
|
|
135
|
+
let n = '';
|
|
136
|
+
// 1. aria-labelledby: a whitespace-SEPARATED id list — resolve each id
|
|
137
|
+
// within the root (shadow roots carry getElementById too), join the
|
|
138
|
+
// name texts in ORDER, skip missing ids (accname step 2B)
|
|
139
|
+
if (el.getAttribute('aria-labelledby')) {
|
|
140
|
+
const root = el.getRootNode();
|
|
141
|
+
const byId = id => (root.getElementById ? root.getElementById(id)
|
|
142
|
+
: root.querySelector('#' + CSS.escape(id)));
|
|
143
|
+
const parts = [];
|
|
144
|
+
for (const id of el.getAttribute('aria-labelledby').trim().split(/\s+/)) {
|
|
145
|
+
const ref = byId(id);
|
|
146
|
+
if (ref) parts.push((ref.innerText || '').trim());
|
|
147
|
+
}
|
|
148
|
+
n = parts.join(' ').trim();
|
|
149
|
+
}
|
|
150
|
+
// 2. aria-label
|
|
151
|
+
if (!n) n = (el.getAttribute('aria-label') || '').trim();
|
|
152
|
+
// 3. implicit <label>
|
|
153
|
+
if (!n && el.labels && el.labels[0]) n = el.labels[0].innerText.trim();
|
|
154
|
+
// 4. content: input value/image alt, element text, descendant img alt
|
|
155
|
+
if (!n && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type)) n = el.value || '';
|
|
156
|
+
if (!n && el.tagName === 'INPUT' && el.type === 'image') n = el.alt || '';
|
|
157
|
+
if (!n && ['A', 'BUTTON', 'SUMMARY'].includes(el.tagName)) {
|
|
158
|
+
n = (el.innerText || '').trim();
|
|
159
|
+
// accname: a descendant image's alt contributes to the link's name
|
|
160
|
+
if (!n) { const im = el.querySelector('img[alt]'); if (im) n = (im.getAttribute('alt') || '').trim(); }
|
|
161
|
+
}
|
|
162
|
+
if (!n && el.tagName === 'IMG') n = el.getAttribute('alt') || '';
|
|
163
|
+
// 5. title — the LAST resort in the accname order
|
|
164
|
+
if (!n) n = (el.getAttribute('title') || '').trim();
|
|
165
|
+
return n.trim();
|
|
166
|
+
};
|
|
167
|
+
'''
|
|
168
|
+
|
|
107
169
|
_JS = r'''(maxEj) => {
|
|
108
170
|
const INTER = 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [tabindex]';
|
|
109
171
|
const out = { contrast: {}, contrastReview: 0, contrastZones: [], targets: [], unnamed: [], fields: [],
|
|
110
|
-
imgs: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
|
|
172
|
+
imgs: [], canvasNoName: [], chartsNoEquiv: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
|
|
111
173
|
blank: 0, videos: 0, videoSubs: 0, tables: 0, tableTh: 0,
|
|
112
174
|
focus: [], focusFail: [], focusContrast: [], focusObscured: [], marks: 0,
|
|
113
175
|
ids: {}, lang: null, title: '', viewport: null, refresh: null,
|
|
@@ -144,6 +206,28 @@ _JS = r'''(maxEj) => {
|
|
|
144
206
|
return s.visibility !== 'hidden' && s.display !== 'none' && parseFloat(s.opacity || '1') > 0.05
|
|
145
207
|
&& !el.closest('[aria-hidden="true"]');
|
|
146
208
|
};
|
|
209
|
+
const visText = el => {
|
|
210
|
+
if (!vis(el)) return false;
|
|
211
|
+
const s = getComputedStyle(el);
|
|
212
|
+
const ti = parseFloat(s.textIndent) || 0;
|
|
213
|
+
if (ti < -100 && (['hidden', 'clip'].includes(s.overflow) || ['hidden', 'clip'].includes(s.overflowX) || ['hidden', 'clip'].includes(s.overflowY))) return false;
|
|
214
|
+
if (s.position === 'absolute' && (s.clip !== 'auto' || s.clipPath !== 'none')) {
|
|
215
|
+
const r = el.getBoundingClientRect();
|
|
216
|
+
if (r.width <= 2 && r.height <= 2) return false;
|
|
217
|
+
}
|
|
218
|
+
return true;
|
|
219
|
+
};
|
|
220
|
+
const hasVisibleText = el => {
|
|
221
|
+
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
|
|
222
|
+
let n;
|
|
223
|
+
while ((n = walker.nextNode())) {
|
|
224
|
+
const txt = (n.nodeValue || '').trim();
|
|
225
|
+
if (!txt) continue;
|
|
226
|
+
const p = n.parentElement;
|
|
227
|
+
if (p && visText(p)) return true;
|
|
228
|
+
}
|
|
229
|
+
return false;
|
|
230
|
+
};
|
|
147
231
|
const path = el => {
|
|
148
232
|
let p = el.tagName.toLowerCase();
|
|
149
233
|
if (el.id) return '#' + el.id;
|
|
@@ -212,6 +296,7 @@ _JS = r'''(maxEj) => {
|
|
|
212
296
|
}
|
|
213
297
|
if (!el || el.closest('script, style, noscript, svg title')) continue;
|
|
214
298
|
if (!vis(el)) continue;
|
|
299
|
+
if (!visText(el)) continue;
|
|
215
300
|
// text_ de solo símbolos (±±±@@) o UN carácter ASCII (X de cerrar):
|
|
216
301
|
// contenido no verbal — sin requisito. CUALQUIER letra/dígito de
|
|
217
302
|
// cualquier alfabeto (CJK, cirílico, árabe…) ES text_ verbal
|
|
@@ -400,26 +485,7 @@ _JS = r'''(maxEj) => {
|
|
|
400
485
|
}
|
|
401
486
|
|
|
402
487
|
// ---- nombres accesibles renderizados ----
|
|
403
|
-
|
|
404
|
-
let n = (el.getAttribute('aria-label') || '').trim();
|
|
405
|
-
if (!n && el.labels && el.labels[0]) n = el.labels[0].innerText.trim();
|
|
406
|
-
if (!n && el.getAttribute('aria-labelledby')) {
|
|
407
|
-
const root = el.getRootNode();
|
|
408
|
-
const ref = root.getElementById ? root.getElementById(el.getAttribute('aria-labelledby'))
|
|
409
|
-
: root.querySelector('#' + CSS.escape(el.getAttribute('aria-labelledby')));
|
|
410
|
-
if (ref) n = (ref.innerText || '').trim();
|
|
411
|
-
}
|
|
412
|
-
if (!n) n = (el.getAttribute('title') || '').trim();
|
|
413
|
-
if (!n && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type)) n = el.value || '';
|
|
414
|
-
if (!n && el.tagName === 'INPUT' && el.type === 'image') n = el.alt || '';
|
|
415
|
-
if (!n && ['A', 'BUTTON', 'SUMMARY'].includes(el.tagName)) {
|
|
416
|
-
n = (el.innerText || '').trim();
|
|
417
|
-
// accname: a descendant image's alt contributes to the link's name
|
|
418
|
-
if (!n) { const im = el.querySelector('img[alt]'); if (im) n = (im.getAttribute('alt') || '').trim(); }
|
|
419
|
-
}
|
|
420
|
-
if (!n && el.tagName === 'IMG') n = el.getAttribute('alt') || '';
|
|
421
|
-
return n.trim();
|
|
422
|
-
};
|
|
488
|
+
/*__NAMEOF__*/
|
|
423
489
|
for (const el of deepQ('a[href], button, summary, [role="button"], [role="link"]')) {
|
|
424
490
|
if (!vis(el) || el.closest('[aria-hidden="true"]')) continue;
|
|
425
491
|
if (!nameOf(el) && out.unnamed.length < 30) out.unnamed.push(path(el));
|
|
@@ -433,6 +499,43 @@ _JS = r'''(maxEj) => {
|
|
|
433
499
|
if (!vis(el)) continue;
|
|
434
500
|
if (!el.hasAttribute('alt') && out.imgs.length < 30) out.imgs.push(el.getAttribute('src') || '');
|
|
435
501
|
}
|
|
502
|
+
// canvas: el pase rendered es el JUEZ del nombre computado (el estático es
|
|
503
|
+
// filtro — la capa suele inyectarse por JS al renderizar el gráfico)
|
|
504
|
+
for (const el of deepQ('canvas')) {
|
|
505
|
+
if (!vis(el)) continue;
|
|
506
|
+
const _role = (el.getAttribute('role') || '').toLowerCase();
|
|
507
|
+
if (_role === 'presentation' || _role === 'none') continue;
|
|
508
|
+
if (el.closest('[aria-hidden="true"]')) continue;
|
|
509
|
+
const _fallback = (el.textContent || '').trim();
|
|
510
|
+
if (!nameOf(el) && !_fallback && out.canvasNoName.length < 20)
|
|
511
|
+
out.canvasNoName.push(path(el));
|
|
512
|
+
}
|
|
513
|
+
// charts CON nombre: ¿hay equivalente de datos visible para la máquina?
|
|
514
|
+
// (aria-details / aria-describedby resolubles, o una tabla en el entorno).
|
|
515
|
+
// Hallazgo de REVISIÓN (low): si los datos viven en prosa cercana, pasa.
|
|
516
|
+
const _chartName = el => (el.getAttribute('aria-label') || '').trim()
|
|
517
|
+
|| (el.getAttribute('title') || '').trim()
|
|
518
|
+
|| [...el.querySelectorAll('title')].map(t => t.textContent.trim())[0]
|
|
519
|
+
|| ((el.getAttribute('aria-labelledby') || '').split(/\s+/)
|
|
520
|
+
.filter(Boolean).some(id => document.getElementById(id)) ? 'named' : '');
|
|
521
|
+
for (const el of deepQ('canvas, svg[role="img"]')) {
|
|
522
|
+
if (!vis(el)) continue;
|
|
523
|
+
if (el.closest('[aria-hidden="true"]')) continue;
|
|
524
|
+
const _r = (el.getAttribute('role') || '').toLowerCase();
|
|
525
|
+
if (el.tagName.toLowerCase() === 'svg' && _r !== 'img') continue;
|
|
526
|
+
if (!_chartName(el)) continue; // sin nombre: ya lo acusan las señales de nombre
|
|
527
|
+
let _equiv = [...(el.getAttribute('aria-details') || '').split(/\s+/),
|
|
528
|
+
...(el.getAttribute('aria-describedby') || '').split(/\s+/)]
|
|
529
|
+
.filter(Boolean).some(id => document.getElementById(id));
|
|
530
|
+
if (!_equiv) {
|
|
531
|
+
// solo el entorno SEMÁNTICO (figure/section/celda/lista) cuenta como
|
|
532
|
+
// "cerca" — el parent genérico contaminaría (la tabla de OTRO chart
|
|
533
|
+
// en el mismo main haría pasar a todos)
|
|
534
|
+
const _scope = el.closest('figure, section, td, li');
|
|
535
|
+
_equiv = !!(_scope && _scope.querySelector('table'));
|
|
536
|
+
}
|
|
537
|
+
if (!_equiv && out.chartsNoEquiv.length < 15) out.chartsNoEquiv.push(path(el));
|
|
538
|
+
}
|
|
436
539
|
for (const el of deepQ('iframe')) {
|
|
437
540
|
if (!((el.getAttribute('title') || '').trim() || (el.getAttribute('aria-label') || '').trim())
|
|
438
541
|
&& out.iframes.length < 20) out.iframes.push(el.getAttribute('src') || '');
|
|
@@ -518,8 +621,10 @@ _JS = r'''(maxEj) => {
|
|
|
518
621
|
if (fgf && !bgf.image) {
|
|
519
622
|
const fs = parseFloat(s.fontSize) || 16;
|
|
520
623
|
const isLarge = fs >= 24 || (fs >= 18.66 && (parseInt(s.fontWeight) || 400) >= 700);
|
|
624
|
+
const hasText = hasVisibleText(el);
|
|
625
|
+
const threshold = !hasText ? 3.0 : (isLarge ? 3.0 : 4.5);
|
|
521
626
|
const rf2 = ratioOf(over(fgf, bgf), bgf);
|
|
522
|
-
if (rf2 <
|
|
627
|
+
if (rf2 < threshold && out.focusContrast.length < 20)
|
|
523
628
|
out.focusContrast.push({ example: path(el), ratio: Math.round(rf2 * 100) / 100 });
|
|
524
629
|
}
|
|
525
630
|
// (2.4.11 por parada se cubre abajo con la causa raíz)
|
|
@@ -539,7 +644,8 @@ _JS = r'''(maxEj) => {
|
|
|
539
644
|
if (prevFocus && prevFocus.blur) { try { prevFocus.focus(); } catch (e) {} }
|
|
540
645
|
|
|
541
646
|
return out;
|
|
542
|
-
}'''
|
|
647
|
+
}''' # /*__NAMEOF__*/ is spliced in below — keep nameOf in _JS_NAMEOF only
|
|
648
|
+
_JS = _JS.replace('/*__NAMEOF__*/', _JS_NAMEOF.strip('\n'))
|
|
543
649
|
|
|
544
650
|
|
|
545
651
|
def _add(findings, lang, severity, code, key, examples=None, **fmt):
|
|
@@ -643,6 +749,12 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
|
|
|
643
749
|
if data.get('imgs'):
|
|
644
750
|
_add(findings, lang, 'high', '1.1.1', 'img_no_alt',
|
|
645
751
|
examples=data['imgs'], n=len(data['imgs']))
|
|
752
|
+
if data.get('canvasNoName'):
|
|
753
|
+
_add(findings, lang, 'high', '1.1.1', 'canvas_no_accessible_layer',
|
|
754
|
+
examples=data['canvasNoName'], n=len(data['canvasNoName']))
|
|
755
|
+
if data.get('chartsNoEquiv'):
|
|
756
|
+
_add(findings, lang, 'low', '1.1.1', 'chart_no_data_equivalent',
|
|
757
|
+
examples=data['chartsNoEquiv'], n=len(data['chartsNoEquiv']))
|
|
646
758
|
if data.get('ariaHidden'):
|
|
647
759
|
_add(findings, lang, 'high', '4.1.2', 'aria_hidden_focusable',
|
|
648
760
|
n=len(data['ariaHidden']), tag='control')
|
|
@@ -660,7 +772,7 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
|
|
|
660
772
|
if re.search(r'user-scalable\s*=\s*(no|0)', vp, re.I):
|
|
661
773
|
_add(findings, lang, 'high', '1.4.4', 'zoom_no')
|
|
662
774
|
elif (m := re.search(r'maximum-scale\s*=\s*([\d.]+)', vp, re.I)) and float(m.group(1)) < 2:
|
|
663
|
-
_add(findings, lang, '
|
|
775
|
+
_add(findings, lang, 'high', '1.4.4', 'zoom_max', v=m.group(1))
|
|
664
776
|
if data.get('refresh'):
|
|
665
777
|
m = re.match(r'\s*(\d+)', str(data['refresh']))
|
|
666
778
|
segs = int(m.group(1)) if m else 0
|
|
@@ -669,14 +781,14 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
|
|
|
669
781
|
_add(findings, lang, 'medium', '2.4.3', 'tabindex_pos',
|
|
670
782
|
examples=data['tabindex'], n=len(data['tabindex']))
|
|
671
783
|
if not (data.get('main') or data.get('skip')):
|
|
672
|
-
_add(findings, lang, '
|
|
784
|
+
_add(findings, lang, 'low', '2.4.1', 'no_bypass')
|
|
673
785
|
|
|
674
786
|
levels = [h['lvl'] for h in (data.get('headings') or []) if h['text']]
|
|
675
787
|
h1s = sum(1 for h in data.get('headings') or [] if h['lvl'] == 1 and h['text'])
|
|
676
788
|
empties = sum(1 for h in data.get('headings') or [] if not h['text'])
|
|
677
789
|
if levels:
|
|
678
790
|
if h1s == 0:
|
|
679
|
-
_add(findings, lang, '
|
|
791
|
+
_add(findings, lang, 'low', '1.3.1', 'no_h1')
|
|
680
792
|
elif h1s > 1:
|
|
681
793
|
_add(findings, lang, 'low', '1.3.1', 'multi_h1', n=h1s)
|
|
682
794
|
prev, jumps = 0, []
|
|
@@ -688,7 +800,7 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
|
|
|
688
800
|
_add(findings, lang, 'low', '1.3.1', 'heading_skips',
|
|
689
801
|
skips=', '.join(jumps[:5]))
|
|
690
802
|
else:
|
|
691
|
-
_add(findings, lang, '
|
|
803
|
+
_add(findings, lang, 'low', '1.3.1', 'no_headings')
|
|
692
804
|
if empties:
|
|
693
805
|
_add(findings, lang, 'low', '1.3.1', 'empty_heading', n=empties)
|
|
694
806
|
tables, con_th = data.get('tables', 0), data.get('tableTh', 0)
|
|
@@ -786,7 +898,7 @@ _JS_FORM_STATE = r'''(pre) => {
|
|
|
786
898
|
suggested: 0, native: 0 };
|
|
787
899
|
for (const el of f.querySelectorAll(FIELDS_JS)) {
|
|
788
900
|
if (el.disabled) continue;
|
|
789
|
-
info.
|
|
901
|
+
info.fields++;
|
|
790
902
|
const key = (el.name || el.id || el.type) + '@' + (f.id || f.action || '');
|
|
791
903
|
const shot_before = pre[key] || {};
|
|
792
904
|
let identified = false, sugerido = false;
|
|
@@ -826,13 +938,13 @@ _JS_FORM_STATE = r'''(pre) => {
|
|
|
826
938
|
return out;
|
|
827
939
|
}'''
|
|
828
940
|
|
|
829
|
-
def audit_forms(url, timeout=45, lang='en', auth_state=None):
|
|
941
|
+
def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
830
942
|
"""3.3.1 Error Identification / 3.3.3 Error Suggestion — the guided flow:
|
|
831
943
|
fill every validatable field with INVALID data, really submit, then judge
|
|
832
944
|
how errors are identified and announced in the post-submit DOM."""
|
|
833
945
|
from playwright.sync_api import sync_playwright
|
|
834
946
|
with sync_playwright() as p:
|
|
835
|
-
nav = p
|
|
947
|
+
nav = _get_browser(p, preferred=browser)
|
|
836
948
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
837
949
|
page = ctx.new_page() if auth_state else nav.new_page()
|
|
838
950
|
try:
|
|
@@ -857,7 +969,7 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None):
|
|
|
857
969
|
'remediation': _t(lang, key + '_rem').format(**fmt)})
|
|
858
970
|
|
|
859
971
|
if navigated:
|
|
860
|
-
add('low', '3.3.1', 'form_navigated', example=
|
|
972
|
+
add('low', '3.3.1', 'form_navigated', example='submit')
|
|
861
973
|
elif touched and state is not None:
|
|
862
974
|
unidentified = [f['form'] for f in state['forms']
|
|
863
975
|
if f['fields'] and f['identified'] == 0 and f['native'] == 0
|
|
@@ -891,56 +1003,64 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
|
891
1003
|
structure; this function returns it as prose an agent can READ and
|
|
892
1004
|
understand from a blind user's perspective.
|
|
893
1005
|
"""
|
|
1006
|
+
# J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga
|
|
1007
|
+
# de proceso por llamada en un servidor MCP de larga vida
|
|
894
1008
|
from playwright.sync_api import sync_playwright
|
|
895
1009
|
pw = sync_playwright().start()
|
|
896
|
-
nav = _get_browser(pw, preferred=browser)
|
|
897
|
-
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
898
|
-
page = ctx.new_page() if auth_state else nav.new_page()
|
|
899
|
-
try:
|
|
900
|
-
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
901
|
-
page.wait_for_timeout(400)
|
|
902
|
-
except Exception as e:
|
|
903
|
-
ctx.close()
|
|
904
|
-
_close_pool()
|
|
905
|
-
return {'error': str(e)[:100]}
|
|
906
|
-
|
|
907
1010
|
try:
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1011
|
+
nav = _get_browser(pw, preferred=browser)
|
|
1012
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1013
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1014
|
+
try:
|
|
1015
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1016
|
+
page.wait_for_timeout(400)
|
|
1017
|
+
except Exception as e:
|
|
1018
|
+
ctx.close()
|
|
1019
|
+
_close_pool()
|
|
1020
|
+
return {'error': str(e)[:100]}
|
|
915
1021
|
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
1022
|
+
try:
|
|
1023
|
+
tree = page.locator('body').aria_snapshot()
|
|
1024
|
+
except Exception:
|
|
1025
|
+
tree = None
|
|
1026
|
+
try:
|
|
1027
|
+
ctx.close()
|
|
1028
|
+
except Exception:
|
|
1029
|
+
pass
|
|
919
1030
|
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
for line in tree.split('\n'):
|
|
924
|
-
stripped = line.strip()
|
|
925
|
-
if not stripped.startswith('- '):
|
|
926
|
-
continue
|
|
927
|
-
# quitar el guion inicial; el resto es el anuncio
|
|
928
|
-
announcement = stripped[2:].rstrip(':')
|
|
929
|
-
if announcement:
|
|
930
|
-
announcements.append(announcement)
|
|
1031
|
+
if not tree:
|
|
1032
|
+
return {'url': url, 'mode': 'sr-transcript',
|
|
1033
|
+
'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
|
|
931
1034
|
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
'
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
1035
|
+
# parse the YAML-like snapshot into linearized announcements
|
|
1036
|
+
import re
|
|
1037
|
+
announcements = []
|
|
1038
|
+
for line in tree.split('\n'):
|
|
1039
|
+
stripped = line.strip()
|
|
1040
|
+
if not stripped.startswith('- '):
|
|
1041
|
+
continue
|
|
1042
|
+
# quitar el guion inicial; el resto es el anuncio
|
|
1043
|
+
announcement = stripped[2:].rstrip(':')
|
|
1044
|
+
if announcement:
|
|
1045
|
+
announcements.append(announcement)
|
|
1046
|
+
|
|
1047
|
+
return {
|
|
1048
|
+
'url': url,
|
|
1049
|
+
'mode': 'sr-transcript',
|
|
1050
|
+
'announcements': announcements[:200], # cap
|
|
1051
|
+
'total': len(announcements),
|
|
1052
|
+
'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
|
|
1053
|
+
'note': ('Linearized announcement order — what a screen reader user hears. '
|
|
1054
|
+
'Roles and names as computed by the browser. Use this to understand '
|
|
1055
|
+
'the page from a blind user\'s perspective.'),
|
|
1056
|
+
}
|
|
942
1057
|
|
|
943
1058
|
|
|
1059
|
+
finally:
|
|
1060
|
+
try:
|
|
1061
|
+
pw.stop()
|
|
1062
|
+
except Exception: # noqa: BLE001
|
|
1063
|
+
pass
|
|
944
1064
|
_JS_HOVER_TEST = r'''() => {
|
|
945
1065
|
// find elements that show tooltips/overlays on hover
|
|
946
1066
|
const candidates = [];
|
|
@@ -959,11 +1079,11 @@ _JS_HOVER_TEST = r'''() => {
|
|
|
959
1079
|
return candidates;
|
|
960
1080
|
}'''
|
|
961
1081
|
|
|
962
|
-
def audit_hover(url, timeout=45, lang='en', auth_state=None):
|
|
1082
|
+
def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
963
1083
|
"""1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?"""
|
|
964
1084
|
from playwright.sync_api import sync_playwright
|
|
965
1085
|
with sync_playwright() as p:
|
|
966
|
-
nav = p
|
|
1086
|
+
nav = _get_browser(p, preferred=browser)
|
|
967
1087
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
968
1088
|
page = ctx.new_page() if auth_state else nav.new_page()
|
|
969
1089
|
try:
|
|
@@ -1142,14 +1262,14 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
|
1142
1262
|
el layout)."""
|
|
1143
1263
|
from playwright.sync_api import sync_playwright
|
|
1144
1264
|
with sync_playwright() as p:
|
|
1145
|
-
nav = p
|
|
1265
|
+
nav = _get_browser(p, preferred=browser)
|
|
1146
1266
|
page = nav.new_page(viewport={'width': 1280, 'height': 800})
|
|
1147
1267
|
try:
|
|
1148
1268
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1149
1269
|
page.wait_for_timeout(300)
|
|
1150
1270
|
except Exception as e: # noqa: BLE001
|
|
1151
1271
|
nav.close()
|
|
1152
|
-
return {'error':
|
|
1272
|
+
return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
|
|
1153
1273
|
|
|
1154
1274
|
page.set_viewport_size({'width': 320, 'height': 800})
|
|
1155
1275
|
page.wait_for_timeout(500)
|
|
@@ -1215,7 +1335,7 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1215
1335
|
"""
|
|
1216
1336
|
from playwright.sync_api import sync_playwright
|
|
1217
1337
|
with sync_playwright() as p:
|
|
1218
|
-
nav = p
|
|
1338
|
+
nav = _get_browser(p, preferred=browser)
|
|
1219
1339
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1220
1340
|
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1221
1341
|
try:
|
|
@@ -1223,7 +1343,7 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1223
1343
|
page.wait_for_timeout(400)
|
|
1224
1344
|
except Exception as e: # noqa: BLE001
|
|
1225
1345
|
nav.close()
|
|
1226
|
-
return {'error':
|
|
1346
|
+
return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
|
|
1227
1347
|
|
|
1228
1348
|
page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
|
|
1229
1349
|
" e.removeAttribute('data-a11ystop'); e.removeAttribute('data-a11yruta'); })")
|
|
@@ -1496,7 +1616,7 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
|
|
|
1496
1616
|
from .a11yaudit import _t as _t_audit, CRIT, compute_score
|
|
1497
1617
|
|
|
1498
1618
|
with sync_playwright() as p:
|
|
1499
|
-
nav = p
|
|
1619
|
+
nav = _get_browser(p, preferred=browser)
|
|
1500
1620
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1501
1621
|
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1502
1622
|
try:
|
|
@@ -1528,10 +1648,7 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
|
|
|
1528
1648
|
'findings': findings,
|
|
1529
1649
|
'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
|
|
1530
1650
|
for s2 in ('high', 'medium', 'low')},
|
|
1531
|
-
'limits': ('
|
|
1532
|
-
'coloreados hardcoded en SVG suelen caer al heredado con '
|
|
1533
|
-
'forced-colors. La comprobación definitiva es visual con '
|
|
1534
|
-
'Windows High Contrast — esto la prepara, no la sustituye.'),
|
|
1651
|
+
'limits': _LIMITS_HCM.get(lang, _LIMITS_HCM['en']),
|
|
1535
1652
|
}
|
|
1536
1653
|
|
|
1537
1654
|
|
|
@@ -1565,7 +1682,7 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
|
|
|
1565
1682
|
from .a11yaudit import _t as _t_audit, CRIT, compute_score
|
|
1566
1683
|
|
|
1567
1684
|
with sync_playwright() as p:
|
|
1568
|
-
nav = p
|
|
1685
|
+
nav = _get_browser(p, preferred=browser)
|
|
1569
1686
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1570
1687
|
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1571
1688
|
try:
|
|
@@ -1600,8 +1717,7 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
|
|
|
1600
1717
|
'findings': findings,
|
|
1601
1718
|
'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
|
|
1602
1719
|
for s2 in ('high', 'medium', 'low')},
|
|
1603
|
-
'limits': (
|
|
1604
|
-
'animaciones JS/WebGL ni parallax por scroll — revisión manual.'),
|
|
1720
|
+
'limits': _LIMITS_MOTION.get(lang, _LIMITS_MOTION['en']),
|
|
1605
1721
|
}
|
|
1606
1722
|
|
|
1607
1723
|
|
|
@@ -1614,7 +1730,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
|
|
|
1614
1730
|
iniciada) para auditar detrás de login."""
|
|
1615
1731
|
from playwright.sync_api import sync_playwright
|
|
1616
1732
|
with sync_playwright() as p:
|
|
1617
|
-
nav = p
|
|
1733
|
+
nav = _get_browser(p, preferred=browser)
|
|
1618
1734
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1619
1735
|
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1620
1736
|
if color_scheme in ('dark', 'light'):
|
|
@@ -1627,7 +1743,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
|
|
|
1627
1743
|
except Exception as e: # noqa: BLE001
|
|
1628
1744
|
if not page.content() or page.url in ('about:blank', ''):
|
|
1629
1745
|
nav.close()
|
|
1630
|
-
return {'error':
|
|
1746
|
+
return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
|
|
1631
1747
|
try:
|
|
1632
1748
|
data = page.evaluate(_JS, MAX_EXAMPLES)
|
|
1633
1749
|
# 1.4.12: inject the WCAG spacing overrides, count clipped texts
|
|
@@ -1695,7 +1811,7 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
|
|
|
1695
1811
|
from .contrast import T as _TC
|
|
1696
1812
|
t9 = _TC.get(lang, _TC['es'])
|
|
1697
1813
|
with sync_playwright() as p:
|
|
1698
|
-
nav = p
|
|
1814
|
+
nav = _get_browser(p, preferred=browser)
|
|
1699
1815
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1700
1816
|
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1701
1817
|
try:
|
|
@@ -1745,23 +1861,243 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
|
|
|
1745
1861
|
pass
|
|
1746
1862
|
|
|
1747
1863
|
|
|
1864
|
+
# --- contrast walk: perceptual pass over EVERY rendered text element --------
|
|
1865
|
+
|
|
1866
|
+
_JS_WALK = r'''(maxEls) => {
|
|
1867
|
+
const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
|
|
1868
|
+
const directText = el => [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
|
|
1869
|
+
const parseC = s => { const m = String(s).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/);
|
|
1870
|
+
return m ? {r:+m[1], g:+m[2], b:+m[3], a: m[4] === undefined ? 1 : +m[4]} : null; };
|
|
1871
|
+
const effBg = el => {
|
|
1872
|
+
const layers = [];
|
|
1873
|
+
let image = null, n = el;
|
|
1874
|
+
while (n && n.nodeType === 1) {
|
|
1875
|
+
const cs = getComputedStyle(n);
|
|
1876
|
+
if (!image && cs.backgroundImage && cs.backgroundImage !== 'none') image = cs.backgroundImage;
|
|
1877
|
+
const c = parseC(cs.backgroundColor);
|
|
1878
|
+
if (c) { layers.push(c); if (c.a >= 1) break; }
|
|
1879
|
+
n = n.parentElement;
|
|
1880
|
+
}
|
|
1881
|
+
let r = 255, g = 255, b = 255;
|
|
1882
|
+
for (let i = layers.length - 1; i >= 0; i--) {
|
|
1883
|
+
const L = layers[i];
|
|
1884
|
+
r = L.r * L.a + r * (1 - L.a); g = L.g * L.a + g * (1 - L.a); b = L.b * L.a + b * (1 - L.a);
|
|
1885
|
+
}
|
|
1886
|
+
return {r: Math.round(r), g: Math.round(g), b: Math.round(b), image};
|
|
1887
|
+
};
|
|
1888
|
+
const path = el => {
|
|
1889
|
+
const parts = [];
|
|
1890
|
+
let n = el, depth = 0;
|
|
1891
|
+
while (n && n.nodeType === 1 && depth < 5) {
|
|
1892
|
+
if (n.id) { parts.unshift('#' + (window.CSS && CSS.escape ? CSS.escape(n.id) : n.id)); break; }
|
|
1893
|
+
const parent = n.parentElement;
|
|
1894
|
+
if (!parent) { parts.unshift(n.tagName.toLowerCase()); break; }
|
|
1895
|
+
const same = [...parent.children].filter(c => c.tagName === n.tagName);
|
|
1896
|
+
let s = n.tagName.toLowerCase();
|
|
1897
|
+
if (same.length > 1) s += ':nth-of-type(' + (same.indexOf(n) + 1) + ')';
|
|
1898
|
+
parts.unshift(s);
|
|
1899
|
+
n = parent; depth++;
|
|
1900
|
+
}
|
|
1901
|
+
return parts.join(' > ') || 'body';
|
|
1902
|
+
};
|
|
1903
|
+
const out = [];
|
|
1904
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
1905
|
+
if (out.length >= maxEls) break;
|
|
1906
|
+
if (!visible(el) || !directText(el)) continue;
|
|
1907
|
+
const cs = getComputedStyle(el);
|
|
1908
|
+
const color = parseC(cs.color);
|
|
1909
|
+
if (!color) continue;
|
|
1910
|
+
if (color.a < 1) { out.push({skip: 'translucent', path: path(el)}); continue; }
|
|
1911
|
+
const fs = parseFloat(cs.fontSize) || 16;
|
|
1912
|
+
const fw = parseInt(cs.fontWeight) || 400;
|
|
1913
|
+
const bg = effBg(el);
|
|
1914
|
+
out.push({path: path(el), tag: el.tagName.toLowerCase(),
|
|
1915
|
+
text: (el.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 60),
|
|
1916
|
+
color, bg: {r: bg.r, g: bg.g, b: bg.b, a: 1},
|
|
1917
|
+
bg_image: bg.image ? bg.image.slice(0, 100) : null,
|
|
1918
|
+
font_px: Math.round(fs * 10) / 10, bold: fw >= 700});
|
|
1919
|
+
}
|
|
1920
|
+
return out;
|
|
1921
|
+
}'''
|
|
1922
|
+
|
|
1923
|
+
|
|
1924
|
+
def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
1925
|
+
lang='en', timeout=45, auth_state=None, browser='auto'):
|
|
1926
|
+
"""Contraste PERCIBIDO de cada text_ renderizado de la página (1.4.3).
|
|
1927
|
+
|
|
1928
|
+
La capa informe de la familia de contraste: donde audit_dom audita y
|
|
1929
|
+
contrast-dom mide UN elemento contra lo que sea que tenga detrás, el walk
|
|
1930
|
+
recorre TODOS los text_ visibles y emite la tabla por elemento que consume
|
|
1931
|
+
un equipo de design system: ratio real, umbral (4.5 normal / 3.0 large por
|
|
1932
|
+
font-size/weight computados), verdict_ y sugerencia de color. Los fondos
|
|
1933
|
+
con imagen/gradiente se miden por PIXELES (peor caso, misma mecánica que
|
|
1934
|
+
contrast-dom) hasta max_sample; el resto queda honestamente sin medir.
|
|
1935
|
+
Con dark=True repite el pase bajo prefers-color-scheme: dark y añade el
|
|
1936
|
+
delta (nuevos fallos / resueltos) — la condición de display que el CSS
|
|
1937
|
+
declarado no ve.
|
|
1938
|
+
|
|
1939
|
+
Filtro honesto, no veredicto: text_ en shadow DOM, canvas, vídeo y
|
|
1940
|
+
pseudo-elementos no se captura; lo no medido se declara, jamás inventado.
|
|
1941
|
+
"""
|
|
1942
|
+
from playwright.sync_api import sync_playwright
|
|
1943
|
+
from .contrast import ratio as _ratio, suggest as _suggest, parse_color
|
|
1944
|
+
|
|
1945
|
+
def _verdicts(entries):
|
|
1946
|
+
for e in entries:
|
|
1947
|
+
if e['ratio'] is not None:
|
|
1948
|
+
e['verdict'] = 'pass' if e['ratio'] >= e['threshold'] else 'fail'
|
|
1949
|
+
|
|
1950
|
+
def _pass(page):
|
|
1951
|
+
raw = page.evaluate(_JS_WALK, max_walk)
|
|
1952
|
+
entries, shot_jobs, skipped = [], [], 0
|
|
1953
|
+
for row in raw:
|
|
1954
|
+
if row.get('skip') == 'translucent':
|
|
1955
|
+
skipped += 1
|
|
1956
|
+
continue
|
|
1957
|
+
fg = {k: row['color'][k] for k in ('r', 'g', 'b')}
|
|
1958
|
+
bg = {k: row['bg'][k] for k in ('r', 'g', 'b')}
|
|
1959
|
+
large = row['font_px'] >= 24 or (row['font_px'] >= 18.66 and row['bold'])
|
|
1960
|
+
thr = 3.0 if large else 4.5
|
|
1961
|
+
entry = {'path': row['path'], 'tag': row['tag'], 'text': row['text'],
|
|
1962
|
+
'font_px': row['font_px'], 'bold': row['bold'],
|
|
1963
|
+
'large_text': large, 'threshold': thr,
|
|
1964
|
+
'color': hexs(fg), 'bg': hexs(bg),
|
|
1965
|
+
'bg_image': row['bg_image'], 'pixel_sampled': False,
|
|
1966
|
+
'ratio': None, 'verdict': 'unmeasured'}
|
|
1967
|
+
if row['bg_image']:
|
|
1968
|
+
shot_jobs.append((entry, fg))
|
|
1969
|
+
else:
|
|
1970
|
+
entry['ratio'] = round(_ratio(fg, bg), 2)
|
|
1971
|
+
entries.append(entry)
|
|
1972
|
+
sampled = 0
|
|
1973
|
+
for entry, fg in shot_jobs:
|
|
1974
|
+
if sampled >= max_sample:
|
|
1975
|
+
continue # stays unmeasured — honest cap, never invented
|
|
1976
|
+
try:
|
|
1977
|
+
loc = page.locator(entry['path']).first
|
|
1978
|
+
box = loc.bounding_box()
|
|
1979
|
+
if not box or box['width'] < 3 or box['height'] < 3:
|
|
1980
|
+
continue
|
|
1981
|
+
m = _samples_background(loc, box, fg)
|
|
1982
|
+
if m:
|
|
1983
|
+
entry['ratio'] = m['worst_ratio']
|
|
1984
|
+
entry['median_ratio'] = m['median_ratio']
|
|
1985
|
+
entry['pixel_sampled'] = True
|
|
1986
|
+
sampled += 1
|
|
1987
|
+
except Exception: # noqa: BLE001 — one dead locator must not kill the walk
|
|
1988
|
+
continue
|
|
1989
|
+
_verdicts(entries)
|
|
1990
|
+
return entries, skipped
|
|
1991
|
+
|
|
1992
|
+
def _summarize(entries, skipped):
|
|
1993
|
+
fails = [e for e in entries if e['verdict'] == 'fail']
|
|
1994
|
+
worst = min((e for e in entries if e['ratio'] is not None),
|
|
1995
|
+
key=lambda e: e['ratio'], default=None)
|
|
1996
|
+
return {'pass': sum(1 for e in entries if e['verdict'] == 'pass'),
|
|
1997
|
+
'fail': len(fails),
|
|
1998
|
+
'unmeasured': sum(1 for e in entries if e['verdict'] == 'unmeasured'),
|
|
1999
|
+
'fails_4_5_normal_text': sum(1 for e in fails if e['threshold'] >= 4.5),
|
|
2000
|
+
'fails_3_0_large_text': sum(1 for e in fails if e['threshold'] < 4.5),
|
|
2001
|
+
'translucent_text_skipped': skipped,
|
|
2002
|
+
'pixel_sampled': sum(1 for e in entries if e['pixel_sampled']),
|
|
2003
|
+
'worst_ratio': worst['ratio'] if worst else None,
|
|
2004
|
+
'worst_element': worst['path'] if worst else None}
|
|
2005
|
+
|
|
2006
|
+
with sync_playwright() as p:
|
|
2007
|
+
def _run(scheme):
|
|
2008
|
+
nav = _get_browser(p, preferred=browser)
|
|
2009
|
+
ctx = (nav.new_context(storage_state=auth_state, color_scheme=scheme)
|
|
2010
|
+
if auth_state else nav.new_context(color_scheme=scheme))
|
|
2011
|
+
page = ctx.new_page()
|
|
2012
|
+
try:
|
|
2013
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
2014
|
+
page.wait_for_timeout(300)
|
|
2015
|
+
return _pass(page)
|
|
2016
|
+
finally:
|
|
2017
|
+
try:
|
|
2018
|
+
ctx.close()
|
|
2019
|
+
nav.close()
|
|
2020
|
+
except Exception: # noqa: BLE001
|
|
2021
|
+
pass
|
|
2022
|
+
|
|
2023
|
+
entries, skipped = _run('light')
|
|
2024
|
+
report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
|
|
2025
|
+
'checked': len(entries),
|
|
2026
|
+
'elements': entries,
|
|
2027
|
+
'summary': _summarize(entries, skipped)}
|
|
2028
|
+
|
|
2029
|
+
# suggestions for the worst flat-background fails (pixel zones have no
|
|
2030
|
+
# single background to suggest against — honest skip)
|
|
2031
|
+
fails = sorted((e for e in entries if e['verdict'] == 'fail' and not e['bg_image']),
|
|
2032
|
+
key=lambda e: e['ratio'])
|
|
2033
|
+
for e in fails[:8]:
|
|
2034
|
+
s = _suggest(parse_color(e['color']), parse_color(e['bg']),
|
|
2035
|
+
target=e['threshold'], lang=lang)
|
|
2036
|
+
if s:
|
|
2037
|
+
e['suggestion'] = s
|
|
2038
|
+
|
|
2039
|
+
if dark:
|
|
2040
|
+
entries_d, skipped_d = _run('dark')
|
|
2041
|
+
report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
|
|
2042
|
+
'elements': entries_d,
|
|
2043
|
+
'summary': _summarize(entries_d, skipped_d)}
|
|
2044
|
+
light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
|
|
2045
|
+
dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
|
|
2046
|
+
report['dark_delta'] = {
|
|
2047
|
+
'new_fails': sorted(dark_fails - light_fails)[:20],
|
|
2048
|
+
'resolved': sorted(light_fails - dark_fails)[:20],
|
|
2049
|
+
'note': ('a site that ignores prefers-color-scheme shows a zero '
|
|
2050
|
+
'delta: same colors in both passes')}
|
|
2051
|
+
|
|
2052
|
+
report['limits'] = (
|
|
2053
|
+
'Computed ratios cover effective background-color with alpha '
|
|
2054
|
+
'compositing; text over images/gradients is pixel-sampled '
|
|
2055
|
+
'(worst-case) up to the cap, the rest is declared unmeasured. Text '
|
|
2056
|
+
'in shadow DOM, canvas, video and pseudo-elements is not captured. '
|
|
2057
|
+
'A fail is a filter finding (1.4.3), not a verdict — judge the '
|
|
2058
|
+
'zone with contrast-dom.'
|
|
2059
|
+
if lang == 'en' else
|
|
2060
|
+
'Los ratios computados cubren background-color efectivo con '
|
|
2061
|
+
'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
|
|
2062
|
+
'por píxeles (peor caso) hasta el tope y el resto se declara sin '
|
|
2063
|
+
'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
|
|
2064
|
+
'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
|
|
2065
|
+
'veredicto — juzga la zona con contrast-dom.')
|
|
2066
|
+
return report
|
|
2067
|
+
|
|
2068
|
+
|
|
1748
2069
|
def contrast_dom_main(argv):
|
|
1749
|
-
ap = argparse.ArgumentParser(description='Real text-over-anything contrast: screenshot + pixel sampling (auto-region)')
|
|
2070
|
+
ap = argparse.ArgumentParser(description='Real text-over-anything contrast: screenshot + pixel sampling (auto-region); --walk = perceptual pass over every text element')
|
|
1750
2071
|
ap.add_argument('url')
|
|
1751
|
-
ap.add_argument('--selector',
|
|
2072
|
+
ap.add_argument('--selector', help='CSS selector of the text element (required without --walk)')
|
|
2073
|
+
ap.add_argument('--walk', action='store_true',
|
|
2074
|
+
help='perceptual pass over every rendered text element (per-element table + suggestions)')
|
|
2075
|
+
ap.add_argument('--max-walk', type=int, default=400, help='max elements collected per pass (default 400)')
|
|
2076
|
+
ap.add_argument('--max-sample', type=int, default=24, help='max image/gradient backgrounds pixel-sampled (default 24)')
|
|
2077
|
+
ap.add_argument('--dark', action='store_true', help='add a second pass under prefers-color-scheme: dark + delta')
|
|
1752
2078
|
ap.add_argument('--text', help='text color (default: computed from the element)')
|
|
1753
2079
|
ap.add_argument('--sample', type=int, default=4)
|
|
1754
2080
|
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
1755
2081
|
ap.add_argument('--timeout', type=int, default=45)
|
|
1756
2082
|
a = ap.parse_args(argv)
|
|
1757
2083
|
try:
|
|
1758
|
-
|
|
1759
|
-
|
|
2084
|
+
if a.walk:
|
|
2085
|
+
if not a.selector:
|
|
2086
|
+
res = contrast_walk(a.url, max_walk=a.max_walk, max_sample=a.max_sample,
|
|
2087
|
+
dark=a.dark, lang=a.lang, timeout=a.timeout)
|
|
2088
|
+
else:
|
|
2089
|
+
res = {'error': '--walk covers the whole page: drop --selector'}
|
|
2090
|
+
else:
|
|
2091
|
+
if not a.selector:
|
|
2092
|
+
res = {'error': 'need --selector ".hero h1" (or --walk for the whole page)'}
|
|
2093
|
+
else:
|
|
2094
|
+
res = contrast_dom(a.url, a.selector, text_color=a.text, sample=a.sample,
|
|
2095
|
+
lang=a.lang, timeout=a.timeout)
|
|
1760
2096
|
except ImportError:
|
|
1761
2097
|
print(json.dumps({'error': 'Playwright not installed'}))
|
|
1762
2098
|
return 1
|
|
1763
2099
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1764
|
-
return 0
|
|
2100
|
+
return 1 if isinstance(res, dict) and 'error' in res else 0
|
|
1765
2101
|
|
|
1766
2102
|
|
|
1767
2103
|
def main(argv):
|
|
@@ -1827,5 +2163,24 @@ def kbd_main(argv):
|
|
|
1827
2163
|
return 0
|
|
1828
2164
|
|
|
1829
2165
|
|
|
2166
|
+
def hover_main(argv):
|
|
2167
|
+
# the same audit the MCP tool a11y_hover runs (audit_hover, verbatim) —
|
|
2168
|
+
# 1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?
|
|
2169
|
+
ap = argparse.ArgumentParser(description='Tooltip dismissibility (1.4.13): hover + Escape, real browser')
|
|
2170
|
+
ap.add_argument('url')
|
|
2171
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
2172
|
+
ap.add_argument('--timeout', type=int, default=45)
|
|
2173
|
+
ap.add_argument('--auth-state', dest='auth_state',
|
|
2174
|
+
help='Path to a Playwright storage_state JSON to audit behind login')
|
|
2175
|
+
a = ap.parse_args(argv)
|
|
2176
|
+
try:
|
|
2177
|
+
res = audit_hover(a.url, timeout=a.timeout, lang=a.lang, auth_state=a.auth_state)
|
|
2178
|
+
except ImportError:
|
|
2179
|
+
print(json.dumps({'error': 'Playwright not installed'}))
|
|
2180
|
+
return 1
|
|
2181
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
2182
|
+
return 0
|
|
2183
|
+
|
|
2184
|
+
|
|
1830
2185
|
if __name__ == '__main__':
|
|
1831
2186
|
sys.exit(main(sys.argv[1:]))
|