@kinti/a11y-toolkit 5.22.0 → 5.22.2
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/a11y_toolkit/__init__.py +5 -0
- package/a11y_toolkit/a11y.py +115 -0
- package/a11y_toolkit/a11yact.py +167 -0
- package/a11y_toolkit/a11yaudit.py +1951 -0
- package/a11y_toolkit/a11ybadge.py +102 -0
- package/a11y_toolkit/a11ybudget.py +122 -0
- package/a11y_toolkit/a11ycrit.py +1017 -0
- package/a11y_toolkit/a11ydiff.py +192 -0
- package/a11y_toolkit/a11ydisprove.py +175 -0
- package/a11y_toolkit/a11ydocx.py +132 -0
- package/a11y_toolkit/a11ydom.py +1831 -0
- package/a11y_toolkit/a11yevidence.py +272 -0
- package/a11y_toolkit/a11yfix.py +330 -0
- package/a11y_toolkit/a11yi18n.py +100 -0
- package/a11y_toolkit/a11yinit.py +113 -0
- package/a11y_toolkit/a11yjourney.py +284 -0
- package/a11y_toolkit/a11yledger.py +210 -0
- package/a11y_toolkit/a11ymutants.py +406 -0
- package/a11y_toolkit/a11yopenacr.py +207 -0
- package/a11y_toolkit/a11ypdf.py +273 -0
- package/a11y_toolkit/a11yroute.py +378 -0
- package/a11y_toolkit/a11ysarif.py +139 -0
- package/a11y_toolkit/a11yscroll.py +212 -0
- package/a11y_toolkit/a11ystatement.py +158 -0
- package/a11y_toolkit/a11yvalidate.py +127 -0
- package/a11y_toolkit/a11yvpat.py +238 -0
- package/a11y_toolkit/a11yvtt.py +136 -0
- package/a11y_toolkit/a11ywcag3.py +262 -0
- package/a11y_toolkit/arialive.js +107 -0
- package/a11y_toolkit/arialive_js.py +113 -0
- package/a11y_toolkit/contrast.py +536 -0
- package/a11y_toolkit/locales/_template.json +468 -0
- package/a11y_toolkit/locales/en.json +525 -0
- package/a11y_toolkit/locales/es.json +525 -0
- package/a11y_toolkit/server.py +1529 -0
- package/bin/a11y-toolkit-mcp.cjs +2 -2
- package/bin/a11y-toolkit.cjs +2 -2
- package/lib/runner.cjs +30 -22
- package/package.json +2 -1
|
@@ -0,0 +1,1831 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""RENDERED accessibility audit via Playwright (what static HTML cannot see).
|
|
3
|
+
|
|
4
|
+
a11y_audit_dom loads the URL in Chromium and evaluates the computed DOM:
|
|
5
|
+
text contrast against effective backgrounds with alpha compositing, 24×24
|
|
6
|
+
target size (WCAG 2.2's 2.5.8), focus indicator heuristic, :focus/:hover state
|
|
7
|
+
contrast, open shadow DOM, same-origin iframes — plus the static signals on
|
|
8
|
+
the live DOM.
|
|
9
|
+
|
|
10
|
+
Requires local Playwright: pip install playwright && playwright install chromium.
|
|
11
|
+
Honest heuristics — a filter, not a verdict.
|
|
12
|
+
|
|
13
|
+
CLI:
|
|
14
|
+
a11ydom.py https://example.com [--lang es] [--timeout 45]
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
from .a11yaudit import CRIT, T, compute_score
|
|
23
|
+
from .contrast import parse_color, decode_png, sample_rgb, hexs, luminance, ratio
|
|
24
|
+
|
|
25
|
+
from . import a11yi18n
|
|
26
|
+
# browser pool: Chromium reutilizable entre llamadas consecutivas
|
|
27
|
+
_POOL = {'playwright': None, 'browser': None, 'type': None}
|
|
28
|
+
|
|
29
|
+
# cadena de detección: el primer navegador disponible gana.
|
|
30
|
+
# El usuario puede forzar con el parámetro 'browser' (chromium, firefox,
|
|
31
|
+
# webkit, chrome, msedge) o dejar 'auto' para que use lo que tenga.
|
|
32
|
+
_CHAIN = [
|
|
33
|
+
('chromium', lambda pw: pw.chromium.launch(headless=True)),
|
|
34
|
+
('firefox', lambda pw: pw.firefox.launch(headless=True)),
|
|
35
|
+
('webkit', lambda pw: pw.webkit.launch(headless=True)),
|
|
36
|
+
('chrome', lambda pw: pw.chromium.launch(channel='chrome', headless=True)),
|
|
37
|
+
('msedge', lambda pw: pw.chromium.launch(channel='msedge', headless=True)),
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
_BROWSER_BY_PARAM = {
|
|
41
|
+
'chromium': lambda pw: pw.chromium.launch(headless=True),
|
|
42
|
+
'firefox': lambda pw: pw.firefox.launch(headless=True),
|
|
43
|
+
'webkit': lambda pw: pw.webkit.launch(headless=True),
|
|
44
|
+
'chrome': lambda pw: pw.chromium.launch(channel='chrome', headless=True),
|
|
45
|
+
'msedge': lambda pw: pw.chromium.launch(channel='msedge', headless=True),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _detect_browser(pw, preferred=None):
|
|
50
|
+
"""Devuelve (browser, nombre). Usa el preferido si está disponible,
|
|
51
|
+
si no prueba la cadena completa y devuelve el primero que arranque."""
|
|
52
|
+
if preferred and preferred != 'auto':
|
|
53
|
+
fn = _BROWSER_BY_PARAM.get(preferred)
|
|
54
|
+
if fn:
|
|
55
|
+
try:
|
|
56
|
+
br = fn(pw)
|
|
57
|
+
return br, preferred
|
|
58
|
+
except Exception:
|
|
59
|
+
pass
|
|
60
|
+
for name, fn in _CHAIN:
|
|
61
|
+
try:
|
|
62
|
+
br = fn(pw)
|
|
63
|
+
return br, name
|
|
64
|
+
except Exception:
|
|
65
|
+
continue
|
|
66
|
+
raise RuntimeError(
|
|
67
|
+
'ningún navegador disponible. Instala uno: '
|
|
68
|
+
'pip install playwright && playwright install chromium')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _get_browser(pw, headless=True, preferred=None):
|
|
72
|
+
"""Devuelve un browser del pool (o crea uno si no existe)."""
|
|
73
|
+
if _POOL['browser'] is not None and _POOL['browser'].is_connected() and \
|
|
74
|
+
_POOL['type'] == (preferred or 'auto'):
|
|
75
|
+
return _POOL['browser']
|
|
76
|
+
_close_pool()
|
|
77
|
+
br, kind = _detect_browser(pw, preferred)
|
|
78
|
+
_POOL['browser'] = br
|
|
79
|
+
_POOL['type'] = kind
|
|
80
|
+
return br
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _close_pool():
|
|
84
|
+
"""Cierra el pool (llamar al terminar el proceso o bajo demanda)."""
|
|
85
|
+
if _POOL['browser']:
|
|
86
|
+
try:
|
|
87
|
+
_POOL['browser'].close()
|
|
88
|
+
except Exception:
|
|
89
|
+
pass
|
|
90
|
+
_POOL['browser'] = None
|
|
91
|
+
_POOL['playwright'] = None
|
|
92
|
+
|
|
93
|
+
MAX_EXAMPLES = 6
|
|
94
|
+
|
|
95
|
+
_TD = a11yi18n.pair('dom') # locales/<lang>.json — community-editable
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _t(lang, key, n=None):
|
|
100
|
+
"""Message by key; `{"one","other"}` entries resolve via the locale's
|
|
101
|
+
CLDR plural rule when the caller passes the count."""
|
|
102
|
+
value = _TD.get(lang, _TD['es']).get(key) or T.get(lang, T['es']).get(key, key)
|
|
103
|
+
return a11yi18n.plural_entry(value, lang, n) if n is not None else value
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ------------------------------------------------------------------- JS -----
|
|
107
|
+
_JS = r'''(maxEj) => {
|
|
108
|
+
const INTER = 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [tabindex]';
|
|
109
|
+
const out = { contrast: {}, contrastReview: 0, contrastZones: [], targets: [], unnamed: [], fields: [],
|
|
110
|
+
imgs: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
|
|
111
|
+
blank: 0, videos: 0, videoSubs: 0, tables: 0, tableTh: 0,
|
|
112
|
+
focus: [], focusFail: [], focusContrast: [], focusObscured: [], marks: 0,
|
|
113
|
+
ids: {}, lang: null, title: '', viewport: null, refresh: null,
|
|
114
|
+
main: false, skip: false, elements: 0, shadow_roots: 0,
|
|
115
|
+
colorOnly: [], orderInversions: 0, loopingAnims: 0 };
|
|
116
|
+
const fixed_els = [...document.querySelectorAll('*')].filter(el => {
|
|
117
|
+
const s = getComputedStyle(el);
|
|
118
|
+
return (s.position === 'fixed' || s.position === 'sticky') && s.display !== 'none'
|
|
119
|
+
&& el.getBoundingClientRect().height > 8;
|
|
120
|
+
}).slice(0, 12);
|
|
121
|
+
|
|
122
|
+
// ---- raíces: document + shadow roots ABIERTOS (tope 20, profundidad 6) ----
|
|
123
|
+
const roots = [document];
|
|
124
|
+
const collectRoots = (base, prof) => {
|
|
125
|
+
if (prof > 6 || roots.length >= 20) return;
|
|
126
|
+
for (const el of base.querySelectorAll('*')) {
|
|
127
|
+
if (el.shadowRoot) { roots.push(el.shadowRoot); collectRoots(el.shadowRoot, prof + 1); }
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
try { collectRoots(document, 0); } catch (e) { /* no bloquear por raíces */ }
|
|
131
|
+
out.shadow_roots = roots.length - 1;
|
|
132
|
+
const deepQ = sel => {
|
|
133
|
+
const acc = [];
|
|
134
|
+
for (const r of roots) {
|
|
135
|
+
for (const el of r.querySelectorAll(sel)) { acc.push(el); if (acc.length >= 600) return acc; }
|
|
136
|
+
}
|
|
137
|
+
return acc;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const vis = el => {
|
|
141
|
+
const r = el.getBoundingClientRect();
|
|
142
|
+
if (r.width < 1 || r.height < 1) return false;
|
|
143
|
+
const s = getComputedStyle(el);
|
|
144
|
+
return s.visibility !== 'hidden' && s.display !== 'none' && parseFloat(s.opacity || '1') > 0.05
|
|
145
|
+
&& !el.closest('[aria-hidden="true"]');
|
|
146
|
+
};
|
|
147
|
+
const path = el => {
|
|
148
|
+
let p = el.tagName.toLowerCase();
|
|
149
|
+
if (el.id) return '#' + el.id;
|
|
150
|
+
let n = el, depth = 0;
|
|
151
|
+
while (n && depth < 3) {
|
|
152
|
+
if (n === document.body) break;
|
|
153
|
+
if (!n.parentElement && n.getRootNode && n.getRootNode().host) {
|
|
154
|
+
n = n.getRootNode().host;
|
|
155
|
+
p = (n.id ? '#' + n.id : n.tagName.toLowerCase()) + ' ::slotted> ' + p;
|
|
156
|
+
depth++;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (!n.parentElement) break;
|
|
160
|
+
n = n.parentElement;
|
|
161
|
+
p = n.tagName.toLowerCase() + (n.id ? '#' + n.id : '') + ' > ' + p;
|
|
162
|
+
depth++;
|
|
163
|
+
}
|
|
164
|
+
return p;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// ---- contraste real: fondo efectivo con composición de alfas ----
|
|
168
|
+
const parseCol = c => {
|
|
169
|
+
const m = /rgba?\(([^)]+)\)/.exec(c || '');
|
|
170
|
+
if (!m) return null;
|
|
171
|
+
const p = m[1].split(',').map(x => parseFloat(x));
|
|
172
|
+
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
|
|
173
|
+
};
|
|
174
|
+
const over = (fg, bg) => ({
|
|
175
|
+
r: Math.round(fg.r * fg.a + bg.r * (1 - fg.a)),
|
|
176
|
+
g: Math.round(fg.g * fg.a + bg.g * (1 - fg.a)),
|
|
177
|
+
b: Math.round(fg.b * fg.a + bg.b * (1 - fg.a)), a: 1 });
|
|
178
|
+
const bgOf = el => {
|
|
179
|
+
const stack = [];
|
|
180
|
+
let n = el;
|
|
181
|
+
while (n) {
|
|
182
|
+
const s = getComputedStyle(n);
|
|
183
|
+
if (s.backgroundImage && s.backgroundImage !== 'none') return { image: true };
|
|
184
|
+
const c = parseCol(s.backgroundColor);
|
|
185
|
+
if (c && c.a > 0) { stack.push(c); if (c.a >= 1) break; }
|
|
186
|
+
if (n === document.documentElement) break;
|
|
187
|
+
n = n.parentElement || (n.getRootNode && n.getRootNode().host) || null;
|
|
188
|
+
}
|
|
189
|
+
let color = { r: 255, g: 255, b: 255, a: 1 };
|
|
190
|
+
for (const c of stack.reverse()) color = over(c, color);
|
|
191
|
+
return color;
|
|
192
|
+
};
|
|
193
|
+
const lum = c => { const f = v => { v /= 255;
|
|
194
|
+
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
|
|
195
|
+
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b); };
|
|
196
|
+
const ratioOf = (a, b) => { const l1 = Math.max(lum(a), lum(b)), l2 = Math.min(lum(a), lum(b));
|
|
197
|
+
return (l1 + 0.05) / (l2 + 0.05); };
|
|
198
|
+
|
|
199
|
+
// ---- contraste de text_ en TODAS las raíces ----
|
|
200
|
+
const fails = new Map();
|
|
201
|
+
const scanTexts = root => {
|
|
202
|
+
const walker = document.createTreeWalker(root.body || root, NodeFilter.SHOW_TEXT);
|
|
203
|
+
let node;
|
|
204
|
+
while ((node = walker.nextNode())) {
|
|
205
|
+
const txt = (node.nodeValue || '').trim();
|
|
206
|
+
if (!txt) continue;
|
|
207
|
+
let el = node.parentElement;
|
|
208
|
+
if (!el) {
|
|
209
|
+
// text_ DIRECTO bajo un shadow root (sin elemento): manda el HOST
|
|
210
|
+
const _rn = node.getRootNode();
|
|
211
|
+
el = (_rn && _rn.host) || null;
|
|
212
|
+
}
|
|
213
|
+
if (!el || el.closest('script, style, noscript, svg title')) continue;
|
|
214
|
+
if (!vis(el)) continue;
|
|
215
|
+
// text_ de solo símbolos (±±±@@) o UN carácter ASCII (X de cerrar):
|
|
216
|
+
// contenido no verbal — sin requisito. CUALQUIER letra/dígito de
|
|
217
|
+
// cualquier alfabeto (CJK, cirílico, árabe…) ES text_ verbal
|
|
218
|
+
if (!/\p{L}|\p{N}/u.test(txt)) continue;
|
|
219
|
+
if (txt.length === 1 && /[a-zA-Z0-9]/.test(txt)) continue;
|
|
220
|
+
// componente inactivo (fieldset disabled, aria-disabled, control
|
|
221
|
+
// disabled): la excepción del propio 1.4.3 — sin requisito
|
|
222
|
+
if (el.closest('fieldset[disabled], [aria-disabled="true"], button[disabled], input[disabled], select[disabled], textarea[disabled]')) continue;
|
|
223
|
+
// label de control disabled, o label sin control: componente inactivo
|
|
224
|
+
// o no-componente — el contraste no aplica (afw4f7)
|
|
225
|
+
if (el.tagName === 'LABEL') {
|
|
226
|
+
const ctl = el.control || (el.getAttribute('for') ? el.getRootNode().getElementById(el.getAttribute('for')) : null);
|
|
227
|
+
if (!ctl || ctl.disabled) continue;
|
|
228
|
+
}
|
|
229
|
+
const s = getComputedStyle(el);
|
|
230
|
+
const fg = parseCol(s.color);
|
|
231
|
+
if (!fg) continue;
|
|
232
|
+
// text-shadow: los colores de la sombra pintan DETRÁS del text_ y
|
|
233
|
+
// participan como fondo peor-caso (8c33: #666 con sombra #aaa sobre
|
|
234
|
+
// blanco falla por 1.6:1 aunque el fondo dé 5.7) — se decide, no se
|
|
235
|
+
// deriva a revisión
|
|
236
|
+
const shCols = (s.textShadow && s.textShadow !== 'none')
|
|
237
|
+
? (s.textShadow.match(/rgba?\([^)]+\)/g) || []).map(parseCol).filter(Boolean)
|
|
238
|
+
: [];
|
|
239
|
+
const bg = bgOf(el);
|
|
240
|
+
if (bg.image) {
|
|
241
|
+
out.contrastReview++;
|
|
242
|
+
const fa = (fg.a === undefined) ? 1 : fg.a;
|
|
243
|
+
const pxx = parseFloat(s.fontSize);
|
|
244
|
+
const isLargePx = pxx >= 24 || (parseInt(s.fontWeight || '400', 10) >= 700 && pxx >= 18.66); // spec bold=700 (600 daba 3:1 a text_ normal)
|
|
245
|
+
// text_ con ALFA: el color real depende del fondo bajo cada píxel; se
|
|
246
|
+
// muestrea en los DOS extremos (compuesto sobre negro y sobre blanco)
|
|
247
|
+
// — el peor decide (bf47c65f: rgba(90,90,90,.8) sobre split negro)
|
|
248
|
+
if (out.contrastZones.length < 11 && fa < 1 && !el.hasAttribute('data-a11ytxt')) {
|
|
249
|
+
const rr = el.getBoundingClientRect();
|
|
250
|
+
if (rr.width > 2 && rr.height > 2 && rr.width <= 1400 && rr.height <= 400) {
|
|
251
|
+
const zi = out.contrastZones.length;
|
|
252
|
+
el.setAttribute('data-a11ytxt', zi);
|
|
253
|
+
for (const pol of [{r:0,g:0,b:0}, {r:255,g:255,b:255}]) {
|
|
254
|
+
const c2 = over({r: fg.r, g: fg.g, b: fg.b, a: fa}, pol);
|
|
255
|
+
out.contrastZones.push({
|
|
256
|
+
i: zi, example: path(el) + (pol.r ? ' (sobre claro)' : ' (sobre oscuro)'),
|
|
257
|
+
fg: 'rgb(' + Math.round(c2.r) + ',' + Math.round(c2.g) + ',' + Math.round(c2.b) + ')',
|
|
258
|
+
px: pxx, large: isLargePx, x: rr.x, y: rr.y, w: rr.width, h: rr.height });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (out.contrastZones.length < 12 && fa >= 1 && !el.hasAttribute('data-a11ytxt')) {
|
|
263
|
+
const rr = el.getBoundingClientRect();
|
|
264
|
+
if (rr.width > 2 && rr.height > 2 && rr.width <= 1400 && rr.height <= 400) {
|
|
265
|
+
el.setAttribute('data-a11ytxt', out.contrastZones.length);
|
|
266
|
+
out.contrastZones.push({
|
|
267
|
+
i: out.contrastZones.length, example: path(el),
|
|
268
|
+
fg: 'rgb(' + Math.round(fg.r) + ',' + Math.round(fg.g) + ',' + Math.round(fg.b) + ')',
|
|
269
|
+
px: pxx, large: isLargePx, x: rr.x, y: rr.y, w: rr.width, h: rr.height });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
const px = parseFloat(s.fontSize);
|
|
275
|
+
const bold = parseInt(s.fontWeight || '400', 10) >= 700;
|
|
276
|
+
const isLarge = px >= 24 || (bold && px >= 18.66);
|
|
277
|
+
const over_ = (f, b) => { const a = (f.a === undefined) ? 1 : f.a;
|
|
278
|
+
return { r: Math.round(f.r * a + b.r * (1 - a)),
|
|
279
|
+
g: Math.round(f.g * a + b.g * (1 - a)),
|
|
280
|
+
b: Math.round(f.b * a + b.b * (1 - a)), a: 1 }; };
|
|
281
|
+
// alfa efectivo del text_: su color Y la opacidad del elemento y sus
|
|
282
|
+
// ancestros (opacity no está en color — 7507c813: negro al 30%)
|
|
283
|
+
let alphaTot = (fg.a === undefined) ? 1 : fg.a;
|
|
284
|
+
for (let an = el; an; an = an.parentElement) {
|
|
285
|
+
alphaTot *= parseFloat(getComputedStyle(an).opacity || '1');
|
|
286
|
+
}
|
|
287
|
+
const fgE = { r: fg.r, g: fg.g, b: fg.b, a: alphaTot };
|
|
288
|
+
let r; // text_ compuesto sobre el fondo
|
|
289
|
+
if (shCols.length) {
|
|
290
|
+
// con text-shadow, la sombra rodea al glifo: es el FONDO efectivo
|
|
291
|
+
// (Passed 4: blanco detrás de negro sobre gris = pasa; 8c33: #aaa
|
|
292
|
+
// detrás de #666 = 1.6:1 falla aunque el fondo dé 5.7)
|
|
293
|
+
r = Math.min(...shCols.map(sc => ratioOf(over_(fgE, sc), sc)));
|
|
294
|
+
} else {
|
|
295
|
+
r = ratioOf(over_(fgE, bg), bg);
|
|
296
|
+
}
|
|
297
|
+
const threshold = isLarge ? 3.0 : 4.5;
|
|
298
|
+
if (r >= threshold) continue;
|
|
299
|
+
const fk = `rgb(${fg.r},${fg.g},${fg.b})`;
|
|
300
|
+
const bk = `rgb(${bg.r},${bg.g},${bg.b})`;
|
|
301
|
+
const key = fk + '|' + bk + '|' + (isLarge ? 'L' : 'N');
|
|
302
|
+
if (!fails.has(key)) fails.set(key, { fg: fk, bg: bk, large: isLarge, ratio: Math.round(r * 100) / 100,
|
|
303
|
+
n: 0, example: path(el) });
|
|
304
|
+
const f = fails.get(key);
|
|
305
|
+
f.n++;
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
for (const r of roots) scanTexts(r);
|
|
309
|
+
out.contrast = [...fails.values()].slice(0, 40);
|
|
310
|
+
|
|
311
|
+
// ---- 1.4.1 use of color: inline links distinguishable ONLY by color ----
|
|
312
|
+
for (const el of deepQ('a[href]')) {
|
|
313
|
+
if (out.colorOnly.length >= 12) break;
|
|
314
|
+
if (!getComputedStyle(el).display.includes('inline')) continue;
|
|
315
|
+
const cont = el.closest('p, li, dd, dt, td, figcaption, blockquote');
|
|
316
|
+
if (!cont || cont.textContent.trim().length < 40) continue; // needs surrounding prose
|
|
317
|
+
const s = getComputedStyle(el);
|
|
318
|
+
if (s.textDecorationLine.includes('underline') || parseInt(s.fontWeight || '400', 10) >= 700) continue; // bold spec=700
|
|
319
|
+
if (el.querySelector('img, svg')) continue; // icon = extra cue
|
|
320
|
+
const cl = parseCol(s.color), cp = parseCol(getComputedStyle(cont).color);
|
|
321
|
+
if (cl && cp && ratioOf(cl, cp) < 3)
|
|
322
|
+
out.colorOnly.push(path(el));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ---- 1.3.2 meaningful sequence: DOM order vs visual order, same parent ----
|
|
326
|
+
{
|
|
327
|
+
const byParent = new Map();
|
|
328
|
+
for (const el of deepQ('p, li, h1, h2, h3, h4, h5, h6')) {
|
|
329
|
+
if (byParent.size > 200) break;
|
|
330
|
+
if (!el.offsetParent) continue;
|
|
331
|
+
const r = el.getBoundingClientRect();
|
|
332
|
+
if (r.height < 4 || r.width < 4) continue;
|
|
333
|
+
const p = el.parentElement;
|
|
334
|
+
if (!p) continue;
|
|
335
|
+
if (!byParent.has(p)) byParent.set(p, []);
|
|
336
|
+
byParent.get(p).push({ top: r.top });
|
|
337
|
+
}
|
|
338
|
+
let inv = 0;
|
|
339
|
+
for (const listEls of byParent.values()) {
|
|
340
|
+
for (let i = 0; i < listEls.length - 1; i++)
|
|
341
|
+
if (listEls[i + 1].top + 4 < listEls[i].top) inv++; // next-in-DOM clearly above
|
|
342
|
+
}
|
|
343
|
+
out.orderInversions = inv;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ---- 2.2.2 computed looping animations (review-only count) ----
|
|
347
|
+
{
|
|
348
|
+
let n = 0;
|
|
349
|
+
for (const r of roots) {
|
|
350
|
+
for (const el of r.querySelectorAll('*')) {
|
|
351
|
+
if (n >= 30) break;
|
|
352
|
+
const cs = getComputedStyle(el);
|
|
353
|
+
if (cs.animationIterationCount === 'infinite' && cs.animationName !== 'none') {
|
|
354
|
+
const durs = (cs.animationDuration || '0s').split(',').map(x => {
|
|
355
|
+
const v = parseFloat(x) || 0; return x.includes('ms') ? v / 1000 : v; });
|
|
356
|
+
if (Math.max(...durs, 0) > 0.15) n++;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
out.loopingAnims = n;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ---- target size 2.5.8 (todas las raíces) ----
|
|
364
|
+
let interpRects = null;
|
|
365
|
+
for (const el of deepQ(INTER)) {
|
|
366
|
+
out.elements++;
|
|
367
|
+
if (el.type === 'hidden' || !vis(el)) continue;
|
|
368
|
+
const disp = getComputedStyle(el).display;
|
|
369
|
+
if (el.tagName === 'A' && disp.includes('inline') && el.closest('p, li, dd, dt, td, figcaption, blockquote')) continue;
|
|
370
|
+
const r = el.getBoundingClientRect();
|
|
371
|
+
if (r.width <= 2 || r.height <= 2) continue; // patrón visualmente hiddenEl (skip link)
|
|
372
|
+
if (el.getAttribute('tabindex') === '-1') continue;
|
|
373
|
+
if (r.width < 24 || r.height < 24) {
|
|
374
|
+
// excepción de espaciado (2.5.8): un objetivo menor de 24px PASA si el
|
|
375
|
+
// más cercano está a ≥24px. Vecinos precomputados (no 121 del DOM
|
|
376
|
+
// arbitrarios) y condena temprana: un solo vecino <24px basta.
|
|
377
|
+
if (!interpRects) {
|
|
378
|
+
interpRects = [];
|
|
379
|
+
for (const other of deepQ(INTER)) {
|
|
380
|
+
if (other.type === 'hidden' || !vis(other)) continue;
|
|
381
|
+
const rr = other.getBoundingClientRect();
|
|
382
|
+
if (rr.width <= 2 && rr.height <= 2) continue;
|
|
383
|
+
interpRects.push({ el: other, r: rr });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
let sep = Infinity;
|
|
387
|
+
for (const par of interpRects) {
|
|
388
|
+
if (par.el === el) continue;
|
|
389
|
+
const r2 = par.r;
|
|
390
|
+
const dx = Math.max(r.left - r2.right, r2.left - r.right, 0);
|
|
391
|
+
const dy = Math.max(r.top - r2.bottom, r2.top - r.bottom, 0);
|
|
392
|
+
const d = Math.hypot(dx, dy);
|
|
393
|
+
if (d < sep) sep = d;
|
|
394
|
+
if (sep < 24) break; // condenado: no hace falta seguir
|
|
395
|
+
}
|
|
396
|
+
if (sep < 24 && out.targets.length < 40) out.targets.push(
|
|
397
|
+
{ example: path(el), w: Math.round(r.width), h: Math.round(r.height),
|
|
398
|
+
inline: disp.includes('inline'), spacing: Math.round(sep) });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ---- nombres accesibles renderizados ----
|
|
403
|
+
const nameOf = el => {
|
|
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
|
+
};
|
|
423
|
+
for (const el of deepQ('a[href], button, summary, [role="button"], [role="link"]')) {
|
|
424
|
+
if (!vis(el) || el.closest('[aria-hidden="true"]')) continue;
|
|
425
|
+
if (!nameOf(el) && out.unnamed.length < 30) out.unnamed.push(path(el));
|
|
426
|
+
}
|
|
427
|
+
for (const el of deepQ('input, select, textarea')) {
|
|
428
|
+
if (el.type === 'hidden' || el.type === 'submit' || el.type === 'button' || el.type === 'reset') continue;
|
|
429
|
+
if (!vis(el)) continue;
|
|
430
|
+
if (!nameOf(el) && out.fields.length < 30) out.fields.push(path(el));
|
|
431
|
+
}
|
|
432
|
+
for (const el of deepQ('img')) {
|
|
433
|
+
if (!vis(el)) continue;
|
|
434
|
+
if (!el.hasAttribute('alt') && out.imgs.length < 30) out.imgs.push(el.getAttribute('src') || '');
|
|
435
|
+
}
|
|
436
|
+
for (const el of deepQ('iframe')) {
|
|
437
|
+
if (!((el.getAttribute('title') || '').trim() || (el.getAttribute('aria-label') || '').trim())
|
|
438
|
+
&& out.iframes.length < 20) out.iframes.push(el.getAttribute('src') || '');
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// ---- estructura ----
|
|
442
|
+
for (const h of deepQ('h1,h2,h3,h4,h5,h6')) {
|
|
443
|
+
out.headings.push({ lvl: +h.tagName[1], text: (h.innerText || '').trim().slice(0, 80) });
|
|
444
|
+
}
|
|
445
|
+
for (const el of deepQ('[tabindex]')) {
|
|
446
|
+
const t = parseInt(el.getAttribute('tabindex') || '0', 10);
|
|
447
|
+
if (t > 0 && out.tabindex.length < 20) out.tabindex.push(path(el));
|
|
448
|
+
}
|
|
449
|
+
for (const r of roots) {
|
|
450
|
+
for (const el of r.querySelectorAll('[aria-hidden="true"]')) {
|
|
451
|
+
if (el.matches(INTER)) {
|
|
452
|
+
if (el.getAttribute('tabindex') !== '-1') out.ariaHidden.push(path(el));
|
|
453
|
+
} else if ([...(el.querySelectorAll(INTER) || [])]
|
|
454
|
+
.some(d => d.getAttribute('tabindex') !== '-1')) {
|
|
455
|
+
out.ariaHidden.push(path(el));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
for (const el of deepQ('a[target="_blank"]')) {
|
|
460
|
+
const t = (el.innerText || '') + ' ' + (el.getAttribute('aria-label') || '') + ' ' + (el.getAttribute('title') || '');
|
|
461
|
+
if (!/(nueva|nuevo|ventana|pesta|tab\b|window|external|externo|exterior)/i.test(t)) out.blank++;
|
|
462
|
+
}
|
|
463
|
+
for (const el of deepQ('video')) {
|
|
464
|
+
out.videos++;
|
|
465
|
+
if (el.querySelector('track[kind="captions"], track[kind="subtitles"]')) out.videoSubs++;
|
|
466
|
+
}
|
|
467
|
+
for (const el of deepQ('table')) {
|
|
468
|
+
out.tables++;
|
|
469
|
+
if (el.querySelector('th')) out.tableTh++;
|
|
470
|
+
}
|
|
471
|
+
for (const r of roots) {
|
|
472
|
+
for (const el of r.querySelectorAll('[id]')) out.ids[el.id] = (out.ids[el.id] || 0) + 1;
|
|
473
|
+
}
|
|
474
|
+
out.lang = document.documentElement.getAttribute('lang');
|
|
475
|
+
out.title = document.title || '';
|
|
476
|
+
const vp = document.querySelector('meta[name="viewport"]');
|
|
477
|
+
out.viewport = vp ? vp.getAttribute('content') : null;
|
|
478
|
+
const rf = document.querySelector('meta[http-equiv="refresh" i]');
|
|
479
|
+
out.refresh = rf ? rf.getAttribute('content') : null;
|
|
480
|
+
out.main = !!document.querySelector('main, [role="main"]');
|
|
481
|
+
out.skip = !!document.querySelector('a[href^="#"]');
|
|
482
|
+
|
|
483
|
+
// ---- marcas para contrastar estados (:hover) desde Python ----
|
|
484
|
+
let mi = 0;
|
|
485
|
+
for (const el of deepQ(INTER)) {
|
|
486
|
+
if (mi >= 25) break;
|
|
487
|
+
if (el.type === 'hidden' || !vis(el)) continue;
|
|
488
|
+
try { el.setAttribute('data-a11yidx', String(mi)); } catch (e) { continue; }
|
|
489
|
+
mi++;
|
|
490
|
+
}
|
|
491
|
+
out.marks = mi;
|
|
492
|
+
|
|
493
|
+
// ---- foco: indicador visible (heurístico) + contraste en estado focus ----
|
|
494
|
+
const hiddenEl = el => { const r = el.getBoundingClientRect();
|
|
495
|
+
return (r.width <= 2 && r.height <= 2); };
|
|
496
|
+
const stops = deepQ(INTER)
|
|
497
|
+
.filter(el => vis(el) && !el.disabled && el.getAttribute('tabindex') !== '-1'
|
|
498
|
+
&& !hiddenEl(el)).slice(0, 40);
|
|
499
|
+
const activeEl = () => { let a = document.activeElement;
|
|
500
|
+
while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement;
|
|
501
|
+
return a; };
|
|
502
|
+
const prevFocus = document.activeElement;
|
|
503
|
+
for (const el of stops) {
|
|
504
|
+
try { el.focus(); } catch (e) { /* no enfocable */ }
|
|
505
|
+
if (activeEl() !== el) {
|
|
506
|
+
out.focusFail.push({ example: path(el), why: 'nofocus' });
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
const s = getComputedStyle(el);
|
|
510
|
+
const outline = s.outlineStyle !== 'none' && parseFloat(s.outlineWidth || '0') > 0;
|
|
511
|
+
const shadow = s.boxShadow && s.boxShadow !== 'none';
|
|
512
|
+
const edgePx = ['Top', 'Right', 'Bottom', 'Left'].some(
|
|
513
|
+
k => parseFloat(s['border' + k + 'Width'] || '0') >= 2
|
|
514
|
+
&& s['border' + k + 'Style'] !== 'none');
|
|
515
|
+
if (!outline && !shadow && !edgePx) out.focus.push(path(el));
|
|
516
|
+
const fgf = parseCol(s.color);
|
|
517
|
+
const bgf = bgOf(el);
|
|
518
|
+
if (fgf && !bgf.image) {
|
|
519
|
+
const fs = parseFloat(s.fontSize) || 16;
|
|
520
|
+
const isLarge = fs >= 24 || (fs >= 18.66 && (parseInt(s.fontWeight) || 400) >= 700);
|
|
521
|
+
const rf2 = ratioOf(over(fgf, bgf), bgf);
|
|
522
|
+
if (rf2 < (isLarge ? 3.0 : 4.5) && out.focusContrast.length < 20)
|
|
523
|
+
out.focusContrast.push({ example: path(el), ratio: Math.round(rf2 * 100) / 100 });
|
|
524
|
+
}
|
|
525
|
+
// (2.4.11 por parada se cubre abajo con la causa raíz)
|
|
526
|
+
}
|
|
527
|
+
// 2.4.11 causa raíz: header fijo arriba sin scroll-padding-top suficiente →
|
|
528
|
+
// saltos de ancla y de foco aterrizan tapados. Determinista y sin falsos
|
|
529
|
+
// negativos de recorridos.
|
|
530
|
+
if (fixed_els.length && out.focusObscured.length === 0) {
|
|
531
|
+
const sp = parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) || 0;
|
|
532
|
+
const top_fixed = fixed_els.map(f => f.getBoundingClientRect()).filter(q => q.top <= 20);
|
|
533
|
+
const hmax = top_fixed.length ? Math.max(...top_fixed.map(q => q.height)) : 0;
|
|
534
|
+
if (hmax > sp + 4) {
|
|
535
|
+
out.focusObscured.push('header fijo de ' + Math.round(hmax) + 'px con scroll-padding-top de '
|
|
536
|
+
+ Math.round(sp) + 'px');
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
if (prevFocus && prevFocus.blur) { try { prevFocus.focus(); } catch (e) {} }
|
|
540
|
+
|
|
541
|
+
return out;
|
|
542
|
+
}'''
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _add(findings, lang, severity, code, key, examples=None, **fmt):
|
|
546
|
+
h = {'severity': severity, 'criterion': CRIT.get(lang, CRIT['es']).get(code, code),
|
|
547
|
+
'signal': key,
|
|
548
|
+
'issue': _t(lang, key, n=fmt.get('n')).format(**fmt),
|
|
549
|
+
'remediation': _t(lang, key + '_rem').format(**fmt)}
|
|
550
|
+
if examples:
|
|
551
|
+
h['examples'] = examples[:MAX_EXAMPLES]
|
|
552
|
+
findings.append(h)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
|
|
556
|
+
"""Agrega los datos JS del DOM en un informe con la misma forma que audit_html."""
|
|
557
|
+
findings = []
|
|
558
|
+
|
|
559
|
+
# 1. Contraste real
|
|
560
|
+
failures = data.get('contrast') or []
|
|
561
|
+
if failures:
|
|
562
|
+
det = '; '.join(f"{f['fg']} vs {f['bg']} = {f['ratio']}:1"
|
|
563
|
+
+ (' (grande)' if f['large'] else '') + f" ×{f['n']}"
|
|
564
|
+
for f in failures[:4])
|
|
565
|
+
_over, _eg = ('sobre', 'p. ej.') if lang == 'es' else ('over', 'e.g.')
|
|
566
|
+
examples = [f"{f['fg']} {_over} {f['bg']} → {f['ratio']}:1 ({_eg} {f['example']})" for f in failures]
|
|
567
|
+
_add(findings, lang, 'high', '1.4.3', 'contrast_fail',
|
|
568
|
+
examples=examples, n=len(failures), det=det)
|
|
569
|
+
measured = data.get('contrastMeasured') or []
|
|
570
|
+
if measured:
|
|
571
|
+
offenders = [m for m in measured
|
|
572
|
+
if m['measured']['worst_ratio'] < (3.0 if m.get('large') else 4.5)]
|
|
573
|
+
if offenders:
|
|
574
|
+
det = '; '.join(f"{m['example']} → worst {m['measured']['worst_ratio']}:1, "
|
|
575
|
+
f"{m['measured']['area_passes_aa_normal_text_4_5']}% passes AA"
|
|
576
|
+
for m in offenders[:4])
|
|
577
|
+
_add(findings, lang, 'high', '1.4.3', 'contrast_image_fail',
|
|
578
|
+
examples=[f"{m['example']} (worst {m['measured']['worst_ratio']}:1)"
|
|
579
|
+
for m in offenders],
|
|
580
|
+
n=len(offenders), det=det)
|
|
581
|
+
# las zonas medidas salen del contador de "revisar" (ya están juzgadas)
|
|
582
|
+
remaining = max(0, data.get('contrastReview', 0) - len(measured))
|
|
583
|
+
if remaining:
|
|
584
|
+
_add(findings, lang, 'low', '1.4.3', 'contrast_review', n=remaining)
|
|
585
|
+
|
|
586
|
+
# 2. Target size 2.5.8 (enlaces inline → baja: la excepción de espaciado
|
|
587
|
+
# probablemente aplica y no es medible aquí; bloques → media)
|
|
588
|
+
targets = data.get('targets') or []
|
|
589
|
+
if targets:
|
|
590
|
+
all_inline = all(t.get('inline') for t in targets)
|
|
591
|
+
det = ', '.join(f"{t['example']} ({t['w']}×{t['h']})" for t in targets[:4])
|
|
592
|
+
_add(findings, lang, 'low' if all_inline else 'medium', '2.5.8',
|
|
593
|
+
'target_small',
|
|
594
|
+
examples=[f"{t['example']} ({t['w']}×{t['h']}px)" for t in targets],
|
|
595
|
+
n=len(targets), det=det)
|
|
596
|
+
|
|
597
|
+
# 2.bis Estados focus/hover
|
|
598
|
+
states = list(data.get('focusContrast') or []) + list(data.get('hover') or [])
|
|
599
|
+
if states:
|
|
600
|
+
det = ', '.join(f"{e['example']} = {e['ratio']}:1" for e in states[:4])
|
|
601
|
+
_add(findings, lang, 'medium', '1.4.3', 'state_contrast',
|
|
602
|
+
examples=[f"{e['example']} = {e['ratio']}:1" for e in states],
|
|
603
|
+
n=len(states), det=det)
|
|
604
|
+
|
|
605
|
+
# 2.ter 2.4.11 foco ocultado por fixed_els
|
|
606
|
+
if data.get('focusObscured'):
|
|
607
|
+
_add(findings, lang, 'medium', '2.4.11', 'focus_obscured',
|
|
608
|
+
examples=data['focusObscured'], n=len(data['focusObscured']),
|
|
609
|
+
det=', '.join(data['focusObscured'][:3]))
|
|
610
|
+
|
|
611
|
+
# v3.12 rendered-only partial signals (review-severity honesty)
|
|
612
|
+
if data.get('colorOnly'):
|
|
613
|
+
_add(findings, lang, 'low', '1.4.1', 'color_only_link',
|
|
614
|
+
examples=data['colorOnly'], n=len(data['colorOnly']))
|
|
615
|
+
if data.get('orderInversions'):
|
|
616
|
+
_add(findings, lang, 'low', '1.3.2', 'dom_visual_order',
|
|
617
|
+
n=data['orderInversions'])
|
|
618
|
+
if data.get('loopingAnims'):
|
|
619
|
+
_add(findings, lang, 'low', '2.2.2', 'motion_moving',
|
|
620
|
+
examples=[], n=data['loopingAnims'],
|
|
621
|
+
example=f"{data['loopingAnims']} looping CSS animations")
|
|
622
|
+
if data.get('spacingClipped'):
|
|
623
|
+
_add(findings, lang, 'medium', '1.4.12', 'text_spacing_clip',
|
|
624
|
+
examples=data['spacingClipped'], n=len(data['spacingClipped']))
|
|
625
|
+
|
|
626
|
+
# 3. Foco
|
|
627
|
+
if data.get('focus'):
|
|
628
|
+
_add(findings, lang, 'medium', '2.4.7', 'focus_invisible',
|
|
629
|
+
examples=data['focus'], n=len(data['focus']),
|
|
630
|
+
det=', '.join(data['focus'][:4]))
|
|
631
|
+
if data.get('focusFail'):
|
|
632
|
+
_add(findings, lang, 'low', '2.4.7', 'focus_not_focusable',
|
|
633
|
+
examples=[f['example'] for f in data['focusFail']],
|
|
634
|
+
n=len(data['focusFail']), det=', '.join(f['example'] for f in data['focusFail'][:4]))
|
|
635
|
+
|
|
636
|
+
# 4. Resto de señales (renderizadas)
|
|
637
|
+
if data.get('unnamed'):
|
|
638
|
+
_add(findings, lang, 'high', '4.1.2', 'ctrl_name',
|
|
639
|
+
examples=data['unnamed'], n=len(data['unnamed']), tag='control')
|
|
640
|
+
if data.get('fields'):
|
|
641
|
+
_add(findings, lang, 'high', '3.3.2', 'field_label',
|
|
642
|
+
examples=data['fields'], n=len(data['fields']))
|
|
643
|
+
if data.get('imgs'):
|
|
644
|
+
_add(findings, lang, 'high', '1.1.1', 'img_no_alt',
|
|
645
|
+
examples=data['imgs'], n=len(data['imgs']))
|
|
646
|
+
if data.get('ariaHidden'):
|
|
647
|
+
_add(findings, lang, 'high', '4.1.2', 'aria_hidden_focusable',
|
|
648
|
+
n=len(data['ariaHidden']), tag='control')
|
|
649
|
+
if not (data.get('lang') or '').strip():
|
|
650
|
+
_add(findings, lang, 'medium', '3.1.1', 'lang_missing')
|
|
651
|
+
if not (data.get('title') or '').strip():
|
|
652
|
+
_add(findings, lang, 'medium', '2.4.2', 'title_missing')
|
|
653
|
+
if data.get('iframes'):
|
|
654
|
+
_add(findings, lang, 'medium', '4.1.2', 'iframe_title',
|
|
655
|
+
examples=data['iframes'], n=len(data['iframes']))
|
|
656
|
+
videos, subframes = data.get('videos', 0), data.get('videoSubs', 0)
|
|
657
|
+
if videos and subframes < videos:
|
|
658
|
+
_add(findings, lang, 'medium', '1.2.2', 'video_captions', n=videos - subframes)
|
|
659
|
+
vp = data.get('viewport') or ''
|
|
660
|
+
if re.search(r'user-scalable\s*=\s*(no|0)', vp, re.I):
|
|
661
|
+
_add(findings, lang, 'high', '1.4.4', 'zoom_no')
|
|
662
|
+
elif (m := re.search(r'maximum-scale\s*=\s*([\d.]+)', vp, re.I)) and float(m.group(1)) < 2:
|
|
663
|
+
_add(findings, lang, 'medium', '1.4.4', 'zoom_max', v=m.group(1))
|
|
664
|
+
if data.get('refresh'):
|
|
665
|
+
m = re.match(r'\s*(\d+)', str(data['refresh']))
|
|
666
|
+
segs = int(m.group(1)) if m else 0
|
|
667
|
+
_add(findings, lang, 'medium' if segs > 0 else 'low', '2.2.1', 'meta_refresh', v=segs)
|
|
668
|
+
if data.get('tabindex'):
|
|
669
|
+
_add(findings, lang, 'medium', '2.4.3', 'tabindex_pos',
|
|
670
|
+
examples=data['tabindex'], n=len(data['tabindex']))
|
|
671
|
+
if not (data.get('main') or data.get('skip')):
|
|
672
|
+
_add(findings, lang, 'medium', '2.4.1', 'no_bypass')
|
|
673
|
+
|
|
674
|
+
levels = [h['lvl'] for h in (data.get('headings') or []) if h['text']]
|
|
675
|
+
h1s = sum(1 for h in data.get('headings') or [] if h['lvl'] == 1 and h['text'])
|
|
676
|
+
empties = sum(1 for h in data.get('headings') or [] if not h['text'])
|
|
677
|
+
if levels:
|
|
678
|
+
if h1s == 0:
|
|
679
|
+
_add(findings, lang, 'medium', '1.3.1', 'no_h1')
|
|
680
|
+
elif h1s > 1:
|
|
681
|
+
_add(findings, lang, 'low', '1.3.1', 'multi_h1', n=h1s)
|
|
682
|
+
prev, jumps = 0, []
|
|
683
|
+
for n in levels:
|
|
684
|
+
if prev and n > prev + 1:
|
|
685
|
+
jumps.append(f'h{prev}→h{n}')
|
|
686
|
+
prev = n
|
|
687
|
+
if jumps:
|
|
688
|
+
_add(findings, lang, 'low', '1.3.1', 'heading_skips',
|
|
689
|
+
skips=', '.join(jumps[:5]))
|
|
690
|
+
else:
|
|
691
|
+
_add(findings, lang, 'medium', '1.3.1', 'no_headings')
|
|
692
|
+
if empties:
|
|
693
|
+
_add(findings, lang, 'low', '1.3.1', 'empty_heading', n=empties)
|
|
694
|
+
tables, con_th = data.get('tables', 0), data.get('tableTh', 0)
|
|
695
|
+
if tables and con_th < tables:
|
|
696
|
+
_add(findings, lang, 'medium', '1.3.1', 'table_no_th', n=tables - con_th)
|
|
697
|
+
if data.get('blank'):
|
|
698
|
+
_add(findings, lang, 'low', '3.2.5', 'blank_no_warning', n=data['blank'])
|
|
699
|
+
dups = sum(1 for k in (data.get('ids') or {}).values() if k > 1)
|
|
700
|
+
if dups:
|
|
701
|
+
_add(findings, lang, 'low', '4.1.2', 'dup_ids', n=dups)
|
|
702
|
+
|
|
703
|
+
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
704
|
+
findings.sort(key=lambda h: order[h['severity']])
|
|
705
|
+
summary = {s: sum(1 for h in findings if h['severity'] == s)
|
|
706
|
+
for s in ('high', 'medium', 'low')}
|
|
707
|
+
return {
|
|
708
|
+
'url': url,
|
|
709
|
+
'mode': 'rendered',
|
|
710
|
+
'color_scheme': color_scheme,
|
|
711
|
+
'nested_iframes': data.get('nested_iframes', 0),
|
|
712
|
+
'shadow_roots': data.get('shadow_roots', 0),
|
|
713
|
+
'score': compute_score(findings),
|
|
714
|
+
'score_note': _t(lang, 'score_note'),
|
|
715
|
+
'interactive_elements': data.get('elements', 0),
|
|
716
|
+
'summary': summary,
|
|
717
|
+
'findings': findings,
|
|
718
|
+
'limits': _t(lang, 'limits'),
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
_JS_FORM_FILL = r'''() => {
|
|
723
|
+
// Fill every validatable field with INVALID data, then submit. Returns what we touched.
|
|
724
|
+
const FIELDS_JS = 'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea';
|
|
725
|
+
const invalidItems = {email: 'not-an-email', url: 'not-a-url', number: 'abc', tel: 'no-phone'};
|
|
726
|
+
const touched_els = [];
|
|
727
|
+
for (const f of document.querySelectorAll('form')) {
|
|
728
|
+
if (f.querySelector('[novalidate]') || f.hasAttribute('novalidate')) { /* still try: JS may validate */ }
|
|
729
|
+
for (const el of f.querySelectorAll(FIELDS_JS)) {
|
|
730
|
+
if (el.disabled || el.readOnly) continue;
|
|
731
|
+
const kindV = (el.type || el.tagName.toLowerCase()).toLowerCase();
|
|
732
|
+
const needs = el.required || el.getAttribute('aria-required') === 'true'
|
|
733
|
+
|| el.hasAttribute('pattern') || el.hasAttribute('minlength') || el.hasAttribute('min');
|
|
734
|
+
let val = '';
|
|
735
|
+
if (invalidItems[kindV]) val = invalidItems[kindV];
|
|
736
|
+
else if (kindV === 'checkbox' || kindV === 'radio') { continue; }
|
|
737
|
+
else if (!needs) continue;
|
|
738
|
+
else val = kindV === 'number' ? 'abc' : '';
|
|
739
|
+
el.value = val;
|
|
740
|
+
el.dispatchEvent(new Event('input', {bubbles: true}));
|
|
741
|
+
el.dispatchEvent(new Event('change', {bubbles: true}));
|
|
742
|
+
touched_els.push({form: f.id || f.action || f.getAttribute('class') || 'form',
|
|
743
|
+
campo: (el.name || el.id || kindV).toString().slice(0, 40)});
|
|
744
|
+
}
|
|
745
|
+
const btn = f.querySelector('button[type=submit], input[type=submit], button:not([type])');
|
|
746
|
+
if (btn) btn.click(); else if (f.requestSubmit) f.requestSubmit();
|
|
747
|
+
}
|
|
748
|
+
return touched_els;
|
|
749
|
+
}'''
|
|
750
|
+
|
|
751
|
+
_JS_FORM_PRE = r'''() => {
|
|
752
|
+
// PRE-submit: la ayuda ordinaria que ya existía (describedby, contexto).
|
|
753
|
+
// Sin esto, "Tu email" contaba como identificación de error y "Use…"
|
|
754
|
+
// como sugerencia — la crítica externa lo destapó: ayuda ≠ error.
|
|
755
|
+
const FIELDS_JS = 'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea';
|
|
756
|
+
const pre = {};
|
|
757
|
+
for (const el of document.querySelectorAll(FIELDS_JS)) {
|
|
758
|
+
if (el.disabled) continue;
|
|
759
|
+
const key = (el.name || el.id || el.type) + '@' + (el.form ? (el.form.id || el.form.action || '') : '');
|
|
760
|
+
let dbTxt = '';
|
|
761
|
+
const db = el.getAttribute('aria-describedby');
|
|
762
|
+
if (db) for (const id of db.split(/\s+/)) {
|
|
763
|
+
const r = document.getElementById(id);
|
|
764
|
+
if (r && (r.innerText || '').trim()) dbTxt += r.innerText.trim() + '\n';
|
|
765
|
+
}
|
|
766
|
+
const nearby = el.closest('div, p, li, td, fieldset');
|
|
767
|
+
pre[key] = { db: dbTxt, ctx: nearby ? (nearby.innerText || '').trim().slice(0, 400) : '' };
|
|
768
|
+
}
|
|
769
|
+
return pre;
|
|
770
|
+
}'''
|
|
771
|
+
|
|
772
|
+
_JS_FORM_STATE = r'''(pre) => {
|
|
773
|
+
// After submit: how were errors identified and announced?
|
|
774
|
+
// Identificación = lo NUEVO tras el envío (aria-invalid, text_ cambiado en
|
|
775
|
+
// un nodo referido, semántica de alerta) — la ayuda previa NO cuenta.
|
|
776
|
+
const RX_ERR = /(error|invalid|required|obligatorio|requerido|inv[áa]lido|incorrecto|falta|requerid)/i;
|
|
777
|
+
const RX_SUG = /(format|example|ejemplo|usa |use |dd\/mm|mm\/dd|pattern|como |like |must be|debe)/i;
|
|
778
|
+
pre = pre || {};
|
|
779
|
+
const out = { forms: [], alerts: 0 };
|
|
780
|
+
for (const a of document.querySelectorAll('[role=alert], [aria-live]')) {
|
|
781
|
+
if ((a.innerText || '').trim() && RX_ERR.test(a.innerText)) out.alerts++;
|
|
782
|
+
}
|
|
783
|
+
const FIELDS_JS = 'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea';
|
|
784
|
+
for (const f of document.querySelectorAll('form')) {
|
|
785
|
+
const info = { form: f.id || f.action || 'form', fields: 0, identified: 0,
|
|
786
|
+
suggested: 0, native: 0 };
|
|
787
|
+
for (const el of f.querySelectorAll(FIELDS_JS)) {
|
|
788
|
+
if (el.disabled) continue;
|
|
789
|
+
info.campos++;
|
|
790
|
+
const key = (el.name || el.id || el.type) + '@' + (f.id || f.action || '');
|
|
791
|
+
const shot_before = pre[key] || {};
|
|
792
|
+
let identified = false, sugerido = false;
|
|
793
|
+
if (el.getAttribute('aria-invalid') === 'true') identified = true;
|
|
794
|
+
const db = el.getAttribute('aria-describedby');
|
|
795
|
+
if (db) for (const id of db.split(/\s+/)) {
|
|
796
|
+
const r = document.getElementById(id);
|
|
797
|
+
if (!r) continue;
|
|
798
|
+
const text_ = (r.innerText || '').trim();
|
|
799
|
+
if (!text_) continue;
|
|
800
|
+
const newOrChanged = text_ !== (shot_before.db || '').split('\n').find(t => t === text_)
|
|
801
|
+
&& !(shot_before.db || '').includes(text_);
|
|
802
|
+
const semanticError = r.matches('[role=alert],[aria-live],.error,.invalid')
|
|
803
|
+
|| r.hasAttribute('aria-errormessage');
|
|
804
|
+
if (newOrChanged || semanticError) {
|
|
805
|
+
identified = true;
|
|
806
|
+
if (RX_SUG.test(text_)) sugerido = true;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
const nearby = el.closest('div, p, li, td, fieldset');
|
|
810
|
+
const ctxNow = nearby ? (nearby.innerText || '').trim().slice(0, 400) : '';
|
|
811
|
+
if (nearby && RX_ERR.test(ctxNow) && !RX_ERR.test(shot_before.ctx || '')) {
|
|
812
|
+
identified = true;
|
|
813
|
+
const newPart = ctxNow.replace((shot_before.ctx || ''), '');
|
|
814
|
+
if (RX_SUG.test(newPart)) sugerido = true;
|
|
815
|
+
}
|
|
816
|
+
// native validation only identifies errors when the form lets it fire
|
|
817
|
+
// (a novalidate form never shows the browser message — the API lying ≠ UX)
|
|
818
|
+
if (!f.noValidate && el.willValidate !== undefined && !el.checkValidity() && el.validationMessage) {
|
|
819
|
+
identified = true; info.native++;
|
|
820
|
+
}
|
|
821
|
+
if (identified) info.identified++;
|
|
822
|
+
if (sugerido) info.suggested++;
|
|
823
|
+
}
|
|
824
|
+
out.forms.push(info);
|
|
825
|
+
}
|
|
826
|
+
return out;
|
|
827
|
+
}'''
|
|
828
|
+
|
|
829
|
+
def audit_forms(url, timeout=45, lang='en', auth_state=None):
|
|
830
|
+
"""3.3.1 Error Identification / 3.3.3 Error Suggestion — the guided flow:
|
|
831
|
+
fill every validatable field with INVALID data, really submit, then judge
|
|
832
|
+
how errors are identified and announced in the post-submit DOM."""
|
|
833
|
+
from playwright.sync_api import sync_playwright
|
|
834
|
+
with sync_playwright() as p:
|
|
835
|
+
nav = p.chromium.launch()
|
|
836
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
837
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
838
|
+
try:
|
|
839
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
840
|
+
page.wait_for_timeout(400)
|
|
841
|
+
except Exception as e: # noqa: BLE001
|
|
842
|
+
nav.close()
|
|
843
|
+
return {'error': _t(lang, 'fetch_error').format(e=e)}
|
|
844
|
+
url_before = page.url
|
|
845
|
+
pre = page.evaluate(_JS_FORM_PRE)
|
|
846
|
+
touched = page.evaluate(_JS_FORM_FILL)
|
|
847
|
+
page.wait_for_timeout(900)
|
|
848
|
+
navigated = page.url.split('#')[0] != url_before.split('#')[0]
|
|
849
|
+
state = None if navigated else page.evaluate(_JS_FORM_STATE, pre)
|
|
850
|
+
nav.close()
|
|
851
|
+
|
|
852
|
+
findings = []
|
|
853
|
+
|
|
854
|
+
def add(sev, code, key, **fmt):
|
|
855
|
+
findings.append({'severity': sev, 'criterion': CRIT.get(lang, CRIT['es']).get(code, code),
|
|
856
|
+
'signal': key, 'issue': _t(lang, key, n=fmt.get('n')).format(**fmt),
|
|
857
|
+
'remediation': _t(lang, key + '_rem').format(**fmt)})
|
|
858
|
+
|
|
859
|
+
if navigated:
|
|
860
|
+
add('low', '3.3.1', 'form_navigated', example=page.url if False else 'submit')
|
|
861
|
+
elif touched and state is not None:
|
|
862
|
+
unidentified = [f['form'] for f in state['forms']
|
|
863
|
+
if f['fields'] and f['identified'] == 0 and f['native'] == 0
|
|
864
|
+
and state['alerts'] == 0]
|
|
865
|
+
if unidentified:
|
|
866
|
+
add('high', '3.3.1', 'form_error_missing', n=len(unidentified))
|
|
867
|
+
error_fields = sum(f['identified'] for f in state['forms'])
|
|
868
|
+
suggested_fields = sum(f['suggested'] for f in state['forms'])
|
|
869
|
+
if error_fields > 0 and suggested_fields == 0:
|
|
870
|
+
add('low', '3.3.3', 'form_error_no_suggestion', n=error_fields)
|
|
871
|
+
|
|
872
|
+
from .a11yaudit import compute_score
|
|
873
|
+
return {
|
|
874
|
+
'url': url, 'mode': 'forms',
|
|
875
|
+
'invalid_fields': len(touched),
|
|
876
|
+
'detail': touched[:10],
|
|
877
|
+
'score': compute_score(findings),
|
|
878
|
+
'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
|
|
879
|
+
for s_ in ('high', 'medium', 'low')},
|
|
880
|
+
'findings': findings,
|
|
881
|
+
'limits': _t(lang, 'limits'),
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
886
|
+
"""Screen reader transcript: what a blind user HEARS on this page.
|
|
887
|
+
|
|
888
|
+
Walks the accessibility tree linearly (the order a screen reader reads)
|
|
889
|
+
and outputs the announcement text with roles, names and states — the
|
|
890
|
+
linearized reading experience. This is what `a11y_snapshot` captures as
|
|
891
|
+
structure; this function returns it as prose an agent can READ and
|
|
892
|
+
understand from a blind user's perspective.
|
|
893
|
+
"""
|
|
894
|
+
from playwright.sync_api import sync_playwright
|
|
895
|
+
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
|
+
try:
|
|
908
|
+
tree = page.locator('body').aria_snapshot()
|
|
909
|
+
except Exception:
|
|
910
|
+
tree = None
|
|
911
|
+
try:
|
|
912
|
+
ctx.close()
|
|
913
|
+
except Exception:
|
|
914
|
+
pass
|
|
915
|
+
|
|
916
|
+
if not tree:
|
|
917
|
+
return {'url': url, 'mode': 'sr-transcript',
|
|
918
|
+
'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
|
|
919
|
+
|
|
920
|
+
# parse the YAML-like snapshot into linearized announcements
|
|
921
|
+
import re
|
|
922
|
+
announcements = []
|
|
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)
|
|
931
|
+
|
|
932
|
+
return {
|
|
933
|
+
'url': url,
|
|
934
|
+
'mode': 'sr-transcript',
|
|
935
|
+
'announcements': announcements[:200], # cap
|
|
936
|
+
'total': len(announcements),
|
|
937
|
+
'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
|
|
938
|
+
'note': ('Linearized announcement order — what a screen reader user hears. '
|
|
939
|
+
'Roles and names as computed by the browser. Use this to understand '
|
|
940
|
+
'the page from a blind user\'s perspective.'),
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
_JS_HOVER_TEST = r'''() => {
|
|
945
|
+
// find elements that show tooltips/overlays on hover
|
|
946
|
+
const candidates = [];
|
|
947
|
+
for (const el of document.querySelectorAll('[title], [data-tooltip], [aria-describedby]')) {
|
|
948
|
+
if (candidates.length >= 10) break;
|
|
949
|
+
const r = el.getBoundingClientRect();
|
|
950
|
+
if (r.width > 10 && r.height > 10 && r.top >= 0 && r.top < innerHeight) {
|
|
951
|
+
candidates.push({
|
|
952
|
+
tag: el.tagName.toLowerCase(),
|
|
953
|
+
id: el.id || '',
|
|
954
|
+
desc: el.getAttribute('aria-describedby') || el.getAttribute('title') || '',
|
|
955
|
+
rect: {x: r.x, y: r.y, w: r.width, h: r.height}
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
return candidates;
|
|
960
|
+
}'''
|
|
961
|
+
|
|
962
|
+
def audit_hover(url, timeout=45, lang='en', auth_state=None):
|
|
963
|
+
"""1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?"""
|
|
964
|
+
from playwright.sync_api import sync_playwright
|
|
965
|
+
with sync_playwright() as p:
|
|
966
|
+
nav = p.chromium.launch()
|
|
967
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
968
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
969
|
+
try:
|
|
970
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
971
|
+
page.wait_for_timeout(400)
|
|
972
|
+
except Exception as e:
|
|
973
|
+
nav.close()
|
|
974
|
+
return {'error': str(e)[:100]}
|
|
975
|
+
|
|
976
|
+
candidates = page.evaluate(_JS_HOVER_TEST)
|
|
977
|
+
no_dismissibles = []
|
|
978
|
+
for c in candidates[:8]:
|
|
979
|
+
try:
|
|
980
|
+
# hover sobre el elemento
|
|
981
|
+
sel = f'{c["tag"]}#{c["id"]}' if c['id'] else c['tag']
|
|
982
|
+
page.hover(sel, timeout=2000)
|
|
983
|
+
page.wait_for_timeout(400)
|
|
984
|
+
# identidad de los tooltips visibles ANTES (por elemento, no
|
|
985
|
+
# por recuento global: other tooltip podía aparecer a la vez y
|
|
986
|
+
# el contador antiguo enmascaraba un cierre correcto)
|
|
987
|
+
before = page.evaluate(
|
|
988
|
+
"() => [...document.querySelectorAll("
|
|
989
|
+
"'[role=tooltip], [class*=tooltip], [class*=popover]')]"
|
|
990
|
+
".filter(el => {"
|
|
991
|
+
" if (el.checkVisibility) "
|
|
992
|
+
" return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
|
|
993
|
+
" const s = getComputedStyle(el);"
|
|
994
|
+
" const box = el.getBoundingClientRect();"
|
|
995
|
+
" return el.offsetParent !== null && s.visibility !== 'hidden'"
|
|
996
|
+
" && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
|
|
997
|
+
"})"
|
|
998
|
+
".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
|
|
999
|
+
if not before:
|
|
1000
|
+
continue # nada visible → no aplica
|
|
1001
|
+
# Escape
|
|
1002
|
+
page.keyboard.press('Escape')
|
|
1003
|
+
page.wait_for_timeout(300)
|
|
1004
|
+
after = page.evaluate(
|
|
1005
|
+
"() => [...document.querySelectorAll("
|
|
1006
|
+
"'[role=tooltip], [class*=tooltip], [class*=popover]')]"
|
|
1007
|
+
".filter(el => {"
|
|
1008
|
+
" if (el.checkVisibility) "
|
|
1009
|
+
" return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
|
|
1010
|
+
" const s = getComputedStyle(el);"
|
|
1011
|
+
" const box = el.getBoundingClientRect();"
|
|
1012
|
+
" return el.offsetParent !== null && s.visibility !== 'hidden'"
|
|
1013
|
+
" && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
|
|
1014
|
+
"})"
|
|
1015
|
+
".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
|
|
1016
|
+
if set(before) <= set(after):
|
|
1017
|
+
# los mismos (o más) siguen visibles: no se cerró con Escape
|
|
1018
|
+
no_dismissibles.append(f'{c["tag"]}#{c["id"] or "no-id"}')
|
|
1019
|
+
except Exception:
|
|
1020
|
+
continue
|
|
1021
|
+
nav.close()
|
|
1022
|
+
|
|
1023
|
+
findings = []
|
|
1024
|
+
if no_dismissibles:
|
|
1025
|
+
from .a11yaudit import compute_score
|
|
1026
|
+
findings.append({
|
|
1027
|
+
'severity': 'low', 'criterion': CRIT.get(lang, CRIT['es']).get('1.4.13', '1.4.13'),
|
|
1028
|
+
'signal': 'hover_not_dismissible',
|
|
1029
|
+
'issue': _t(lang, 'hover_not_dismissible').format(n=len(no_dismissibles)),
|
|
1030
|
+
'remediation': _t(lang, 'hover_not_dismissible_rem'),
|
|
1031
|
+
'examples': no_dismissibles[:4]})
|
|
1032
|
+
return {'url': url, 'mode': 'hover', 'score': compute_score(findings),
|
|
1033
|
+
'summary': {'high': 0, 'medium': 0, 'low': len(findings)},
|
|
1034
|
+
'findings': findings}
|
|
1035
|
+
return {'url': url, 'mode': 'hover', 'score': 100,
|
|
1036
|
+
'summary': {'high': 0, 'medium': 0, 'low': 0}, 'findings': []}
|
|
1037
|
+
|
|
1038
|
+
|
|
1039
|
+
_JS_SPACING = r'''() => {
|
|
1040
|
+
// WCAG 1.4.12 Text Spacing: the documented override set, applied globally,
|
|
1041
|
+
// then measure which texts get clipped by height-constrained containers.
|
|
1042
|
+
const css = document.createElement('style');
|
|
1043
|
+
css.id = 'a11y-spacing-1412';
|
|
1044
|
+
css.textContent = '*{line-height:1.5!important;letter-spacing:0.12em!important;'
|
|
1045
|
+
+ 'word-spacing:0.16em!important} p{margin-bottom:2em!important}';
|
|
1046
|
+
document.head.appendChild(css);
|
|
1047
|
+
const clip = [];
|
|
1048
|
+
for (const el of document.querySelectorAll('p, li, h1, h2, h3, h4, h5, h6, a, span, label')) {
|
|
1049
|
+
if (clip.length >= 15) break;
|
|
1050
|
+
if (!el.offsetParent) continue;
|
|
1051
|
+
const s = getComputedStyle(el);
|
|
1052
|
+
const clipped = (s.overflow === 'hidden' || s.overflowY === 'hidden')
|
|
1053
|
+
&& el.scrollHeight > el.clientHeight + 3;
|
|
1054
|
+
if (clipped) clip.push(el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
|
|
1055
|
+
}
|
|
1056
|
+
css.remove();
|
|
1057
|
+
return clip;
|
|
1058
|
+
}'''
|
|
1059
|
+
|
|
1060
|
+
_JS_HOVER = r'''(i) => {
|
|
1061
|
+
const el = document.querySelector('[data-a11yidx="' + i + '"]');
|
|
1062
|
+
if (!el) return null;
|
|
1063
|
+
const parseCol = c => { const m = /rgba?\(([^)]+)\)/.exec(c || '');
|
|
1064
|
+
if (!m) return null;
|
|
1065
|
+
const p = m[1].split(',').map(x => parseFloat(x));
|
|
1066
|
+
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 }; };
|
|
1067
|
+
const over = (fg, bg) => ({ r: Math.round(fg.r * fg.a + bg.r * (1 - fg.a)),
|
|
1068
|
+
g: Math.round(fg.g * fg.a + bg.g * (1 - fg.a)),
|
|
1069
|
+
b: Math.round(fg.b * fg.a + bg.b * (1 - fg.a)), a: 1 });
|
|
1070
|
+
const bgOf = el => { const stack = []; let n = el;
|
|
1071
|
+
while (n) { const c = parseCol(getComputedStyle(n).backgroundColor);
|
|
1072
|
+
if (c && c.a > 0) { stack.push(c); if (c.a >= 1) break; }
|
|
1073
|
+
if (n === document.documentElement) break;
|
|
1074
|
+
n = n.parentElement; }
|
|
1075
|
+
let color = { r: 255, g: 255, b: 255, a: 1 };
|
|
1076
|
+
for (const c of stack.reverse()) color = over(c, color);
|
|
1077
|
+
return color; };
|
|
1078
|
+
const lum = c => { const f = v => { v /= 255;
|
|
1079
|
+
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
|
|
1080
|
+
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b); };
|
|
1081
|
+
const s = getComputedStyle(el);
|
|
1082
|
+
const fg = parseCol(s.color);
|
|
1083
|
+
if (!fg) return null;
|
|
1084
|
+
const bg = bgOf(el);
|
|
1085
|
+
if (bg.image) return null;
|
|
1086
|
+
const l1 = Math.max(lum(fg), lum(bg)), l2 = Math.min(lum(fg), lum(bg));
|
|
1087
|
+
return { fg: `rgb(${fg.r},${fg.g},${fg.b})`, bg: `rgb(${bg.r},${bg.g},${bg.b})`,
|
|
1088
|
+
ratio: Math.round(((l1 + 0.05) / (l2 + 0.05)) * 100) / 100 };
|
|
1089
|
+
}'''
|
|
1090
|
+
|
|
1091
|
+
# claves de lista que se fusionan de iframes same-origin (con prefijo)
|
|
1092
|
+
_IFRAME_LISTS = ('contrast', 'targets', 'unnamed', 'fields', 'imgs', 'iframes',
|
|
1093
|
+
'headings', 'tabindex', 'ariaHidden')
|
|
1094
|
+
_IFRAME_COUNTERS = ('blank', 'videos', 'videoSubs', 'tables', 'tableTh',
|
|
1095
|
+
'elements', 'contrastReview')
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def _merge_iframes(data):
|
|
1099
|
+
"""Integra los escaneos de iframes same-origin en el informe principal."""
|
|
1100
|
+
subframes = data.pop('iframes_data', [])
|
|
1101
|
+
data['nested_iframes'] = len(subframes)
|
|
1102
|
+
for sub in subframes:
|
|
1103
|
+
pref = 'iframe: '
|
|
1104
|
+
for k in _IFRAME_LISTS:
|
|
1105
|
+
for item in (sub.get(k) or [])[:12]:
|
|
1106
|
+
if isinstance(item, dict):
|
|
1107
|
+
item = dict(item, example=pref + str(item.get('example', item)))
|
|
1108
|
+
else:
|
|
1109
|
+
item = pref + str(item)
|
|
1110
|
+
data.setdefault(k, [])
|
|
1111
|
+
if len(data[k]) < 40:
|
|
1112
|
+
data[k].append(item)
|
|
1113
|
+
for k in _IFRAME_COUNTERS:
|
|
1114
|
+
data[k] = data.get(k, 0) + (sub.get(k) or 0)
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
_JS_OVERFLOW = r'''() => {
|
|
1118
|
+
const vw = document.documentElement.clientWidth;
|
|
1119
|
+
const offenders = [];
|
|
1120
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
1121
|
+
const r = el.getBoundingClientRect();
|
|
1122
|
+
if (r.right > vw + 8 && r.width > 8) {
|
|
1123
|
+
const s = getComputedStyle(el);
|
|
1124
|
+
if (s.position === 'fixed' || s.position === 'absolute') continue;
|
|
1125
|
+
if (offenders.length < 8) offenders.push({ el: el.tagName.toLowerCase()
|
|
1126
|
+
+ (el.id ? '#' + el.id : '')
|
|
1127
|
+
+ (el.className && typeof el.className === 'string' ? '.' + el.className.split(' ')[0] : ''),
|
|
1128
|
+
w: Math.round(r.width) });
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
return { vw, scroll: document.documentElement.scrollWidth, offenders };
|
|
1132
|
+
}'''
|
|
1133
|
+
|
|
1134
|
+
|
|
1135
|
+
def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
1136
|
+
"""Reflujo 320px — criterio 1.4.10 (AA), la comprobación que ni axe ni
|
|
1137
|
+
Lighthouse automatizan. Nota de método: el estándar define el reflujo como
|
|
1138
|
+
«320 CSS px, equivalente a 1280px al 400% de zoom», y el zoom real del
|
|
1139
|
+
navegador RE-HACE el layout a ese ancho — por eso la medición correcta es
|
|
1140
|
+
un viewport de 320px, no emular zoom con CSS (validado empíricamente:
|
|
1141
|
+
el truco de zoom CSS marca en falso páginas sanas porque no re-lleva a cabo
|
|
1142
|
+
el layout)."""
|
|
1143
|
+
from playwright.sync_api import sync_playwright
|
|
1144
|
+
with sync_playwright() as p:
|
|
1145
|
+
nav = p.chromium.launch()
|
|
1146
|
+
page = nav.new_page(viewport={'width': 1280, 'height': 800})
|
|
1147
|
+
try:
|
|
1148
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1149
|
+
page.wait_for_timeout(300)
|
|
1150
|
+
except Exception as e: # noqa: BLE001
|
|
1151
|
+
nav.close()
|
|
1152
|
+
return {'error': f'no se pudo cargar: {e}'}
|
|
1153
|
+
|
|
1154
|
+
page.set_viewport_size({'width': 320, 'height': 800})
|
|
1155
|
+
page.wait_for_timeout(500)
|
|
1156
|
+
r320 = page.evaluate(_JS_OVERFLOW)
|
|
1157
|
+
nav.close()
|
|
1158
|
+
|
|
1159
|
+
findings = []
|
|
1160
|
+
|
|
1161
|
+
def add(sev, code, key, examples, **fmt):
|
|
1162
|
+
findings.append({'severity': sev, 'criterion': CRIT.get(lang, CRIT['es']).get(code, code),
|
|
1163
|
+
'signal': key, 'issue': _t(lang, key, n=fmt.get('n')).format(**fmt),
|
|
1164
|
+
'remediation': _t(lang, key + '_rem').format(**fmt),
|
|
1165
|
+
'examples': examples[:6]})
|
|
1166
|
+
|
|
1167
|
+
ok320 = r320['scroll'] <= r320['vw'] + 1
|
|
1168
|
+
if not ok320:
|
|
1169
|
+
add('high', '1.4.10', 'reflow_fail',
|
|
1170
|
+
[f"{m['el']} ({m['w']}px)" for m in r320['offenders']],
|
|
1171
|
+
n=len(r320['offenders']), w=r320['vw'],
|
|
1172
|
+
det=', '.join(f"{m['el']} ({m['w']}px)" for m in r320['offenders'][:3]))
|
|
1173
|
+
|
|
1174
|
+
from .a11yaudit import compute_score
|
|
1175
|
+
return {
|
|
1176
|
+
'url': url,
|
|
1177
|
+
'mode': 'reflow',
|
|
1178
|
+
'score': compute_score(findings),
|
|
1179
|
+
'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
|
|
1180
|
+
for s_ in ('high', 'medium', 'low')},
|
|
1181
|
+
'measurements': {'reflow_320': {'scroll': r320['scroll'], 'viewport': r320['vw'],
|
|
1182
|
+
'ok': ok320}},
|
|
1183
|
+
'findings': findings,
|
|
1184
|
+
'limits': _t(lang, 'limits'),
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
|
|
1188
|
+
_JS_STOP = r"""(i) => {
|
|
1189
|
+
let a = document.activeElement;
|
|
1190
|
+
while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement;
|
|
1191
|
+
if (!a || a === document.body || a === document.documentElement) return null;
|
|
1192
|
+
if (a.tagName === 'IFRAME') return 'iframe:' + ((a.src || '').slice(0, 50));
|
|
1193
|
+
if (!a.hasAttribute('data-a11ystop')) {
|
|
1194
|
+
a.setAttribute('data-a11ystop', String(i));
|
|
1195
|
+
const ruta = a.tagName.toLowerCase() + (a.id ? '#' + a.id : '')
|
|
1196
|
+
+ (a.innerText && a.innerText.trim() ? ' "' + a.innerText.trim().slice(0, 24) + '"' : '');
|
|
1197
|
+
a.setAttribute('data-a11yruta', ruta);
|
|
1198
|
+
}
|
|
1199
|
+
return parseInt(a.getAttribute('data-a11ystop'), 10);
|
|
1200
|
+
}"""
|
|
1201
|
+
|
|
1202
|
+
_STOP_META = r"""(i) => {
|
|
1203
|
+
const el = document.querySelector('[data-a11ystop="' + i + '"]');
|
|
1204
|
+
return el ? el.getAttribute('data-a11yruta') : ('parada ' + i);
|
|
1205
|
+
}"""
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, browser='auto'):
|
|
1209
|
+
"""Detección de TRAMPAS DE TECLADO (2.1.2) con Tab real.
|
|
1210
|
+
|
|
1211
|
+
Recorre hasta max_pasos tabulaciones reales en Chromium, registra la
|
|
1212
|
+
secuencia de paradas, detecta ciclos (el patrón de un modal) y comprueba si
|
|
1213
|
+
ESCAPE libera el ciclo. Un modal que cicla y suelta con Escape es correcto;
|
|
1214
|
+
uno que no suelta es trampa — hallazgo 'high'.
|
|
1215
|
+
"""
|
|
1216
|
+
from playwright.sync_api import sync_playwright
|
|
1217
|
+
with sync_playwright() as p:
|
|
1218
|
+
nav = p.chromium.launch()
|
|
1219
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1220
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1221
|
+
try:
|
|
1222
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1223
|
+
page.wait_for_timeout(400)
|
|
1224
|
+
except Exception as e: # noqa: BLE001
|
|
1225
|
+
nav.close()
|
|
1226
|
+
return {'error': f'no se pudo cargar: {e}'}
|
|
1227
|
+
|
|
1228
|
+
page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
|
|
1229
|
+
" e.removeAttribute('data-a11ystop'); e.removeAttribute('data-a11yruta'); })")
|
|
1230
|
+
url_before = page.url
|
|
1231
|
+
seq = []
|
|
1232
|
+
paths = {}
|
|
1233
|
+
for i in range(max_steps):
|
|
1234
|
+
page.keyboard.press('Tab')
|
|
1235
|
+
try:
|
|
1236
|
+
stop = page.evaluate(_JS_STOP, i)
|
|
1237
|
+
except Exception: # noqa: BLE001
|
|
1238
|
+
# execution context destroyed = LA NAVEGACIÓN OCURRIÓ al enfocar (3.2.1)
|
|
1239
|
+
break
|
|
1240
|
+
if stop is None:
|
|
1241
|
+
break
|
|
1242
|
+
seq.append(stop)
|
|
1243
|
+
if stop not in paths:
|
|
1244
|
+
paths[stop] = page.evaluate(_STOP_META, stop)
|
|
1245
|
+
# detección de ciclo: el final de la secuencia se repite con periodo p
|
|
1246
|
+
cycle = None
|
|
1247
|
+
for p_ in range(1, min(12, len(seq) // 2) + 1):
|
|
1248
|
+
if seq[-p_:] == seq[-2 * p_:-p_] and len(set(seq[-p_:])) >= 1:
|
|
1249
|
+
# needs al menos 2 repeticiones completas del periodo
|
|
1250
|
+
reps = sum(1 for k in range(len(seq) - p_, 0, -p_)
|
|
1251
|
+
if seq[k:k + p_] == seq[-p_:])
|
|
1252
|
+
if reps >= 2:
|
|
1253
|
+
cycle = seq[-p_:]
|
|
1254
|
+
break
|
|
1255
|
+
|
|
1256
|
+
# 3.2.1: ¿el foco provocó navegación? (context destroyed = navegación)
|
|
1257
|
+
focus_navigated = None
|
|
1258
|
+
try:
|
|
1259
|
+
if page.url != url_before:
|
|
1260
|
+
focus_navigated = page.url
|
|
1261
|
+
except Exception:
|
|
1262
|
+
focus_navigated = url_before + ' → (navigated away)'
|
|
1263
|
+
|
|
1264
|
+
# 3.2.2: ¿un select provoca navegación al cambiar?
|
|
1265
|
+
input_navigated = None
|
|
1266
|
+
input_elem = None
|
|
1267
|
+
if not focus_navigated:
|
|
1268
|
+
try:
|
|
1269
|
+
sel = page.query_selector('select')
|
|
1270
|
+
if sel:
|
|
1271
|
+
opts = sel.query_selector_all('option')
|
|
1272
|
+
if len(opts) > 1:
|
|
1273
|
+
url_pre = page.url
|
|
1274
|
+
sel.select_option(index=1)
|
|
1275
|
+
page.wait_for_timeout(600)
|
|
1276
|
+
if page.url != url_pre:
|
|
1277
|
+
input_navigated = page.url
|
|
1278
|
+
input_elem = 'select'
|
|
1279
|
+
except Exception:
|
|
1280
|
+
pass
|
|
1281
|
+
|
|
1282
|
+
esc_releases = None
|
|
1283
|
+
if cycle and not focus_navigated:
|
|
1284
|
+
try:
|
|
1285
|
+
in_cycle = set(cycle)
|
|
1286
|
+
page.keyboard.press('Escape')
|
|
1287
|
+
page.wait_for_timeout(150)
|
|
1288
|
+
for _ in range(3):
|
|
1289
|
+
page.keyboard.press('Tab')
|
|
1290
|
+
page.wait_for_timeout(80)
|
|
1291
|
+
stop = page.evaluate(_JS_STOP, len(seq))
|
|
1292
|
+
if stop is None or stop not in in_cycle:
|
|
1293
|
+
esc_releases = True
|
|
1294
|
+
break
|
|
1295
|
+
else:
|
|
1296
|
+
esc_releases = False
|
|
1297
|
+
except Exception:
|
|
1298
|
+
esc_releases = None
|
|
1299
|
+
try:
|
|
1300
|
+
nav.close()
|
|
1301
|
+
except Exception:
|
|
1302
|
+
pass
|
|
1303
|
+
|
|
1304
|
+
findings = []
|
|
1305
|
+
if focus_navigated:
|
|
1306
|
+
findings.append({
|
|
1307
|
+
'severity': 'high', 'criterion': CRIT.get(lang, CRIT['es']).get('3.2.1', '3.2.1'),
|
|
1308
|
+
'signal': 'focus_navigates',
|
|
1309
|
+
'issue': _t(lang, 'focus_navigates').format(example='un elemento', url=focus_navigated[:60]),
|
|
1310
|
+
'remediation': _t(lang, 'focus_navigates_rem')})
|
|
1311
|
+
if input_navigated:
|
|
1312
|
+
findings.append({
|
|
1313
|
+
'severity': 'high', 'criterion': CRIT.get(lang, CRIT['es']).get('3.2.2', '3.2.2'),
|
|
1314
|
+
'signal': 'input_navigates',
|
|
1315
|
+
'issue': _t(lang, 'input_navigates').format(example=input_elem, url=input_navigated[:60]),
|
|
1316
|
+
'remediation': _t(lang, 'input_navigates_rem')})
|
|
1317
|
+
if cycle and esc_releases is False:
|
|
1318
|
+
elems = [paths.get(i, f'tab stop {i}') for i in cycle]
|
|
1319
|
+
findings.append({
|
|
1320
|
+
'severity': 'high', 'criterion': CRIT.get(lang, CRIT['es']).get('2.1.2', '2.1.2'),
|
|
1321
|
+
'signal': 'kbd_trap', 'issue': _t(lang, 'kbd_trap').format(
|
|
1322
|
+
n=len(cycle), cycle=' ↔ '.join(elems)),
|
|
1323
|
+
'remediation': _t(lang, 'kbd_trap_rem'),
|
|
1324
|
+
'examples': elems,
|
|
1325
|
+
})
|
|
1326
|
+
from .a11yaudit import compute_score
|
|
1327
|
+
return {
|
|
1328
|
+
'url': url,
|
|
1329
|
+
'mode': 'keyboard',
|
|
1330
|
+
'score': compute_score(findings),
|
|
1331
|
+
'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
|
|
1332
|
+
for s_ in ('high', 'medium', 'low')},
|
|
1333
|
+
'steps': len(seq),
|
|
1334
|
+
'tab_stops': [paths.get(i, f'tab stop {i}') for i in seq],
|
|
1335
|
+
'cycle': {'detected': bool(cycle),
|
|
1336
|
+
'elements': [paths.get(i, f'tab stop {i}') for i in cycle] if cycle else [],
|
|
1337
|
+
'escape_releases': esc_releases},
|
|
1338
|
+
'findings': findings,
|
|
1339
|
+
'limits': (('Real Tab walk in Chromium (max {n} steps). Focus inside cross-origin '
|
|
1340
|
+
'iframes is not trackable and is marked as such. A cycle that Escape '
|
|
1341
|
+
'releases (a correct modal) is NOT reported as a finding.'
|
|
1342
|
+
).format(n=max_steps) if lang == 'en' else
|
|
1343
|
+
('Recorrido con Tab real en Chromium (tope {n} pasos). El foco dentro de '
|
|
1344
|
+
'iframes entre dominios no es rastreable y se marca como tal. Un ciclo '
|
|
1345
|
+
'con Escape operativo (modal correcto) NO se reporta como hallazgo.'
|
|
1346
|
+
).format(n=max_steps)),
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
# La captura del FONDO real: el text_ se vuelve transparente durante el
|
|
1351
|
+
# screenshot (los glyphs desaparecen y queda el fondo puro, sin bordes de
|
|
1352
|
+
# antialiasing que sesguen el muestreo); después se restaura. La imagen se
|
|
1353
|
+
# recorta geométricamente al rect real (Playwright redondea el clip: floor de
|
|
1354
|
+
# x/y, ceil de ancho/alto — las filas/columnas de "sliver" quedan fuera).
|
|
1355
|
+
_JS_BACKGROUND = ("el => { el.__a11y_color = el.style.getPropertyValue('color'); "
|
|
1356
|
+
"el.__a11y_fill = el.style.getPropertyValue('-webkit-text-fill-color'); "
|
|
1357
|
+
"el.style.setProperty('color', 'transparent', 'important'); "
|
|
1358
|
+
"el.style.setProperty('-webkit-text-fill-color', 'transparent', 'important'); }")
|
|
1359
|
+
_JS_RESTORE = ("el => { if (el.__a11y_color !== undefined) { "
|
|
1360
|
+
"el.style.setProperty('color', el.__a11y_color); "
|
|
1361
|
+
"el.style.removeProperty('-webkit-text-fill-color'); "
|
|
1362
|
+
"if (el.__a11y_fill) el.style.setProperty('-webkit-text-fill-color', el.__a11y_fill); } }")
|
|
1363
|
+
|
|
1364
|
+
|
|
1365
|
+
def _covered_fraction(start, tam, p):
|
|
1366
|
+
"""Fracción del intervalo [p, p+1) cubierta por [ini, ini+tam)."""
|
|
1367
|
+
return max(0.0, min(p + 1.0, start + tam) - max(p, start))
|
|
1368
|
+
|
|
1369
|
+
|
|
1370
|
+
def _clip_rect(rgb, w, h, rect):
|
|
1371
|
+
"""Descarta las filas/columnas del sliver de redondeo del screenshot.
|
|
1372
|
+
|
|
1373
|
+
rect = {'x', 'y', 'width', 'height'} (coordenadas fraccionales del
|
|
1374
|
+
elemento). Devuelve (rw, rh, bytes) o None si no queda nada medible."""
|
|
1375
|
+
import math
|
|
1376
|
+
x0, y0 = math.floor(rect['x']), math.floor(rect['y'])
|
|
1377
|
+
top = 0
|
|
1378
|
+
while top < h and _covered_fraction(rect['y'], rect['height'], y0 + top) < 0.5:
|
|
1379
|
+
top += 1
|
|
1380
|
+
bot = 0
|
|
1381
|
+
while bot < h - top and _covered_fraction(rect['y'], rect['height'], y0 + h - 1 - bot) < 0.5:
|
|
1382
|
+
bot += 1
|
|
1383
|
+
left = 0
|
|
1384
|
+
while left < w and _covered_fraction(rect['x'], rect['width'], x0 + left) < 0.5:
|
|
1385
|
+
left += 1
|
|
1386
|
+
right = 0
|
|
1387
|
+
while right < w - left and _covered_fraction(rect['x'], rect['width'], x0 + w - 1 - right) < 0.5:
|
|
1388
|
+
right += 1
|
|
1389
|
+
rw, rh = w - left - right, h - top - bot
|
|
1390
|
+
if rw < 3 or rh < 3:
|
|
1391
|
+
return None
|
|
1392
|
+
clip = bytearray(rw * rh * 3)
|
|
1393
|
+
for j in range(rh):
|
|
1394
|
+
o = ((top + j) * w + left) * 3
|
|
1395
|
+
clip[j * rw * 3:(j + 1) * rw * 3] = rgb[o:o + rw * 3]
|
|
1396
|
+
return rw, rh, bytes(clip)
|
|
1397
|
+
|
|
1398
|
+
|
|
1399
|
+
def _samples_background(loc, rect, c):
|
|
1400
|
+
"""Fondo real de `loc` medido SOLO donde hay glyphs (afw4f7).
|
|
1401
|
+
|
|
1402
|
+
Dos capturas (normal y con el text_ transparente): los píxeles que
|
|
1403
|
+
difieren son los glyphs; el fondo se muestrea en exactamente esos
|
|
1404
|
+
puntos — un degradado que solo pisa al text_ por su parte clara no
|
|
1405
|
+
puede acusarse por la parte oscura donde no hay text_. Sin glyphs
|
|
1406
|
+
detectables, cae al muestreo de toda la región."""
|
|
1407
|
+
try:
|
|
1408
|
+
shot_before = loc.screenshot()
|
|
1409
|
+
loc.evaluate(_JS_BACKGROUND)
|
|
1410
|
+
png = loc.screenshot()
|
|
1411
|
+
finally:
|
|
1412
|
+
try:
|
|
1413
|
+
loc.evaluate(_JS_RESTORE)
|
|
1414
|
+
except Exception: # noqa: BLE001
|
|
1415
|
+
pass
|
|
1416
|
+
w, h, rgb = decode_png(png)
|
|
1417
|
+
clip = _clip_rect(rgb, w, h, rect)
|
|
1418
|
+
if not clip:
|
|
1419
|
+
return None
|
|
1420
|
+
rw, rh, rgb2 = clip
|
|
1421
|
+
try:
|
|
1422
|
+
wA, hA, rgbA = decode_png(shot_before)
|
|
1423
|
+
clipA = _clip_rect(rgbA, wA, hA, rect)
|
|
1424
|
+
if clipA and (clipA[0], clipA[1]) == (rw, rh):
|
|
1425
|
+
glyphs = []
|
|
1426
|
+
for o in range(0, rw * rh):
|
|
1427
|
+
x3, a3 = o * 3, o * 3
|
|
1428
|
+
d = abs(rgb2[x3] - clipA[2][a3]) + abs(rgb2[x3 + 1] - clipA[2][a3 + 1]) \
|
|
1429
|
+
+ abs(rgb2[x3 + 2] - clipA[2][a3 + 2])
|
|
1430
|
+
if d > 90:
|
|
1431
|
+
glyphs.append(o)
|
|
1432
|
+
if len(glyphs) >= 8:
|
|
1433
|
+
lt = luminance(c)
|
|
1434
|
+
ratios = []
|
|
1435
|
+
for o in glyphs[::max(1, len(glyphs) // 600)]:
|
|
1436
|
+
px = (rgb2[o * 3] / 255, rgb2[o * 3 + 1] / 255, rgb2[o * 3 + 2] / 255)
|
|
1437
|
+
lb = luminance({'r': rgb2[o * 3], 'g': rgb2[o * 3 + 1], 'b': rgb2[o * 3 + 2]})
|
|
1438
|
+
l1, l2 = max(lt, lb), min(lt, lb)
|
|
1439
|
+
ratios.append((l1 + 0.05) / (l2 + 0.05))
|
|
1440
|
+
ratios.sort()
|
|
1441
|
+
p95 = ratios[max(0, int(len(ratios) * 0.95) - 1)]
|
|
1442
|
+
return {'worst_ratio': round(ratios[0], 2),
|
|
1443
|
+
'median_ratio': round(ratios[len(ratios) // 2], 2),
|
|
1444
|
+
'p95_ratio': round(p95, 2),
|
|
1445
|
+
'area_passes_aa_normal_text_4_5': round(
|
|
1446
|
+
100 * sum(1 for r in ratios if r >= 4.5) / len(ratios)),
|
|
1447
|
+
'area_passes_aa_min_3_0': round(
|
|
1448
|
+
100 * sum(1 for r in ratios if r >= 3.0) / len(ratios)),
|
|
1449
|
+
'sampled_pixels': len(ratios),
|
|
1450
|
+
'method': 'glyph-diff'}
|
|
1451
|
+
except Exception: # noqa: BLE001
|
|
1452
|
+
pass
|
|
1453
|
+
return sample_rgb(rw, rh, rgb2, c)
|
|
1454
|
+
|
|
1455
|
+
|
|
1456
|
+
def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
1457
|
+
"""1.4.3/1.4.12-adjacente — ¿sobrevive el contenido a forced-colors: active?
|
|
1458
|
+
|
|
1459
|
+
Los usuarios de Windows High Contrast Mode (ahora forced-colors CSS) ven
|
|
1460
|
+
la paleta del sistema: los colores del autor desaparecen. Lo que se
|
|
1461
|
+
rompe: text_ pintado con color sobre fondo pintado (los DOS pasan al
|
|
1462
|
+
esquema del sistema, el contraste del autor ya no aplica — pero los
|
|
1463
|
+
iconos SVG con fill coloreado y las imágenes informativas PNG que
|
|
1464
|
+
dependen del color del autor pueden quedar invisible_els sobre el fondo
|
|
1465
|
+
del sistema), y bordes usados como único indicador visual. Nadie más
|
|
1466
|
+
lo automatiza."""
|
|
1467
|
+
from playwright.sync_api import sync_playwright
|
|
1468
|
+
_JS_FC = r'''() => {
|
|
1469
|
+
const invisible_els = [];
|
|
1470
|
+
let n = 0;
|
|
1471
|
+
for (const el of document.querySelectorAll('svg, img, [role=img], canvas')) {
|
|
1472
|
+
if (n >= 400) break;
|
|
1473
|
+
n++;
|
|
1474
|
+
const r = el.getBoundingClientRect();
|
|
1475
|
+
if (r.width <= 2 || r.height <= 2) continue;
|
|
1476
|
+
const cs = getComputedStyle(el);
|
|
1477
|
+
if (cs.visibility === 'hidden' || cs.display === 'none') continue;
|
|
1478
|
+
// con forced-colors, fill/stroke coloreados del autor caen a heredado
|
|
1479
|
+
// salvo que usen los keywords del sistema; detectar fill coloreado
|
|
1480
|
+
// hardcoded en SVG (ni currentColor ni CanvasText)
|
|
1481
|
+
if (el.tagName.toLowerCase() === 'svg') {
|
|
1482
|
+
const fills = [...el.querySelectorAll('[fill]')].map(x => x.getAttribute('fill'));
|
|
1483
|
+
if (el.getAttribute('fill')) fills.push(el.getAttribute('fill'));
|
|
1484
|
+
const col = fills.find(f => f && !['currentColor', 'CanvasText', 'Canvas', 'none',
|
|
1485
|
+
'inherit', 'transparent'].includes(f)
|
|
1486
|
+
&& !f.startsWith('url('));
|
|
1487
|
+
if (col) invisible_els.push('svg fill=' + col + ' — puede desaparecer en HCM');
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
// imágenes informativas sin forced-color-adjust: en HCM Windows las
|
|
1491
|
+
// oscurece; si el PNG es oscuro, desaparece. Señal de revisión si hay
|
|
1492
|
+
// PNG con clase de icono (heurística humilde)
|
|
1493
|
+
const icons = document.querySelectorAll('img[class*=icon i], svg[class*=icon i]').length;
|
|
1494
|
+
return { coloredSvgs: invisible_els.slice(0, 8), icons };
|
|
1495
|
+
}'''
|
|
1496
|
+
from .a11yaudit import _t as _t_audit, CRIT, compute_score
|
|
1497
|
+
|
|
1498
|
+
with sync_playwright() as p:
|
|
1499
|
+
nav = p.chromium.launch()
|
|
1500
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1501
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1502
|
+
try:
|
|
1503
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1504
|
+
page.wait_for_timeout(400)
|
|
1505
|
+
normal = page.evaluate(_JS_FC)
|
|
1506
|
+
page.emulate_media(forced_colors='active')
|
|
1507
|
+
page.wait_for_timeout(400)
|
|
1508
|
+
forced = page.evaluate(_JS_FC)
|
|
1509
|
+
except Exception as e: # noqa: BLE001
|
|
1510
|
+
nav.close()
|
|
1511
|
+
return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
|
|
1512
|
+
nav.close()
|
|
1513
|
+
|
|
1514
|
+
findings = []
|
|
1515
|
+
if forced['coloredSvgs']:
|
|
1516
|
+
findings.append({
|
|
1517
|
+
'severity': 'low', 'criterion': CRIT.get(lang, CRIT['es']).get('1.4.3', '1.4.3'),
|
|
1518
|
+
'signal': 'forced_colors_svg',
|
|
1519
|
+
'issue': _t_audit(lang, 'forced_colors_svg').format(n=len(forced['coloredSvgs'])),
|
|
1520
|
+
'remediation': _t_audit(lang, 'forced_colors_svg_rem'),
|
|
1521
|
+
'examples': forced['coloredSvgs']})
|
|
1522
|
+
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
1523
|
+
findings.sort(key=lambda h: order[h['severity']])
|
|
1524
|
+
return {
|
|
1525
|
+
'mode': 'forced-colors', 'url': url,
|
|
1526
|
+
'normal': normal, 'forced': forced,
|
|
1527
|
+
'score': compute_score(findings),
|
|
1528
|
+
'findings': findings,
|
|
1529
|
+
'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
|
|
1530
|
+
for s2 in ('high', 'medium', 'low')},
|
|
1531
|
+
'limits': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
|
|
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.'),
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
|
|
1538
|
+
def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
1539
|
+
"""2.2.2 (2.3.3) — ¿respeta el sitio prefers-reduced-motion?
|
|
1540
|
+
|
|
1541
|
+
Carga la página normal y cuenta animaciones CSS en bucle (>0.15s,
|
|
1542
|
+
infinite). Recarga emulando prefers-reduced-motion: reduce y cuenta otra
|
|
1543
|
+
vez. Si el número NO baja, el sitio ignora la preferencia del usuario
|
|
1544
|
+
(2.2.2: pausa/parada/ocultar; 2.3.3 AAA). Nadie más lo automatiza:
|
|
1545
|
+
axe lo deja en revisión manual."""
|
|
1546
|
+
from playwright.sync_api import sync_playwright
|
|
1547
|
+
_JS_RM = r'''() => {
|
|
1548
|
+
let n = 0, examples = [];
|
|
1549
|
+
for (const el of document.querySelectorAll('*')) {
|
|
1550
|
+
if (n >= 40) break;
|
|
1551
|
+
const cs = getComputedStyle(el);
|
|
1552
|
+
if (cs.animationIterationCount !== 'infinite' || cs.animationName === 'none') continue;
|
|
1553
|
+
const durs = (cs.animationDuration || '0s').split(',').map(
|
|
1554
|
+
x => { const v = parseFloat(x) || 0; return x.includes('ms') ? v / 1000 : v; });
|
|
1555
|
+
const dur = Math.max(...durs, 0);
|
|
1556
|
+
if (dur <= 0.15) continue;
|
|
1557
|
+
n++;
|
|
1558
|
+
if (examples.length < 6) examples.push(
|
|
1559
|
+
el.tagName.toLowerCase() + (el.id ? '#' + el.id : '')
|
|
1560
|
+
+ '.' + String(el.className).slice(0, 25) + ' (' + cs.animationName.slice(0, 30) + ')');
|
|
1561
|
+
}
|
|
1562
|
+
const videos = document.querySelectorAll('video[autoplay]').length;
|
|
1563
|
+
return { anims: n, examples: examples, videos };
|
|
1564
|
+
}'''
|
|
1565
|
+
from .a11yaudit import _t as _t_audit, CRIT, compute_score
|
|
1566
|
+
|
|
1567
|
+
with sync_playwright() as p:
|
|
1568
|
+
nav = p.chromium.launch()
|
|
1569
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1570
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1571
|
+
try:
|
|
1572
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1573
|
+
page.wait_for_timeout(600)
|
|
1574
|
+
normal = page.evaluate(_JS_RM)
|
|
1575
|
+
page.emulate_media(reduced_motion='reduce')
|
|
1576
|
+
page.wait_for_timeout(600)
|
|
1577
|
+
reduced = page.evaluate(_JS_RM)
|
|
1578
|
+
except Exception as e: # noqa: BLE001
|
|
1579
|
+
nav.close()
|
|
1580
|
+
return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
|
|
1581
|
+
nav.close()
|
|
1582
|
+
|
|
1583
|
+
respects = reduced['anims'] < normal['anims']
|
|
1584
|
+
findings = []
|
|
1585
|
+
if normal['anims'] > 0 and not respects:
|
|
1586
|
+
findings.append({
|
|
1587
|
+
'severity': 'medium', 'criterion': CRIT.get(lang, CRIT['es']).get('2.2.2', '2.2.2'),
|
|
1588
|
+
'signal': 'reduced_motion_ignored',
|
|
1589
|
+
'issue': _t_audit(lang, 'reduced_motion_ignored').format(
|
|
1590
|
+
n=normal['anims'], nr=reduced['anims']),
|
|
1591
|
+
'remediation': _t_audit(lang, 'reduced_motion_ignored_rem'),
|
|
1592
|
+
'examples': normal['examples'][:4]})
|
|
1593
|
+
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
1594
|
+
findings.sort(key=lambda h: order[h['severity']])
|
|
1595
|
+
return {
|
|
1596
|
+
'mode': 'reduced-motion', 'url': url,
|
|
1597
|
+
'normal': normal, 'reduced': reduced,
|
|
1598
|
+
'respects': respects,
|
|
1599
|
+
'score': compute_score(findings),
|
|
1600
|
+
'findings': findings,
|
|
1601
|
+
'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
|
|
1602
|
+
for s2 in ('high', 'medium', 'low')},
|
|
1603
|
+
'limits': ('Mide CSS animations y video[autoplay]. No cubre '
|
|
1604
|
+
'animaciones JS/WebGL ni parallax por scroll — revisión manual.'),
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
|
|
1608
|
+
def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', color_scheme='light'):
|
|
1609
|
+
"""Carga la URL en Chromium y devuelve el informe renderizado.
|
|
1610
|
+
|
|
1611
|
+
Escanea también los iframes same-origin (hasta 4) y contrasta los estados
|
|
1612
|
+
:hover reales de los primeros controles marcados. auth_state: ruta a un
|
|
1613
|
+
storage_state de Playwright (cookies/localStorage exportados con la sesión
|
|
1614
|
+
iniciada) para auditar detrás de login."""
|
|
1615
|
+
from playwright.sync_api import sync_playwright
|
|
1616
|
+
with sync_playwright() as p:
|
|
1617
|
+
nav = p.chromium.launch()
|
|
1618
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1619
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1620
|
+
if color_scheme in ('dark', 'light'):
|
|
1621
|
+
# contraste por esquema: los temas oscuros fallan donde el claro
|
|
1622
|
+
# pasa — nadie audita ambos (axe tampoco)
|
|
1623
|
+
page.emulate_media(color_scheme=color_scheme)
|
|
1624
|
+
try:
|
|
1625
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1626
|
+
page.wait_for_timeout(400)
|
|
1627
|
+
except Exception as e: # noqa: BLE001
|
|
1628
|
+
if not page.content() or page.url in ('about:blank', ''):
|
|
1629
|
+
nav.close()
|
|
1630
|
+
return {'error': f'no se pudo cargar: {e}'}
|
|
1631
|
+
try:
|
|
1632
|
+
data = page.evaluate(_JS, MAX_EXAMPLES)
|
|
1633
|
+
# 1.4.12: inject the WCAG spacing overrides, count clipped texts
|
|
1634
|
+
data['spacingClipped'] = page.evaluate(_JS_SPACING)
|
|
1635
|
+
# 1.4.3 real: captura + muestreo píxel a píxel de las zonas sobre
|
|
1636
|
+
# imagen/degradado que el contraste computado no puede calcular
|
|
1637
|
+
# (main frame; los iframes quedan como conteo de "revisar")
|
|
1638
|
+
measured = []
|
|
1639
|
+
for z in (data.get('contrastZones') or [])[:8]:
|
|
1640
|
+
try:
|
|
1641
|
+
c = parse_color(z['fg'])
|
|
1642
|
+
if not c:
|
|
1643
|
+
continue
|
|
1644
|
+
m = _samples_background(
|
|
1645
|
+
page.locator(f'[data-a11ytxt="{z["i"]}"]'),
|
|
1646
|
+
{'x': z.get('x', 0), 'y': z.get('y', 0),
|
|
1647
|
+
'width': z.get('w', 1400), 'height': z.get('h', 400)}, c)
|
|
1648
|
+
if m:
|
|
1649
|
+
measured.append({'example': z['example'], 'fg': z['fg'],
|
|
1650
|
+
'large': bool(z.get('large')),
|
|
1651
|
+
'measured': m})
|
|
1652
|
+
except Exception: # noqa: BLE001
|
|
1653
|
+
continue
|
|
1654
|
+
data['contrastMeasured'] = measured
|
|
1655
|
+
# iframes same-origin: mismo colector por frame
|
|
1656
|
+
subframes = []
|
|
1657
|
+
for fr in page.frames[1:5]:
|
|
1658
|
+
try:
|
|
1659
|
+
subframes.append(fr.evaluate(_JS, MAX_EXAMPLES))
|
|
1660
|
+
except Exception: # noqa: BLE001
|
|
1661
|
+
continue # cross-origin o no escaneable
|
|
1662
|
+
data['iframes_data'] = subframes
|
|
1663
|
+
# hover real sobre los controles marcados
|
|
1664
|
+
hover = []
|
|
1665
|
+
for i in range(min(10, int(data.get('marks', 0)))):
|
|
1666
|
+
try:
|
|
1667
|
+
page.hover(f'[data-a11yidx="{i}"]', timeout=1000)
|
|
1668
|
+
r = page.evaluate(_JS_HOVER, i)
|
|
1669
|
+
if r and r['ratio'] < 3:
|
|
1670
|
+
hover.append(dict(r, example=f'hover #{i}'))
|
|
1671
|
+
except Exception: # noqa: BLE001
|
|
1672
|
+
continue
|
|
1673
|
+
data['hover'] = hover
|
|
1674
|
+
finally:
|
|
1675
|
+
try:
|
|
1676
|
+
ctx.close()
|
|
1677
|
+
except Exception:
|
|
1678
|
+
pass
|
|
1679
|
+
_merge_iframes(data)
|
|
1680
|
+
return audit_dom(data, url, lang=lang, color_scheme=color_scheme)
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45,
|
|
1684
|
+
auth_state=None, browser='auto'):
|
|
1685
|
+
"""Contraste REAL de un elemento contra lo que sea que tenga detrás.
|
|
1686
|
+
|
|
1687
|
+
La versión automatizada de a11y_contrast_image: carga la página, captura el
|
|
1688
|
+
elemento que coincide con `selector` con el text_ en transparente (queda el
|
|
1689
|
+
fondo puro, sin bordes de antialiasing), muestrea sus píxeles y los
|
|
1690
|
+
contrasta con el color del text_ — computado del elemento cuando no se da.
|
|
1691
|
+
Para text_ sobre imágenes, degradados, vídeo o cualquier fondo que el
|
|
1692
|
+
cálculo CSS no puede resolver. Requiere Playwright.
|
|
1693
|
+
"""
|
|
1694
|
+
from playwright.sync_api import sync_playwright
|
|
1695
|
+
from .contrast import T as _TC
|
|
1696
|
+
t9 = _TC.get(lang, _TC['es'])
|
|
1697
|
+
with sync_playwright() as p:
|
|
1698
|
+
nav = p.chromium.launch()
|
|
1699
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1700
|
+
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1701
|
+
try:
|
|
1702
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1703
|
+
page.wait_for_timeout(300)
|
|
1704
|
+
loc = page.locator(selector).first
|
|
1705
|
+
try:
|
|
1706
|
+
loc.wait_for(timeout=timeout * 1000)
|
|
1707
|
+
except Exception: # noqa: BLE001
|
|
1708
|
+
return {'error': t9['selector_missing'].format(s=selector)}
|
|
1709
|
+
if text_color:
|
|
1710
|
+
c = parse_color(text_color)
|
|
1711
|
+
if not c:
|
|
1712
|
+
return {'error': t9['invalid_color']}
|
|
1713
|
+
else:
|
|
1714
|
+
comp = loc.evaluate('el => getComputedStyle(el).color')
|
|
1715
|
+
c = parse_color(comp)
|
|
1716
|
+
if not c:
|
|
1717
|
+
return {'error': f"{t9['invalid_color']} (computed: {comp})"}
|
|
1718
|
+
if c.get('a', 1) < 1:
|
|
1719
|
+
return {'error': t9['opaque_text']}
|
|
1720
|
+
try:
|
|
1721
|
+
box = loc.bounding_box()
|
|
1722
|
+
if not box or box['width'] < 3 or box['height'] < 3:
|
|
1723
|
+
return {'error': t9['no_box'].format(s=selector)}
|
|
1724
|
+
m = _samples_background(loc, box, c)
|
|
1725
|
+
except Exception: # noqa: BLE001
|
|
1726
|
+
return {'error': t9['no_box'].format(s=selector)}
|
|
1727
|
+
if not m:
|
|
1728
|
+
return {'error': t9['no_pixels']}
|
|
1729
|
+
out = {'url': url, 'selector': selector, 'text_color': hexs(c),
|
|
1730
|
+
'image': f'{selector} ({round(box["width"])}×{round(box["height"])})',
|
|
1731
|
+
'worst_ratio': m['worst_ratio'],
|
|
1732
|
+
'median_ratio': m['median_ratio'],
|
|
1733
|
+
'p95_ratio': m['p95_ratio'],
|
|
1734
|
+
'area_passes_aa_normal_text_4_5': m['area_passes_aa_normal_text_4_5'],
|
|
1735
|
+
'area_passes_aa_min_3_0': m['area_passes_aa_min_3_0'],
|
|
1736
|
+
'sampled_pixels': m['sampled_pixels'],
|
|
1737
|
+
'interpretation': t9['interp']}
|
|
1738
|
+
if 'worst_zone' in m:
|
|
1739
|
+
out['worst_zone'] = m['worst_zone']
|
|
1740
|
+
return out
|
|
1741
|
+
finally:
|
|
1742
|
+
try:
|
|
1743
|
+
ctx.close()
|
|
1744
|
+
except Exception: # noqa: BLE001
|
|
1745
|
+
pass
|
|
1746
|
+
|
|
1747
|
+
|
|
1748
|
+
def contrast_dom_main(argv):
|
|
1749
|
+
ap = argparse.ArgumentParser(description='Real text-over-anything contrast: screenshot + pixel sampling (auto-region)')
|
|
1750
|
+
ap.add_argument('url')
|
|
1751
|
+
ap.add_argument('--selector', required=True, help='CSS selector of the text element')
|
|
1752
|
+
ap.add_argument('--text', help='text color (default: computed from the element)')
|
|
1753
|
+
ap.add_argument('--sample', type=int, default=4)
|
|
1754
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
1755
|
+
ap.add_argument('--timeout', type=int, default=45)
|
|
1756
|
+
a = ap.parse_args(argv)
|
|
1757
|
+
try:
|
|
1758
|
+
res = contrast_dom(a.url, a.selector, text_color=a.text, sample=a.sample,
|
|
1759
|
+
lang=a.lang, timeout=a.timeout)
|
|
1760
|
+
except ImportError:
|
|
1761
|
+
print(json.dumps({'error': 'Playwright not installed'}))
|
|
1762
|
+
return 1
|
|
1763
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1764
|
+
return 0
|
|
1765
|
+
|
|
1766
|
+
|
|
1767
|
+
def main(argv):
|
|
1768
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
1769
|
+
ap.add_argument('url')
|
|
1770
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
1771
|
+
ap.add_argument('--timeout', type=int, default=45)
|
|
1772
|
+
a = ap.parse_args(argv)
|
|
1773
|
+
try:
|
|
1774
|
+
res = audit_dom_url(a.url, timeout=a.timeout, lang=a.lang)
|
|
1775
|
+
except ImportError:
|
|
1776
|
+
print(json.dumps({'error': 'Playwright not installed: pip install playwright && playwright install chromium'}))
|
|
1777
|
+
return 1
|
|
1778
|
+
except Exception as e: # noqa: BLE001
|
|
1779
|
+
print(json.dumps({'error': str(e)}))
|
|
1780
|
+
return 1
|
|
1781
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1782
|
+
return 0
|
|
1783
|
+
|
|
1784
|
+
|
|
1785
|
+
def reflow_main(argv):
|
|
1786
|
+
ap = argparse.ArgumentParser(description='Reflujo 320px (1.4.10)')
|
|
1787
|
+
ap.add_argument('url')
|
|
1788
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
1789
|
+
ap.add_argument('--timeout', type=int, default=45)
|
|
1790
|
+
a = ap.parse_args(argv)
|
|
1791
|
+
try:
|
|
1792
|
+
res = audit_reflow(a.url, timeout=a.timeout, lang=a.lang)
|
|
1793
|
+
except ImportError:
|
|
1794
|
+
print(json.dumps({'error': 'Playwright not installed'}))
|
|
1795
|
+
return 1
|
|
1796
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1797
|
+
return 0
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
def forms_main(argv):
|
|
1801
|
+
ap = argparse.ArgumentParser(description='Form errors: fill invalid + submit + judge (3.3.1/3.3.3)')
|
|
1802
|
+
ap.add_argument('url')
|
|
1803
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
1804
|
+
ap.add_argument('--timeout', type=int, default=45)
|
|
1805
|
+
a = ap.parse_args(argv)
|
|
1806
|
+
try:
|
|
1807
|
+
res = audit_forms(a.url, timeout=a.timeout, lang=a.lang)
|
|
1808
|
+
except ImportError:
|
|
1809
|
+
print(json.dumps({'error': 'Playwright not installed'}))
|
|
1810
|
+
return 1
|
|
1811
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1812
|
+
return 0
|
|
1813
|
+
|
|
1814
|
+
|
|
1815
|
+
def kbd_main(argv):
|
|
1816
|
+
ap = argparse.ArgumentParser(description='Trampas de teclado (2.1.2) con Tab real')
|
|
1817
|
+
ap.add_argument('url')
|
|
1818
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
1819
|
+
ap.add_argument('--max-steps', type=int, default=60)
|
|
1820
|
+
a = ap.parse_args(argv)
|
|
1821
|
+
try:
|
|
1822
|
+
res = audit_keyboard(a.url, max_steps=a.max_steps, lang=a.lang)
|
|
1823
|
+
except ImportError:
|
|
1824
|
+
print(json.dumps({'error': 'Playwright not installed'}))
|
|
1825
|
+
return 1
|
|
1826
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1827
|
+
return 0
|
|
1828
|
+
|
|
1829
|
+
|
|
1830
|
+
if __name__ == '__main__':
|
|
1831
|
+
sys.exit(main(sys.argv[1:]))
|