@mizchi/vlmkit-core 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,397 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * A11y focus-order check.
4
+ *
5
+ * Drives `Tab` through the page and records the focused element at
6
+ * each step. Detects two classes of bug:
7
+ *
8
+ * 1. **Visual mismatch** — focus jumps around the page instead of
9
+ * reading top-to-bottom, left-to-right. Common cause: rearranging
10
+ * elements with `order:` (flexbox), `grid-area`, or `position`
11
+ * without setting matching `tabindex`. Keyboard users get
12
+ * disoriented.
13
+ *
14
+ * 2. **Trap or skipped** — `Tab` lands on the same element twice in
15
+ * a row (focus trap) or skips an element with `tabindex="-1"`
16
+ * that should be reachable (e.g., custom button without
17
+ * `role="button"` + `tabindex="0"`).
18
+ *
19
+ * Pairs well with `vrt a11y-touch` (size) and `vrt a11y-contrast`
20
+ * (contrast) — those check static rendering, this checks the
21
+ * keyboard journey.
22
+ *
23
+ * Usage:
24
+ * vrt a11y-focus-order <html-or-url>
25
+ */
26
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
27
+ import { join, resolve } from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+ import { chromium, type Page } from "playwright";
30
+ import { handleCliError } from "./cli-error.ts";
31
+ import { DIM, RESET, GREEN, RED, YELLOW, BOLD, CYAN } from "./terminal-colors.ts";
32
+
33
+ export interface FocusOrderOptions {
34
+ source: string;
35
+ outputDir: string;
36
+ reportPath?: string;
37
+ viewport?: { width: number; height: number };
38
+ /** Maximum Tab presses (avoids infinite focus loops). Default 64. */
39
+ maxSteps?: number;
40
+ }
41
+
42
+ export interface FocusStep {
43
+ tabIndex: number;
44
+ path: string;
45
+ tag: string;
46
+ text: string;
47
+ bbox: { x: number; y: number; width: number; height: number };
48
+ /** Author `tabindex` attribute value (null = unset / default). */
49
+ tabindexAttr: string | null;
50
+ }
51
+
52
+ export interface FocusOrderFinding {
53
+ /** "trap" = same element focused twice in a row. */
54
+ /** "reverse" = focus moved backward (negative Δy or Δx in same row). */
55
+ /** "skip-row" = focus skipped down by > 1 visual row at a time. */
56
+ kind: "trap" | "reverse" | "skip-row";
57
+ fromIndex: number;
58
+ toIndex: number;
59
+ message: string;
60
+ }
61
+
62
+ export interface FocusOrderReport {
63
+ source: string;
64
+ viewport: { width: number; height: number };
65
+ screenshot: string;
66
+ steps: FocusStep[];
67
+ findings: FocusOrderFinding[];
68
+ reportPath: string;
69
+ }
70
+
71
+ function isUrl(s: string): boolean { return /^https?:\/\//.test(s); }
72
+
73
+ function parseArgs(argv: string[]) {
74
+ let outputDir = "";
75
+ let report = "";
76
+ let maxSteps = 64;
77
+ const positional: string[] = [];
78
+ for (let i = 0; i < argv.length; i++) {
79
+ const a = argv[i];
80
+ if (a === "--output-dir") outputDir = argv[++i];
81
+ else if (a === "--report") report = argv[++i];
82
+ else if (a === "--max-steps") maxSteps = parseInt(argv[++i] ?? "64", 10);
83
+ else positional.push(a);
84
+ }
85
+ return { positional, outputDir, report, maxSteps };
86
+ }
87
+
88
+ export const A11Y_FOCUS_ORDER_SAMPLE_SCRIPT = `
89
+ (function focused() {
90
+ const el = document.activeElement;
91
+ if (!el || el === document.body || el === document.documentElement) return null;
92
+ function shortPath(el) {
93
+ const parts = [];
94
+ let cur = el;
95
+ while (cur && cur !== document.body && parts.length < 5) {
96
+ let p = cur.tagName.toLowerCase();
97
+ if (cur.id) p += "#" + cur.id;
98
+ else if (cur.className && typeof cur.className === "string") {
99
+ const cls = cur.className.trim().split(/\\s+/).slice(0, 2).join(".");
100
+ if (cls) p += "." + cls;
101
+ }
102
+ parts.unshift(p);
103
+ cur = cur.parentElement;
104
+ }
105
+ return parts.join(">");
106
+ }
107
+ const r = el.getBoundingClientRect();
108
+ const text = (el.textContent || el.getAttribute("aria-label") || el.getAttribute("title") || el.getAttribute("placeholder") || "").trim().slice(0, 60);
109
+ return {
110
+ path: shortPath(el),
111
+ tag: el.tagName.toLowerCase(),
112
+ text,
113
+ bbox: { x: r.x, y: r.y, width: r.width, height: r.height },
114
+ tabindexAttr: el.getAttribute("tabindex"),
115
+ };
116
+ })()
117
+ `;
118
+
119
+ /**
120
+ * Walk Tab focus on an already-navigated Playwright Page and return
121
+ * the focus sequence. Pulled out of `runFocusOrder` so `vrt diff-pr`
122
+ * can reuse it without launching a second browser. The page is left
123
+ * in whatever focus state Tab ended in — callers that need the
124
+ * pristine page should clone it first.
125
+ */
126
+ export async function collectFocusStepsOnPage(
127
+ page: Page,
128
+ maxSteps = 64,
129
+ ): Promise<FocusStep[]> {
130
+ const steps: FocusStep[] = [];
131
+ let firstFingerprint: string | null = null;
132
+ for (let i = 0; i < maxSteps; i++) {
133
+ await page.keyboard.press("Tab");
134
+ const sample = await page.evaluate(A11Y_FOCUS_ORDER_SAMPLE_SCRIPT) as Omit<FocusStep, "tabIndex"> | null;
135
+ if (!sample) break;
136
+ // Cycle detection: path + bbox together. Path alone aliases
137
+ // sibling elements (3 buttons all serialize to "button"), which
138
+ // would false-cycle on the first sibling jump. Bbox makes the
139
+ // fingerprint position-aware.
140
+ const fp = `${sample.path}@${sample.bbox.x.toFixed(0)},${sample.bbox.y.toFixed(0)}`;
141
+ if (firstFingerprint === null) firstFingerprint = fp;
142
+ else if (fp === firstFingerprint && i > 0) break;
143
+ steps.push({ tabIndex: i, ...sample });
144
+ }
145
+ return steps;
146
+ }
147
+
148
+ /**
149
+ * Detect focus-order findings from a captured step sequence. Pure
150
+ * post-process — extracted from `runFocusOrder`. Heuristics are
151
+ * deliberately conservative (24 px / 40 px / 16 px thresholds) to
152
+ * avoid false positives on normal layouts. See the comments inside
153
+ * `runFocusOrder` for the rationale.
154
+ */
155
+ export function analyzeFocusOrderSteps(steps: FocusStep[]): FocusOrderFinding[] {
156
+ const findings: FocusOrderFinding[] = [];
157
+ for (let i = 1; i < steps.length; i++) {
158
+ const prev = steps[i - 1]!;
159
+ const cur = steps[i]!;
160
+ const samePath = prev.path === cur.path;
161
+ const sameBbox = Math.abs(prev.bbox.x - cur.bbox.x) < 4
162
+ && Math.abs(prev.bbox.y - cur.bbox.y) < 4;
163
+ if (samePath && sameBbox) {
164
+ findings.push({
165
+ kind: "trap",
166
+ fromIndex: i - 1, toIndex: i,
167
+ message: `Focus stayed on the same element (\`${cur.path}\`) across two Tab presses.`,
168
+ });
169
+ continue;
170
+ }
171
+ const dy = cur.bbox.y - prev.bbox.y;
172
+ const dx = cur.bbox.x - prev.bbox.x;
173
+ const sameRow = Math.abs(dy) <= 16;
174
+ if (sameRow && dx < -40) {
175
+ findings.push({
176
+ kind: "reverse",
177
+ fromIndex: i - 1, toIndex: i,
178
+ message: `Focus moved left within the same row (from \`${prev.path}\` at x=${prev.bbox.x.toFixed(0)} to \`${cur.path}\` at x=${cur.bbox.x.toFixed(0)}). Visual order is L-to-R; check \`tabindex\` or DOM order.`,
179
+ });
180
+ } else if (dy < -24) {
181
+ findings.push({
182
+ kind: "reverse",
183
+ fromIndex: i - 1, toIndex: i,
184
+ message: `Focus moved up by ${(-dy).toFixed(0)}px (from \`${prev.path}\` at y=${prev.bbox.y.toFixed(0)} to \`${cur.path}\` at y=${cur.bbox.y.toFixed(0)}). Visual order is top-to-bottom; check \`tabindex\` or DOM order.`,
185
+ });
186
+ } else if (dy > 200) {
187
+ findings.push({
188
+ kind: "skip-row",
189
+ fromIndex: i - 1, toIndex: i,
190
+ message: `Focus jumped down by ${dy.toFixed(0)}px (from \`${prev.path}\` to \`${cur.path}\`). Confirm no focusable element was unintentionally skipped.`,
191
+ });
192
+ }
193
+ }
194
+ return findings;
195
+ }
196
+
197
+ export async function runFocusOrder(
198
+ options: FocusOrderOptions,
199
+ ): Promise<FocusOrderReport> {
200
+ const outputDir = resolve(options.outputDir);
201
+ await mkdir(outputDir, { recursive: true });
202
+ const viewport = options.viewport ?? { width: 1280, height: 720 };
203
+ const maxSteps = options.maxSteps ?? 64;
204
+ const html = isUrl(options.source) ? null : await readFile(resolve(options.source), "utf-8");
205
+
206
+ const steps: FocusStep[] = [];
207
+ let screenshotPath: string;
208
+ const browser = await chromium.launch();
209
+ try {
210
+ const page = await browser.newPage({ viewport });
211
+ if (isUrl(options.source)) {
212
+ await page.goto(options.source, { waitUntil: "networkidle", timeout: 30000 });
213
+ } else {
214
+ await page.setContent(html!, { waitUntil: "networkidle" });
215
+ }
216
+ await page.addStyleTag({
217
+ content: `*, *::before, *::after { transition: none !important; animation: none !important; }`,
218
+ });
219
+ screenshotPath = join(outputDir, "page.png");
220
+ await page.screenshot({ path: screenshotPath, fullPage: false });
221
+
222
+ // Start from the document. The first Tab moves focus to the
223
+ // earliest focusable element. We capture activeElement after
224
+ // each press until either the focus cycles back to the first
225
+ // element or we hit `maxSteps`.
226
+ let firstPath: string | null = null;
227
+ for (let i = 0; i < maxSteps; i++) {
228
+ await page.keyboard.press("Tab");
229
+ const sample = await page.evaluate(A11Y_FOCUS_ORDER_SAMPLE_SCRIPT) as Omit<FocusStep, "tabIndex"> | null;
230
+ if (!sample) break;
231
+ if (firstPath === null) firstPath = sample.path;
232
+ else if (sample.path === firstPath && i > 0) break; // cycled
233
+ steps.push({ tabIndex: i, ...sample });
234
+ }
235
+ await page.close();
236
+ } finally {
237
+ await browser.close();
238
+ }
239
+
240
+ // Detect findings:
241
+ // trap — same element twice in a row
242
+ // reverse — y moved up by > 4px, or x moved left by > 40px on
243
+ // the same row (similar y, within ±16px). Out-of-DOM
244
+ // order on the visual page.
245
+ // skip-row — y jumped > 200px without intermediate stops on rows
246
+ // in between. (Heuristic; large jumps are sometimes
247
+ // legitimate, e.g. jumping past a paragraph.)
248
+ const findings: FocusOrderFinding[] = [];
249
+ for (let i = 1; i < steps.length; i++) {
250
+ const prev = steps[i - 1]!;
251
+ const cur = steps[i]!;
252
+ // Trap = same path AND overlapping bbox. Sibling elements with
253
+ // identical class/tag (the path generator can't distinguish them
254
+ // without nth-of-type) would otherwise false-positive.
255
+ const samePath = prev.path === cur.path;
256
+ const sameBbox = Math.abs(prev.bbox.x - cur.bbox.x) < 4
257
+ && Math.abs(prev.bbox.y - cur.bbox.y) < 4;
258
+ if (samePath && sameBbox) {
259
+ findings.push({
260
+ kind: "trap",
261
+ fromIndex: i - 1, toIndex: i,
262
+ message: `Focus stayed on the same element (\`${cur.path}\`) across two Tab presses.`,
263
+ });
264
+ continue;
265
+ }
266
+ if (samePath && !sameBbox) {
267
+ // Two siblings with identical class/tag — not a trap, just
268
+ // path-generator ambiguity. Continue with visual checks below.
269
+ }
270
+ const dy = cur.bbox.y - prev.bbox.y;
271
+ const dx = cur.bbox.x - prev.bbox.x;
272
+ const sameRow = Math.abs(dy) <= 16;
273
+ if (sameRow && dx < -40) {
274
+ findings.push({
275
+ kind: "reverse",
276
+ fromIndex: i - 1, toIndex: i,
277
+ message: `Focus moved left within the same row (from \`${prev.path}\` at x=${prev.bbox.x.toFixed(0)} to \`${cur.path}\` at x=${cur.bbox.x.toFixed(0)}). Visual order is L-to-R; check \`tabindex\` or DOM order.`,
278
+ });
279
+ } else if (dy < -24) {
280
+ // 24 px is approximately one button-row height — anything less
281
+ // is the inline-text vs button-row bbox.y delta and would
282
+ // false-positive on normal layouts. Subagent dogfood validated
283
+ // this threshold needs to be conservative.
284
+ findings.push({
285
+ kind: "reverse",
286
+ fromIndex: i - 1, toIndex: i,
287
+ message: `Focus moved up the page (from y=${prev.bbox.y.toFixed(0)} to y=${cur.bbox.y.toFixed(0)}, Δ ${dy.toFixed(0)}px). Visual order is T-to-B; reorder DOM or remove \`tabindex\` overrides.`,
288
+ });
289
+ } else if (dy > 200) {
290
+ // Only flag if there are other interactive elements in between
291
+ // — checking inside the report would require capturing the
292
+ // full element list. For now, surface as a heuristic.
293
+ findings.push({
294
+ kind: "skip-row",
295
+ fromIndex: i - 1, toIndex: i,
296
+ message: `Focus jumped from y=${prev.bbox.y.toFixed(0)} to y=${cur.bbox.y.toFixed(0)} (Δ ${dy.toFixed(0)}px) — verify no focusable elements were skipped between.`,
297
+ });
298
+ }
299
+ }
300
+
301
+ const reportPath = options.reportPath ?? join(outputDir, "report.md");
302
+ const md = renderReport({
303
+ source: options.source, viewport, screenshot: screenshotPath, steps, findings,
304
+ });
305
+ await writeFile(reportPath, md);
306
+
307
+ console.log(` ${BOLD}${CYAN}vrt a11y-focus-order${RESET}`);
308
+ console.log(` ${DIM}source: ${options.source}${RESET}`);
309
+ console.log(` ${DIM}captured ${steps.length} focus step(s)${RESET}`);
310
+ const icon = findings.length === 0 ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;
311
+ console.log(` ${icon} ${findings.length} finding(s)`);
312
+ for (const f of findings.slice(0, 5)) {
313
+ console.log(` ${DIM}[${f.kind}] ${f.message}${RESET}`);
314
+ }
315
+ console.log(` ${DIM}report: ${reportPath}${RESET}`);
316
+
317
+ return {
318
+ source: options.source, viewport, screenshot: screenshotPath,
319
+ steps, findings, reportPath,
320
+ };
321
+ }
322
+
323
+ function renderReport(r: Omit<FocusOrderReport, "reportPath">): string {
324
+ const lines: string[] = [];
325
+ lines.push("# A11y focus-order report");
326
+ lines.push("");
327
+ lines.push(`Source: \`${r.source}\` at ${r.viewport.width}×${r.viewport.height}`);
328
+ lines.push("");
329
+ lines.push(`Captured **${r.steps.length}** focus step(s) by pressing \`Tab\` until focus cycled or step limit hit.`);
330
+ lines.push("");
331
+ lines.push("## Focus sequence");
332
+ lines.push("");
333
+ lines.push("| # | Element | Text | Position (x,y) | tabindex |");
334
+ lines.push("|---|---|---|---|---|");
335
+ for (const s of r.steps) {
336
+ const idx = s.tabindexAttr === null ? "—" : `\`${s.tabindexAttr}\``;
337
+ lines.push(`| ${s.tabIndex} | \`${s.path}\` | \`${s.text}\` | ${s.bbox.x.toFixed(0)}, ${s.bbox.y.toFixed(0)} | ${idx} |`);
338
+ }
339
+ lines.push("");
340
+
341
+ if (r.findings.length === 0) {
342
+ lines.push("## ✓ No focus-order issues detected");
343
+ lines.push("");
344
+ lines.push("Focus order matches visual order (top-to-bottom, left-to-right within rows). " +
345
+ "No focus traps or large unexplained jumps.");
346
+ } else {
347
+ lines.push(`## ${r.findings.length} finding(s)`);
348
+ lines.push("");
349
+ for (const f of r.findings) {
350
+ const from = r.steps[f.fromIndex];
351
+ const to = r.steps[f.toIndex];
352
+ lines.push(`- **${f.kind}** (step ${f.fromIndex} → ${f.toIndex}): ${f.message}`);
353
+ if (from && to) {
354
+ lines.push(` - from: \`${from.path}\` at (${from.bbox.x.toFixed(0)}, ${from.bbox.y.toFixed(0)})`);
355
+ lines.push(` - to: \`${to.path}\` at (${to.bbox.x.toFixed(0)}, ${to.bbox.y.toFixed(0)})`);
356
+ }
357
+ }
358
+ lines.push("");
359
+ lines.push("## Suggested next step");
360
+ lines.push("");
361
+ lines.push("1. Open the page and step through with `Tab` manually to confirm the report.");
362
+ lines.push("2. For `reverse` findings: check if the divergent element has an explicit " +
363
+ "`tabindex` that overrides DOM order. If so, either remove the `tabindex` or " +
364
+ "reorder the DOM.");
365
+ lines.push("3. For `trap` findings: a custom widget likely captured focus and didn't " +
366
+ "release. Check `onkeydown` handlers or roving-`tabindex` patterns.");
367
+ lines.push("4. For `skip-row` findings: large vertical jumps are sometimes intentional " +
368
+ "(skipping a paragraph between two buttons). Verify the skipped region has no " +
369
+ "intended focusable elements.");
370
+ }
371
+ lines.push("");
372
+ return lines.join("\n");
373
+ }
374
+
375
+ async function main(argv = process.argv.slice(2)) {
376
+ if (argv[0] === "--help" || argv[0] === "-h") argv = [];
377
+ const { positional, outputDir, report, maxSteps } = parseArgs(argv);
378
+ if (positional.length === 0) {
379
+ console.log("Usage: vrt a11y-focus-order <html-or-url> [options]");
380
+ console.log("Options:");
381
+ console.log(" --max-steps N Maximum Tab presses (default: 64)");
382
+ console.log(" --output-dir <dir> Default: ./test-results/a11y-focus-order");
383
+ console.log(" --report <path> Markdown report path");
384
+ process.exit(1);
385
+ }
386
+ await runFocusOrder({
387
+ source: positional[0]!,
388
+ outputDir: outputDir || join(process.cwd(), "test-results", "a11y-focus-order"),
389
+ reportPath: report || undefined,
390
+ maxSteps,
391
+ });
392
+ }
393
+
394
+ const isCliEntry = process.env.__VRT_DISPATCHER_LEAF__ === "a11y-focus-order" || (process.argv[1] ? resolve(process.argv[1]) === fileURLToPath(import.meta.url) : false);
395
+ if (isCliEntry) {
396
+ main().catch(handleCliError);
397
+ }