@sloppy-ai/verify 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/accessibility.mjs +420 -0
- package/browser.mjs +30 -0
- package/class-clash-core.mjs +130 -0
- package/class-clash.mjs +52 -0
- package/film-checks.mjs +2120 -0
- package/film.mjs +664 -0
- package/jumps-core.mjs +191 -0
- package/jumps.mjs +68 -0
- package/layout-core.mjs +164 -0
- package/layout.mjs +65 -0
- package/motion-watch.mjs +557 -0
- package/multi-width.mjs +244 -0
- package/package.json +40 -4
- package/verification.mjs +401 -0
- package/README.md +0 -3
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* DOM-backed accessibility verification.
|
|
4
|
+
*
|
|
5
|
+
* The browser collector is deliberately separate from the pure audit function so
|
|
6
|
+
* the checks can be tested with a synthetic role/name/rect snapshot without a
|
|
7
|
+
* browser. This module never claims a pass when the browser is unavailable.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { tryLaunch } from './browser.mjs';
|
|
11
|
+
|
|
12
|
+
const INTERACTIVE_ROLES = new Set([
|
|
13
|
+
'button', 'link', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio',
|
|
14
|
+
'switch', 'checkbox', 'radio', 'option', 'slider', 'spinbutton', 'combobox'
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
const FORM_TAGS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);
|
|
18
|
+
|
|
19
|
+
function overlapsAnotherTarget(item, snapshot) {
|
|
20
|
+
const { x = 0, y = 0, width = 0, height = 0 } = item.rect;
|
|
21
|
+
const cx = x + width / 2;
|
|
22
|
+
const cy = y + height / 2;
|
|
23
|
+
const box = { left: cx - 12, right: cx + 12, top: cy - 12, bottom: cy + 12 };
|
|
24
|
+
return snapshot.some((other) => {
|
|
25
|
+
if (!other || other === item || other.hidden || other.disabled || !other.rect) return false;
|
|
26
|
+
const rect = other.rect;
|
|
27
|
+
if (!Number.isFinite(rect.x) || !Number.isFinite(rect.y)) return false;
|
|
28
|
+
if (!['BUTTON', 'A', 'SUMMARY', 'INPUT', 'SELECT', 'TEXTAREA'].includes(other.tag) && !other.role) return false;
|
|
29
|
+
return rect.x < box.right && rect.x + rect.width > box.left && rect.y < box.bottom && rect.y + rect.height > box.top;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function analyzeFocusOrder(stops) {
|
|
34
|
+
const jumps = [];
|
|
35
|
+
for (let index = 1; index < stops.length; index += 1) {
|
|
36
|
+
const previous = stops[index - 1];
|
|
37
|
+
const current = stops[index];
|
|
38
|
+
if (!previous || !current || current.selector === stops[0]?.selector) continue;
|
|
39
|
+
if (previous.positiveTabindex || current.positiveTabindex) continue;
|
|
40
|
+
const verticalDelta = previous.docTop - current.docTop;
|
|
41
|
+
const horizontalDelta = (previous.docLeft ?? 0) - (current.docLeft ?? 0);
|
|
42
|
+
const verticalJump = verticalDelta > 24;
|
|
43
|
+
const horizontalJump = Math.abs(previous.docTop - current.docTop) <= 8 && horizontalDelta > 50;
|
|
44
|
+
if (verticalJump || horizontalJump) {
|
|
45
|
+
jumps.push({ from: previous.selector, to: current.selector, delta: verticalJump ? verticalDelta : horizontalDelta });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return jumps;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function auditA11ySnapshot(snapshot, options = {}) {
|
|
52
|
+
const findings = [];
|
|
53
|
+
const push = (rule, message, item, extra = {}) => {
|
|
54
|
+
findings.push({
|
|
55
|
+
rule,
|
|
56
|
+
message,
|
|
57
|
+
severity: extra.severity || 'medium',
|
|
58
|
+
confidence: extra.confidence || 'high',
|
|
59
|
+
objective: extra.objective !== false,
|
|
60
|
+
evidence: {
|
|
61
|
+
kind: extra.kind || 'dom',
|
|
62
|
+
description: message,
|
|
63
|
+
selector: item?.selector,
|
|
64
|
+
viewport: options.viewport,
|
|
65
|
+
criterion: extra.criterion
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
for (const item of snapshot) {
|
|
71
|
+
if (!item || item.hidden || item.disabled) continue;
|
|
72
|
+
const role = String(item.role || '').toLowerCase();
|
|
73
|
+
const isInteractive = INTERACTIVE_ROLES.has(role) || ['BUTTON', 'A', 'SUMMARY'].includes(item.tag);
|
|
74
|
+
const isForm = FORM_TAGS.has(item.tag) && String(item.type || '').toLowerCase() !== 'hidden';
|
|
75
|
+
const hasName = Boolean(String(item.name || '').trim());
|
|
76
|
+
|
|
77
|
+
if ((isInteractive || isForm) && !hasName) {
|
|
78
|
+
const isFormControl = isForm && !['button', 'submit', 'reset'].includes(String(item.type || '').toLowerCase());
|
|
79
|
+
if (isFormControl) {
|
|
80
|
+
push('a11y.inputUnlabeled', `Form control <${item.tag.toLowerCase()}> has no label, aria-label, or labelledby reference.`, item, {
|
|
81
|
+
severity: 'high',
|
|
82
|
+
criterion: 'WCAG 3.3.2 Labels or Instructions / 4.1.2 Name, Role, Value'
|
|
83
|
+
});
|
|
84
|
+
} else {
|
|
85
|
+
push('a11y.nameMissing', `Interactive <${item.tag.toLowerCase()}> has no accessible name.`, item, {
|
|
86
|
+
severity: 'high',
|
|
87
|
+
criterion: 'WCAG 4.1.2 Name, Role, Value'
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (item.focusVisible === false && Number(item.tabIndex) >= 0) {
|
|
93
|
+
push('a11y.focusInvisible', `Focused <${item.tag.toLowerCase()}> has no visible outline or focus shadow.`, item, {
|
|
94
|
+
severity: 'medium',
|
|
95
|
+
confidence: 'medium',
|
|
96
|
+
criterion: 'WCAG 2.4.7 Focus Visible'
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (isInteractive && item.rect && !item.inlineLink) {
|
|
101
|
+
const { width = 0, height = 0, x, y } = item.rect;
|
|
102
|
+
const undersized = width > 0 && height > 0 && (width < 24 || height < 24);
|
|
103
|
+
const spacingExempt = undersized && Number.isFinite(x) && Number.isFinite(y) && !overlapsAnotherTarget(item, snapshot);
|
|
104
|
+
if (undersized && !spacingExempt) {
|
|
105
|
+
push('a11y.targetTooSmall', `Interactive target is ${Math.round(width)}x${Math.round(height)}px; WCAG 2.2 AA requires at least 24x24 CSS px.`, item, {
|
|
106
|
+
severity: 'medium',
|
|
107
|
+
confidence: 'medium',
|
|
108
|
+
criterion: 'WCAG 2.5.8 Target Size (Minimum)'
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (Number(item.explicitTabIndex) > 0) {
|
|
114
|
+
push('a11y.positiveTabindex', `Explicit tabindex="${item.explicitTabIndex}" overrides the natural focus order.`, item, {
|
|
115
|
+
severity: 'medium',
|
|
116
|
+
objective: false,
|
|
117
|
+
criterion: 'WCAG 2.4.3 Focus Order'
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (item.ariaExpanded !== undefined && item.ariaExpanded !== null && !item.ariaControls) {
|
|
122
|
+
push('a11y.stateUnwired', `Element exposes aria-expanded="${item.ariaExpanded}" without aria-controls naming the region it expands.`, item, {
|
|
123
|
+
severity: 'medium',
|
|
124
|
+
confidence: 'medium',
|
|
125
|
+
objective: false,
|
|
126
|
+
criterion: 'WCAG 4.1.2 Name, Role, Value'
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
for (const duplicate of options.duplicateIds || []) {
|
|
132
|
+
push('a11y.duplicateId', `Duplicate id "${duplicate}" makes labels and aria references ambiguous.`, { selector: `#${duplicate}` }, {
|
|
133
|
+
severity: 'low',
|
|
134
|
+
confidence: 'high',
|
|
135
|
+
objective: false
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
for (const broken of options.brokenReferences || []) {
|
|
140
|
+
push('a11y.brokenReference', `${broken.attribute} references missing id "${broken.id}".`, { selector: broken.selector }, {
|
|
141
|
+
severity: 'high',
|
|
142
|
+
criterion: 'WCAG 4.1.2 Name, Role, Value'
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
for (const jump of options.focusOrderJumps || []) {
|
|
147
|
+
push('a11y.focusOrderJump', `Tab order moves from "${jump.from}" to "${jump.to}" (${Math.round(Math.abs(jump.delta))}px backwards); confirm the focus sequence follows the visual reading order.`, { selector: jump.to }, {
|
|
148
|
+
severity: 'low',
|
|
149
|
+
confidence: 'low',
|
|
150
|
+
objective: false,
|
|
151
|
+
kind: 'interaction',
|
|
152
|
+
criterion: 'WCAG 2.4.3 Focus Order'
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (options.reflowOverflow) {
|
|
157
|
+
push('a11y.reflowOverflow', `At 320 CSS px the page scrolls horizontally (${options.reflowOverflow.scrollWidth}px content in ${options.reflowOverflow.clientWidth}px viewport).`, { selector: 'document' }, {
|
|
158
|
+
severity: 'high',
|
|
159
|
+
criterion: 'WCAG 1.4.10 Reflow'
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
for (const clipped of options.textResizeClipped || []) {
|
|
164
|
+
push('a11y.textResizeClipped', `At 200% text size, text is clipped inside a fixed-height element (${clipped.scrollHeight}px content in ${clipped.clientHeight}px box).`, { selector: clipped.selector }, {
|
|
165
|
+
severity: 'medium',
|
|
166
|
+
confidence: 'medium',
|
|
167
|
+
kind: 'computed-style',
|
|
168
|
+
criterion: 'WCAG 1.4.4 Resize Text'
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (options.reducedMotionIgnored) {
|
|
173
|
+
push('a11y.reducedMotionIgnored', 'Infinite animation keeps running under prefers-reduced-motion: reduce.', { selector: 'document' }, {
|
|
174
|
+
severity: 'low',
|
|
175
|
+
confidence: 'low',
|
|
176
|
+
objective: false,
|
|
177
|
+
kind: 'computed-style'
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return findings;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function runAccessibilityAudit(target, options = {}) {
|
|
185
|
+
if (!/^https?:\/\//i.test(String(target))) {
|
|
186
|
+
return {
|
|
187
|
+
target,
|
|
188
|
+
ok: false,
|
|
189
|
+
mode: 'static',
|
|
190
|
+
isStaticFallback: true,
|
|
191
|
+
findings: [],
|
|
192
|
+
summary: 'Accessibility audit requires a served http(s) URL; no DOM snapshot was collected.',
|
|
193
|
+
unavailable: 'Accessibility evidence requires a browser and a served URL.'
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const launchResult = await tryLaunch();
|
|
198
|
+
if (!launchResult.browser) {
|
|
199
|
+
return {
|
|
200
|
+
target,
|
|
201
|
+
ok: false,
|
|
202
|
+
mode: 'browser',
|
|
203
|
+
isStaticFallback: false,
|
|
204
|
+
findings: [],
|
|
205
|
+
summary: `Accessibility audit unavailable: ${launchResult.reason}`,
|
|
206
|
+
unavailable: launchResult.reason
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const browser = launchResult.browser;
|
|
211
|
+
const page = await browser.newPage({ viewport: { width: options.width || 1440, height: options.height || 900 } });
|
|
212
|
+
try {
|
|
213
|
+
await page.goto(target, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 8000 });
|
|
214
|
+
await page.waitForTimeout(options.settleMs ?? 250);
|
|
215
|
+
|
|
216
|
+
const snapshot = await page.evaluate(() => {
|
|
217
|
+
const nameOf = (el) => {
|
|
218
|
+
const aria = el.getAttribute('aria-label')?.trim();
|
|
219
|
+
if (aria) return aria;
|
|
220
|
+
const labelledby = el.getAttribute('aria-labelledby');
|
|
221
|
+
if (labelledby) {
|
|
222
|
+
const text = labelledby.split(/\s+/).map((id) => document.getElementById(id)?.textContent || '').join(' ').trim();
|
|
223
|
+
if (text) return text;
|
|
224
|
+
}
|
|
225
|
+
if (el.tagName === 'IMG') return (el.getAttribute('alt') || '').trim();
|
|
226
|
+
if (el.labels && el.labels.length) {
|
|
227
|
+
const text = [...el.labels].map((label) => (label.innerText || label.textContent || '').trim()).filter(Boolean).join(' ').trim();
|
|
228
|
+
if (text) return text;
|
|
229
|
+
}
|
|
230
|
+
if (el.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes((el.type || '').toLowerCase())) return el.value || '';
|
|
231
|
+
return (el.innerText || el.textContent || '').trim() || (el.getAttribute('title') || '').trim();
|
|
232
|
+
};
|
|
233
|
+
const roleOf = (el) => {
|
|
234
|
+
const explicit = el.getAttribute('role');
|
|
235
|
+
if (explicit) return explicit;
|
|
236
|
+
if (el.tagName === 'BUTTON' || el.tagName === 'SUMMARY') return 'button';
|
|
237
|
+
if (el.tagName === 'A' && el.hasAttribute('href')) return 'link';
|
|
238
|
+
if (el.tagName === 'INPUT') {
|
|
239
|
+
return ({ checkbox: 'checkbox', radio: 'radio', range: 'slider', number: 'spinbutton' })[(el.type || '').toLowerCase()] || 'textbox';
|
|
240
|
+
}
|
|
241
|
+
if (el.tagName === 'SELECT') return 'combobox';
|
|
242
|
+
if (el.tagName === 'TEXTAREA') return 'textbox';
|
|
243
|
+
return '';
|
|
244
|
+
};
|
|
245
|
+
const selectorOf = (el) => {
|
|
246
|
+
if (el.id) return `#${el.id}`;
|
|
247
|
+
const cls = [...el.classList].filter((value) => /^[A-Za-z0-9_-]+$/.test(value)).slice(0, 2);
|
|
248
|
+
return `${el.tagName.toLowerCase()}${cls.map((value) => `.${value}`).join('')}`;
|
|
249
|
+
};
|
|
250
|
+
const items = [];
|
|
251
|
+
const previousFocus = document.activeElement;
|
|
252
|
+
const all = [...document.querySelectorAll('body *')];
|
|
253
|
+
for (const el of all) {
|
|
254
|
+
const style = getComputedStyle(el);
|
|
255
|
+
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) continue;
|
|
256
|
+
const rect = el.getBoundingClientRect();
|
|
257
|
+
if (!rect.width || !rect.height) continue;
|
|
258
|
+
const tag = el.tagName;
|
|
259
|
+
const role = roleOf(el);
|
|
260
|
+
const interactive = ['BUTTON', 'A', 'SUMMARY', 'INPUT', 'SELECT', 'TEXTAREA'].includes(tag) || Boolean(el.getAttribute('role'));
|
|
261
|
+
if (!interactive && !el.hasAttribute('aria-expanded')) continue;
|
|
262
|
+
const type = (el.getAttribute('type') || (tag === 'INPUT' ? 'text' : '') || '').toLowerCase();
|
|
263
|
+
if (tag === 'INPUT' && type === 'hidden') continue;
|
|
264
|
+
const labels = el.labels ? [...el.labels] : [];
|
|
265
|
+
const hasLabel = labels.length > 0 || Boolean(el.getAttribute('aria-label') || el.getAttribute('aria-labelledby') || el.getAttribute('title'));
|
|
266
|
+
const focusable = el.tabIndex >= 0 && !el.disabled;
|
|
267
|
+
let focusVisible;
|
|
268
|
+
if (focusable) {
|
|
269
|
+
try { el.focus({ preventScroll: true }); } catch {}
|
|
270
|
+
const focusedStyle = getComputedStyle(el);
|
|
271
|
+
focusVisible = (focusedStyle.outlineStyle !== 'none' && focusedStyle.outlineWidth !== '0px') || focusedStyle.boxShadow !== 'none';
|
|
272
|
+
}
|
|
273
|
+
items.push({
|
|
274
|
+
tag,
|
|
275
|
+
role,
|
|
276
|
+
name: nameOf(el),
|
|
277
|
+
id: el.id || undefined,
|
|
278
|
+
selector: selectorOf(el),
|
|
279
|
+
type,
|
|
280
|
+
hidden: false,
|
|
281
|
+
disabled: Boolean(el.disabled),
|
|
282
|
+
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
283
|
+
tabIndex: el.tabIndex,
|
|
284
|
+
explicitTabIndex: el.getAttribute('tabindex'),
|
|
285
|
+
inlineLink: tag === 'A' && style.display === 'inline',
|
|
286
|
+
hasLabel,
|
|
287
|
+
focusVisible,
|
|
288
|
+
ariaExpanded: el.getAttribute('aria-expanded'),
|
|
289
|
+
ariaControls: el.getAttribute('aria-controls') || undefined
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (previousFocus && previousFocus !== document.body && typeof previousFocus.focus === 'function') {
|
|
294
|
+
try { previousFocus.focus({ preventScroll: true }); } catch {}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const ids = new Map();
|
|
298
|
+
for (const el of document.querySelectorAll('[id]')) ids.set(el.id, (ids.get(el.id) || 0) + 1);
|
|
299
|
+
const duplicateIds = [...ids.entries()].filter(([, count]) => count > 1).map(([id]) => id);
|
|
300
|
+
|
|
301
|
+
const brokenReferences = [];
|
|
302
|
+
for (const el of document.querySelectorAll('[aria-labelledby], [aria-describedby], [aria-controls], [aria-owns]')) {
|
|
303
|
+
for (const attribute of ['aria-labelledby', 'aria-describedby', 'aria-controls', 'aria-owns']) {
|
|
304
|
+
const value = el.getAttribute(attribute);
|
|
305
|
+
if (!value) continue;
|
|
306
|
+
for (const id of value.split(/\s+/).filter(Boolean)) {
|
|
307
|
+
if (!document.getElementById(id)) brokenReferences.push({ attribute, id, selector: selectorOf(el) });
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return { items, duplicateIds, brokenReferences };
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
let focusOrderJumps = [];
|
|
316
|
+
if (options.checkFocusOrder !== false) {
|
|
317
|
+
await page.evaluate(() => window.scrollTo(0, 0));
|
|
318
|
+
const stops = [];
|
|
319
|
+
for (let index = 0; index < 30; index += 1) {
|
|
320
|
+
await page.keyboard.press('Tab');
|
|
321
|
+
const stop = await page.evaluate(() => {
|
|
322
|
+
const el = document.activeElement;
|
|
323
|
+
if (!el || el === document.body || el === document.documentElement) return null;
|
|
324
|
+
const rect = el.getBoundingClientRect();
|
|
325
|
+
const label = el.getAttribute('aria-label') || (el.innerText || el.textContent || el.tagName).trim().slice(0, 40);
|
|
326
|
+
return {
|
|
327
|
+
selector: el.id ? `#${el.id}` : `${el.tagName.toLowerCase()}${label ? `[${label}]` : ''}`,
|
|
328
|
+
docTop: rect.top + window.scrollY,
|
|
329
|
+
docLeft: rect.left,
|
|
330
|
+
positiveTabindex: Number(el.getAttribute('tabindex')) > 0
|
|
331
|
+
};
|
|
332
|
+
});
|
|
333
|
+
if (stop) stops.push(stop);
|
|
334
|
+
if (stops.length > 2 && stop?.selector === stops[0]?.selector) break;
|
|
335
|
+
}
|
|
336
|
+
focusOrderJumps = analyzeFocusOrder(stops);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const viewport = page.viewportSize();
|
|
340
|
+
let reflowOverflow = null;
|
|
341
|
+
let textResizeClipped = [];
|
|
342
|
+
try {
|
|
343
|
+
await page.setViewportSize({ width: 320, height: 800 });
|
|
344
|
+
await page.waitForTimeout(120);
|
|
345
|
+
const reflow = await page.evaluate(() => ({
|
|
346
|
+
scrollWidth: document.documentElement.scrollWidth,
|
|
347
|
+
clientWidth: document.documentElement.clientWidth
|
|
348
|
+
}));
|
|
349
|
+
if (reflow.scrollWidth > reflow.clientWidth + 1) reflowOverflow = reflow;
|
|
350
|
+
|
|
351
|
+
await page.evaluate(() => { document.documentElement.style.fontSize = '32px'; });
|
|
352
|
+
await page.waitForTimeout(120);
|
|
353
|
+
textResizeClipped = await page.evaluate(() => {
|
|
354
|
+
const clipped = [];
|
|
355
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
356
|
+
const style = getComputedStyle(el);
|
|
357
|
+
if (style.overflow !== 'hidden' && style.overflowY !== 'hidden') continue;
|
|
358
|
+
const text = (el.innerText || el.textContent || '').trim();
|
|
359
|
+
if (!text || el.children.length > 0) continue;
|
|
360
|
+
if (el.scrollHeight > el.clientHeight + 2) {
|
|
361
|
+
const cls = [...el.classList].filter((value) => /^[A-Za-z0-9_-]+$/.test(value)).slice(0, 2);
|
|
362
|
+
clipped.push({ selector: el.id ? `#${el.id}` : `${el.tagName.toLowerCase()}${cls.map((value) => `.${value}`).join('')}`, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight });
|
|
363
|
+
}
|
|
364
|
+
if (clipped.length >= 5) break;
|
|
365
|
+
}
|
|
366
|
+
return clipped;
|
|
367
|
+
});
|
|
368
|
+
await page.evaluate(() => { document.documentElement.style.fontSize = ''; });
|
|
369
|
+
} finally {
|
|
370
|
+
if (viewport) await page.setViewportSize(viewport);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
let reducedMotionIgnored = false;
|
|
374
|
+
if (options.checkReducedMotion !== false) {
|
|
375
|
+
await page.emulateMedia({ reducedMotion: 'reduce' });
|
|
376
|
+
await page.reload({ waitUntil: 'domcontentloaded', timeout: options.timeoutMs || 8000 });
|
|
377
|
+
await page.waitForTimeout(150);
|
|
378
|
+
reducedMotionIgnored = await page.evaluate(() => (document.getAnimations?.() || []).some((animation) => {
|
|
379
|
+
const timing = animation.effect?.getTiming?.();
|
|
380
|
+
return animation.playState === 'running' && timing && timing.iterations === Infinity;
|
|
381
|
+
}));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const findings = auditA11ySnapshot(snapshot.items, {
|
|
385
|
+
duplicateIds: snapshot.duplicateIds,
|
|
386
|
+
brokenReferences: snapshot.brokenReferences,
|
|
387
|
+
focusOrderJumps,
|
|
388
|
+
reflowOverflow,
|
|
389
|
+
textResizeClipped,
|
|
390
|
+
reducedMotionIgnored,
|
|
391
|
+
viewport: { width: options.width || 1440, height: options.height || 900 }
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
target,
|
|
396
|
+
ok: findings.length === 0,
|
|
397
|
+
mode: 'browser',
|
|
398
|
+
isStaticFallback: false,
|
|
399
|
+
findings,
|
|
400
|
+
summary: findings.length
|
|
401
|
+
? `Found ${findings.length} accessibility issue(s) in the rendered DOM.`
|
|
402
|
+
: 'Rendered DOM passes the name, label, focus, target-size, reference, reflow, text-resize, and reduced-motion checks.',
|
|
403
|
+
checked: ['accessible name', 'form labels', 'focus visibility', 'focus order', 'target size 24x24', 'aria references', 'reflow at 320px', '200% text resize', 'reduced motion']
|
|
404
|
+
};
|
|
405
|
+
} catch (error) {
|
|
406
|
+
const reason = String(error?.message || error).split('\n')[0];
|
|
407
|
+
return {
|
|
408
|
+
target,
|
|
409
|
+
ok: false,
|
|
410
|
+
mode: 'browser',
|
|
411
|
+
isStaticFallback: false,
|
|
412
|
+
findings: [],
|
|
413
|
+
summary: `Accessibility audit failed: ${reason}`,
|
|
414
|
+
unavailable: reason
|
|
415
|
+
};
|
|
416
|
+
} finally {
|
|
417
|
+
await page.close();
|
|
418
|
+
await browser.close();
|
|
419
|
+
}
|
|
420
|
+
}
|
package/browser.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Headless browser loader with graceful static fallback detection.
|
|
2
|
+
// playwright-core is optional: when unavailable, Sloppy gracefully falls back
|
|
3
|
+
// to static source-scan multi-width and contrast simulation.
|
|
4
|
+
|
|
5
|
+
export async function tryLaunch() {
|
|
6
|
+
let chromium;
|
|
7
|
+
try {
|
|
8
|
+
;({ chromium } = await import('playwright-core'));
|
|
9
|
+
} catch (err) {
|
|
10
|
+
return { browser: null, reason: 'playwright-core not installed' };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const path = process.env.CHROME_PATH;
|
|
14
|
+
try {
|
|
15
|
+
const browser = await chromium.launch(path ? { executablePath: path } : { channel: 'chrome', headless: true });
|
|
16
|
+
return { browser, reason: null };
|
|
17
|
+
} catch (err) {
|
|
18
|
+
return { browser: null, reason: `Chrome launch failed: ${err?.message || err}` };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function launch() {
|
|
23
|
+
const result = await tryLaunch();
|
|
24
|
+
if (!result.browser) {
|
|
25
|
+
console.error(`[BROWSER LAUNCH FAILED] ${result.reason}`);
|
|
26
|
+
console.error('Install Google Chrome or install playwright-core: `npm i -D playwright-core`');
|
|
27
|
+
process.exit(2);
|
|
28
|
+
}
|
|
29
|
+
return result.browser;
|
|
30
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// PostCSS owns CSS syntax (including nesting, comments, strings and at-rules).
|
|
2
|
+
// This checker compares class namespaces, not the full CSS cascade. Different
|
|
3
|
+
// explicit root scopes and CSS Modules are isolated; an unscoped class overlaps
|
|
4
|
+
// every scope with that class. Composed/overlapping scopes still need review.
|
|
5
|
+
export function splitSelectors(value) {
|
|
6
|
+
const parts = []
|
|
7
|
+
let start = 0, depth = 0, quote = null, escaped = false
|
|
8
|
+
for (let i = 0; i < value.length; i++) {
|
|
9
|
+
const char = value[i]
|
|
10
|
+
if (escaped) { escaped = false; continue }
|
|
11
|
+
if (char === '\\') { escaped = true; continue }
|
|
12
|
+
if (quote) { if (char === quote) quote = null; continue }
|
|
13
|
+
if (char === '"' || char === "'") { quote = char; continue }
|
|
14
|
+
if (char === '(' || char === '[') depth++
|
|
15
|
+
else if (char === ')' || char === ']') depth--
|
|
16
|
+
else if (char === ',' && depth === 0) { parts.push(value.slice(start, i).trim()); start = i + 1 }
|
|
17
|
+
}
|
|
18
|
+
parts.push(value.slice(start).trim())
|
|
19
|
+
return parts.filter(Boolean)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function withoutConditions(selector) {
|
|
23
|
+
// :not() and :has() filter matches; their argument classes are not classes
|
|
24
|
+
// being styled. Ignore those conditions conservatively when finding a root.
|
|
25
|
+
let result = ''
|
|
26
|
+
for (let i = 0; i < selector.length; i++) {
|
|
27
|
+
const match = selector.slice(i).match(/^:(?:not|has)\(/)
|
|
28
|
+
if (!match) { result += selector[i]; continue }
|
|
29
|
+
i += match[0].length
|
|
30
|
+
let depth = 1, quote = null
|
|
31
|
+
for (; i < selector.length && depth; i++) {
|
|
32
|
+
const char = selector[i]
|
|
33
|
+
if (char === '\\') { i++; continue }
|
|
34
|
+
if (quote) { if (char === quote) quote = null; continue }
|
|
35
|
+
if (char === '"' || char === "'") quote = char
|
|
36
|
+
else if (char === '(') depth++
|
|
37
|
+
else if (char === ')') depth--
|
|
38
|
+
}
|
|
39
|
+
i--
|
|
40
|
+
}
|
|
41
|
+
return result
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function unwrapAttributeWhere(selector) {
|
|
45
|
+
// A single plain attribute does not branch. Unwrap it, then let the normal
|
|
46
|
+
// attribute stripping below discard it; attribute values are not exclusive
|
|
47
|
+
// namespace roots. Escapes, compounds and selector lists still need review.
|
|
48
|
+
const simple = /^:where\(\s*(\[\s*-?[_a-zA-Z][\w-]*(?:\s*[~|^$*]?=\s*(?:"[^"\\\[\]]*"|'[^'\\\[\]]*'|-?[_a-zA-Z][\w-]*)(?:\s+[is])?)?\s*\])\s*\)/
|
|
49
|
+
let result = '', attributeDepth = 0, quote = null
|
|
50
|
+
for (let i = 0; i < selector.length; i++) {
|
|
51
|
+
const char = selector[i]
|
|
52
|
+
if (char === '\\') { result += selector.slice(i, i + 2); i++; continue }
|
|
53
|
+
if (quote) { result += char; if (char === quote) quote = null; continue }
|
|
54
|
+
if (char === '"' || char === "'") quote = char
|
|
55
|
+
if (!attributeDepth && char === ':') {
|
|
56
|
+
const match = selector.slice(i).match(simple)
|
|
57
|
+
if (match) { result += match[1]; i += match[0].length - 1; continue }
|
|
58
|
+
}
|
|
59
|
+
if (char === '[') attributeDepth++
|
|
60
|
+
else if (char === ']') attributeDepth--
|
|
61
|
+
result += char
|
|
62
|
+
}
|
|
63
|
+
return result
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function classDefinitions(css, file, parse) {
|
|
67
|
+
const root = parse(css, { from: file })
|
|
68
|
+
const definitions = []
|
|
69
|
+
const manual = []
|
|
70
|
+
const selectorsFor = (node) => {
|
|
71
|
+
if (!node || node.type === 'root') return ['']
|
|
72
|
+
const parents = selectorsFor(node.parent)
|
|
73
|
+
if (node.type === 'rule') {
|
|
74
|
+
return parents.flatMap((parent) => splitSelectors(node.selector).map((selector) => selector.includes('&') ? selector.replaceAll('&', parent || ':root') : `${parent} ${selector}`.trim()))
|
|
75
|
+
}
|
|
76
|
+
if (node.type === 'atrule' && node.name.toLowerCase() === 'scope') {
|
|
77
|
+
const match = node.params.match(/^\s*\(([^()]*)\)/)
|
|
78
|
+
if (!match) { manual.push(`@scope at ${file}:${node.source.start.line} has a complex/implicit root; inspect its isolation`); return parents }
|
|
79
|
+
return parents.flatMap((parent) => splitSelectors(match[1]).map((scope) => `${parent} ${scope}`.trim()))
|
|
80
|
+
}
|
|
81
|
+
return parents
|
|
82
|
+
}
|
|
83
|
+
root.walkRules((rule) => {
|
|
84
|
+
for (let parent = rule.parent; parent; parent = parent.parent) if (parent.type === 'atrule' && /keyframes$/i.test(parent.name)) return
|
|
85
|
+
// A nesting-only block doesn't itself paint a selector.
|
|
86
|
+
if (!rule.nodes.some((node) => node.type === 'decl')) return
|
|
87
|
+
for (const selector of selectorsFor(rule)) {
|
|
88
|
+
const stripped = withoutConditions(unwrapAttributeWhere(selector))
|
|
89
|
+
const branch = stripped.search(/:(?:is|where)\(/)
|
|
90
|
+
const scopedBranch = branch >= 0 && /[.#](-?[_a-zA-Z][\w-]*)/.test(stripped.slice(0, branch))
|
|
91
|
+
if (/\\|:(?:global|local)\(/.test(stripped) || branch >= 0 && !scopedBranch) manual.push(`selector at ${file}:${rule.source.start.line} uses escapes or branching logic without a clear root; inspect namespace overlap: ${selector}`)
|
|
92
|
+
// Quoted attribute values may contain dots that are not classes.
|
|
93
|
+
const structural = stripped.replace(/\[[^\]]*\]/g, '')
|
|
94
|
+
const classes = [...structural.matchAll(/\.(-?[_a-zA-Z][\w-]*)/g)]
|
|
95
|
+
for (let i = 0; i < classes.length; i++) {
|
|
96
|
+
const name = classes[i][1]
|
|
97
|
+
if (name.startsWith('ss-')) continue
|
|
98
|
+
const before = structural.slice(0, classes[i].index)
|
|
99
|
+
const anchor = before.match(/[.#](-?[_a-zA-Z][\w-]*)/)?.[0] || ''
|
|
100
|
+
definitions.push({ name, scope: /\.module\.css$/i.test(file) && !selector.includes(':global(') ? `module:${file}` : anchor, file, line: rule.source.start.line, selector })
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
return { definitions, manual: [...new Set(manual)] }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function findClashes(definitions) {
|
|
108
|
+
const groups = new Map()
|
|
109
|
+
for (const definition of definitions) {
|
|
110
|
+
const list = groups.get(definition.name) || []
|
|
111
|
+
list.push(definition)
|
|
112
|
+
groups.set(definition.name, list)
|
|
113
|
+
}
|
|
114
|
+
const findings = []
|
|
115
|
+
for (const [name, group] of groups) {
|
|
116
|
+
const overlaps = new Map()
|
|
117
|
+
for (let a = 0; a < group.length; a++) for (let b = a + 1; b < group.length; b++) {
|
|
118
|
+
const left = group[a], right = group[b]
|
|
119
|
+
if (left.file === right.file) continue
|
|
120
|
+
// Explicit stylesheet bundles are one component's cascade. They may
|
|
121
|
+
// share selectors internally, but still collide with another bundle.
|
|
122
|
+
if (left.owner && left.owner === right.owner) continue
|
|
123
|
+
if (left.scope.startsWith('module:') || right.scope.startsWith('module:')) continue
|
|
124
|
+
if (left.scope && right.scope && left.scope !== right.scope) continue
|
|
125
|
+
for (const item of [left, right]) overlaps.set(`${item.file}:${item.line}`, item)
|
|
126
|
+
}
|
|
127
|
+
if (overlaps.size) findings.push({ name, definitions: [...overlaps.values()] })
|
|
128
|
+
}
|
|
129
|
+
return findings.sort((a, b) => a.name.localeCompare(b.name))
|
|
130
|
+
}
|
package/class-clash.mjs
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Classes defined by more than one demo's CSS. Two demos on one page that both
|
|
2
|
+
// define .cp-nav restyle each other, and whichever loads last wins.
|
|
3
|
+
//
|
|
4
|
+
// node scripts/class-clash.mjs this repo's examples, showcase and site demos
|
|
5
|
+
// node scripts/class-clash.mjs src/demos a.css any folders or files in your project
|
|
6
|
+
//
|
|
7
|
+
// Checks namespaces, including nested CSS and @scope. It cannot prove that
|
|
8
|
+
// arbitrarily composed roots never overlap; inspect those on the host page.
|
|
9
|
+
import { readFileSync, statSync, readdirSync, existsSync } from 'node:fs'
|
|
10
|
+
import { resolve, join, sep } from 'node:path'
|
|
11
|
+
import { classDefinitions, findClashes } from './class-clash-core.mjs'
|
|
12
|
+
|
|
13
|
+
const args = process.argv.slice(2)
|
|
14
|
+
if (args.includes('--help')) {
|
|
15
|
+
console.log('usage: node scripts/class-clash.mjs [--bundle directory] [directory|file.css ...]\nDefaults to examples/ and teaching/ when present. --bundle declares one component split across multiple stylesheets; collisions with other components are still checked. Requires postcss. Exit: 0 no overlap detected, 1 potential overlaps, 2 incomplete.')
|
|
16
|
+
process.exit(0)
|
|
17
|
+
}
|
|
18
|
+
const find = (path) => {
|
|
19
|
+
if (statSync(path).isFile()) return path.endsWith('.css') ? [resolve(path)] : []
|
|
20
|
+
return readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap((entry) => {
|
|
21
|
+
if (entry.isSymbolicLink() || ['node_modules', '.git', 'dist', '.next'].includes(entry.name)) return []
|
|
22
|
+
const child = join(path, entry.name)
|
|
23
|
+
return entry.isDirectory() ? find(child) : entry.isFile() && entry.name.endsWith('.css') ? [resolve(child)] : []
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const bundles = [], paths = []
|
|
28
|
+
for (let i = 0; i < args.length; i++) {
|
|
29
|
+
if (args[i] === '--bundle') {
|
|
30
|
+
const dir = args[++i]
|
|
31
|
+
if (!dir || dir.startsWith('--') || !statSync(dir).isDirectory()) throw new Error('--bundle needs an existing component directory')
|
|
32
|
+
bundles.push(resolve(dir))
|
|
33
|
+
} else if (args[i].startsWith('--')) throw new Error(`unknown option: ${args[i]}`)
|
|
34
|
+
else paths.push(args[i])
|
|
35
|
+
}
|
|
36
|
+
const { default: postcss } = await import('postcss').catch(() => { throw new Error('PostCSS is missing; install the verification dependencies (npm install -D postcss).') })
|
|
37
|
+
const inputs = paths.length ? paths : ['examples', 'teaching'].filter(existsSync)
|
|
38
|
+
const files = [...new Set(inputs.flatMap(find))]
|
|
39
|
+
if (!files.length) throw new Error('no CSS files found; pass the demo directories to inspect')
|
|
40
|
+
const definitions = [], manual = []
|
|
41
|
+
for (const file of files) {
|
|
42
|
+
const result = classDefinitions(readFileSync(file, 'utf8'), file, postcss.parse)
|
|
43
|
+
const owner = bundles.filter(dir => file.startsWith(`${dir}${sep}`)).sort((a, b) => b.length - a.length)[0]
|
|
44
|
+
definitions.push(...result.definitions.map(definition => ({ ...definition, owner })))
|
|
45
|
+
manual.push(...result.manual)
|
|
46
|
+
}
|
|
47
|
+
const clashes = findClashes(definitions)
|
|
48
|
+
for (const clash of clashes) console.log(`.${clash.name}: ${clash.definitions.map((d) => `${d.file}:${d.line} (${d.selector})`).join(' ')}`)
|
|
49
|
+
for (const line of manual) console.log(`manual: ${line}`)
|
|
50
|
+
console.log(`class clash: ${manual.length ? 'inconclusive' : clashes.length ? 'potential overlaps' : 'no overlapping class namespaces detected'} (${files.length} CSS files, ${bundles.length} explicit bundles); composed scopes need host-page review`)
|
|
51
|
+
process.exitCode = manual.length ? 2 : clashes.length ? 1 : 0
|
|
52
|
+
} catch (error) { console.error(`class clash: incomplete: ${error.message}`); process.exitCode = 2 }
|