@mizchi/vlmkit-core 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -6
- package/package.json +3 -3
- package/src/authored-style-capture.ts +185 -0
- package/src/authored-style-diff.ts +32 -0
- package/src/computed-style-capture.ts +143 -22
- package/src/element-compare.ts +25 -10
- package/src/heatmap-regions.ts +5 -6
- package/src/heatmap.ts +155 -1
- package/src/image-resize.ts +1 -1
- package/src/index.ts +5 -8
- package/src/png-utils.ts +30 -0
- package/src/region-shift.ts +173 -0
- package/src/run-ledger.ts +39 -0
- package/src/text-rows.ts +2 -0
- package/src/types.ts +65 -0
- package/src/a11y-contrast.ts +0 -387
- package/src/a11y-focus-order.ts +0 -397
- package/src/a11y-touch.ts +0 -340
- package/src/grid-ratio.ts +0 -251
- package/src/png-diff.ts +0 -165
- package/src/quality.ts +0 -209
- package/src/region-classify.ts +0 -189
- package/src/shift-origin.ts +0 -204
- package/src/visual-semantic.ts +0 -185
package/src/a11y-touch.ts
DELETED
|
@@ -1,340 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* A11y touch-target check.
|
|
4
|
-
*
|
|
5
|
-
* WCAG 2.1 AAA (criterion 2.5.5) requires interactive elements to have
|
|
6
|
-
* a target size of at least 44 × 44 CSS px. WCAG 2.2 AA (criterion
|
|
7
|
-
* 2.5.8) relaxes this to 24 × 24 with sufficient spacing. Small
|
|
8
|
-
* touch targets are unreachable for users with motor impairments
|
|
9
|
-
* and frustrating on touchscreens.
|
|
10
|
-
*
|
|
11
|
-
* Scans visible interactive elements (button, link, input, select,
|
|
12
|
-
* textarea, [role=button], [role=link], elements with tabindex ≥ 0)
|
|
13
|
-
* and reports those whose bounding box falls below the chosen
|
|
14
|
-
* threshold.
|
|
15
|
-
*
|
|
16
|
-
* Usage:
|
|
17
|
-
* vrt a11y-touch <html-or-url>
|
|
18
|
-
* vrt a11y-touch <url> --level AAA # 44x44 (default)
|
|
19
|
-
* vrt a11y-touch <url> --level AA # 24x24
|
|
20
|
-
*/
|
|
21
|
-
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
|
22
|
-
import { basename, join, resolve } from "node:path";
|
|
23
|
-
import { fileURLToPath } from "node:url";
|
|
24
|
-
import { chromium, type Page } from "playwright";
|
|
25
|
-
import { handleCliError } from "./cli-error.ts";
|
|
26
|
-
import { DIM, RESET, GREEN, RED, BOLD, CYAN } from "./terminal-colors.ts";
|
|
27
|
-
|
|
28
|
-
export type WcagTouchLevel = "AAA" | "AA";
|
|
29
|
-
|
|
30
|
-
export interface TouchCheckOptions {
|
|
31
|
-
/** HTML file path or http(s) URL. */
|
|
32
|
-
source: string;
|
|
33
|
-
outputDir: string;
|
|
34
|
-
reportPath?: string;
|
|
35
|
-
viewport?: { width: number; height: number };
|
|
36
|
-
/** Required size threshold. AAA → 44px, AA → 24px. Default AAA. */
|
|
37
|
-
level?: WcagTouchLevel;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface TouchTargetFinding {
|
|
41
|
-
path: string;
|
|
42
|
-
tag: string;
|
|
43
|
-
text: string;
|
|
44
|
-
bbox: { x: number; y: number; width: number; height: number };
|
|
45
|
-
/** Minimum of width and height — the limiting dimension. */
|
|
46
|
-
minSide: number;
|
|
47
|
-
required: number;
|
|
48
|
-
/** Same selectors with overlapping or near-adjacent bboxes within 24 px. */
|
|
49
|
-
cluster: boolean;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export interface TouchReport {
|
|
53
|
-
source: string;
|
|
54
|
-
level: WcagTouchLevel;
|
|
55
|
-
viewport: { width: number; height: number };
|
|
56
|
-
screenshot: string;
|
|
57
|
-
inspectedCount: number;
|
|
58
|
-
failures: TouchTargetFinding[];
|
|
59
|
-
reportPath: string;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export const A11Y_TOUCH_SAMPLE_SCRIPT = `
|
|
63
|
-
(function a11yTouch() {
|
|
64
|
-
function shortPath(el) {
|
|
65
|
-
const parts = [];
|
|
66
|
-
let cur = el;
|
|
67
|
-
while (cur && cur !== document.body && parts.length < 5) {
|
|
68
|
-
let p = cur.tagName.toLowerCase();
|
|
69
|
-
if (cur.id) p += "#" + cur.id;
|
|
70
|
-
else if (cur.className && typeof cur.className === "string") {
|
|
71
|
-
const cls = cur.className.trim().split(/\\s+/).slice(0, 2).join(".");
|
|
72
|
-
if (cls) p += "." + cls;
|
|
73
|
-
}
|
|
74
|
-
parts.unshift(p);
|
|
75
|
-
cur = cur.parentElement;
|
|
76
|
-
}
|
|
77
|
-
return parts.join(">");
|
|
78
|
-
}
|
|
79
|
-
const selectors = [
|
|
80
|
-
"button",
|
|
81
|
-
"a[href]",
|
|
82
|
-
"input:not([type='hidden'])",
|
|
83
|
-
"select",
|
|
84
|
-
"textarea",
|
|
85
|
-
"summary",
|
|
86
|
-
"[role='button']",
|
|
87
|
-
"[role='link']",
|
|
88
|
-
"[tabindex]:not([tabindex='-1'])",
|
|
89
|
-
].join(",");
|
|
90
|
-
const out = [];
|
|
91
|
-
const seen = new Set();
|
|
92
|
-
for (const el of document.querySelectorAll(selectors)) {
|
|
93
|
-
if (seen.has(el)) continue;
|
|
94
|
-
seen.add(el);
|
|
95
|
-
const cs = getComputedStyle(el);
|
|
96
|
-
if (cs.visibility === "hidden" || cs.display === "none" || parseFloat(cs.opacity) < 0.5) continue;
|
|
97
|
-
if (el.hasAttribute("disabled") || el.getAttribute("aria-hidden") === "true") continue;
|
|
98
|
-
const r = el.getBoundingClientRect();
|
|
99
|
-
if (r.width === 0 || r.height === 0) continue;
|
|
100
|
-
const text = (el.textContent || el.getAttribute("aria-label") || el.getAttribute("title") || "").trim().slice(0, 60);
|
|
101
|
-
out.push({
|
|
102
|
-
path: shortPath(el),
|
|
103
|
-
tag: el.tagName.toLowerCase(),
|
|
104
|
-
text,
|
|
105
|
-
bbox: { x: r.x, y: r.y, width: r.width, height: r.height },
|
|
106
|
-
});
|
|
107
|
-
if (out.length > 400) break;
|
|
108
|
-
}
|
|
109
|
-
return out;
|
|
110
|
-
})()
|
|
111
|
-
`;
|
|
112
|
-
|
|
113
|
-
export interface A11yTouchRawSample {
|
|
114
|
-
path: string;
|
|
115
|
-
tag: string;
|
|
116
|
-
text: string;
|
|
117
|
-
bbox: { x: number; y: number; width: number; height: number };
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* Build the list of touch-target failures from raw samples. Pure
|
|
122
|
-
* post-process so the `vrt diff-pr` CI gate can reuse it on its
|
|
123
|
-
* own Playwright page without spinning up a new browser.
|
|
124
|
-
*/
|
|
125
|
-
export function analyzeA11yTouchSamples(
|
|
126
|
-
samples: A11yTouchRawSample[],
|
|
127
|
-
level: WcagTouchLevel = "AAA",
|
|
128
|
-
): TouchTargetFinding[] {
|
|
129
|
-
const required = level === "AAA" ? 44 : 24;
|
|
130
|
-
const byPath = new Map<string, A11yTouchRawSample>();
|
|
131
|
-
for (const s of samples) if (!byPath.has(s.path)) byPath.set(s.path, s);
|
|
132
|
-
const findings: TouchTargetFinding[] = [];
|
|
133
|
-
const elements = [...byPath.values()];
|
|
134
|
-
for (let i = 0; i < elements.length; i++) {
|
|
135
|
-
const e = elements[i]!;
|
|
136
|
-
const minSide = Math.min(e.bbox.width, e.bbox.height);
|
|
137
|
-
if (minSide >= required) continue;
|
|
138
|
-
let cluster = false;
|
|
139
|
-
for (let j = 0; j < elements.length; j++) {
|
|
140
|
-
if (i === j) continue;
|
|
141
|
-
const o = elements[j]!;
|
|
142
|
-
const cx1 = e.bbox.x + e.bbox.width / 2, cy1 = e.bbox.y + e.bbox.height / 2;
|
|
143
|
-
const cx2 = o.bbox.x + o.bbox.width / 2, cy2 = o.bbox.y + o.bbox.height / 2;
|
|
144
|
-
const dx = cx2 - cx1, dy = cy2 - cy1;
|
|
145
|
-
if (Math.sqrt(dx * dx + dy * dy) < 24) { cluster = true; break; }
|
|
146
|
-
}
|
|
147
|
-
findings.push({
|
|
148
|
-
path: e.path,
|
|
149
|
-
tag: e.tag,
|
|
150
|
-
text: e.text,
|
|
151
|
-
bbox: e.bbox,
|
|
152
|
-
minSide: Math.round(minSide),
|
|
153
|
-
required,
|
|
154
|
-
cluster,
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
findings.sort((a, b) => a.minSide - b.minSide);
|
|
158
|
-
return findings;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function parseArgs(argv: string[]) {
|
|
162
|
-
let outputDir = "";
|
|
163
|
-
let report = "";
|
|
164
|
-
let level: WcagTouchLevel = "AAA";
|
|
165
|
-
const positional: string[] = [];
|
|
166
|
-
for (let i = 0; i < argv.length; i++) {
|
|
167
|
-
const a = argv[i];
|
|
168
|
-
if (a === "--output-dir") outputDir = argv[++i];
|
|
169
|
-
else if (a === "--report") report = argv[++i];
|
|
170
|
-
else if (a === "--level") {
|
|
171
|
-
const v = argv[++i];
|
|
172
|
-
if (v === "AA" || v === "AAA") level = v;
|
|
173
|
-
} else positional.push(a);
|
|
174
|
-
}
|
|
175
|
-
return { positional, outputDir, report, level };
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
function isUrl(s: string): boolean {
|
|
179
|
-
return /^https?:\/\//.test(s);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export async function runA11yTouch(options: TouchCheckOptions): Promise<TouchReport> {
|
|
183
|
-
const outputDir = resolve(options.outputDir);
|
|
184
|
-
await mkdir(outputDir, { recursive: true });
|
|
185
|
-
const viewport = options.viewport ?? { width: 1280, height: 900 };
|
|
186
|
-
const level = options.level ?? "AAA";
|
|
187
|
-
const required = level === "AAA" ? 44 : 24;
|
|
188
|
-
|
|
189
|
-
const browser = await chromium.launch();
|
|
190
|
-
let samples: A11yTouchRawSample[];
|
|
191
|
-
let screenshotPath: string;
|
|
192
|
-
try {
|
|
193
|
-
const page = await browser.newPage({ viewport });
|
|
194
|
-
if (isUrl(options.source)) {
|
|
195
|
-
await page.goto(options.source, { waitUntil: "networkidle", timeout: 30000 });
|
|
196
|
-
} else {
|
|
197
|
-
const html = await readFile(resolve(options.source), "utf-8");
|
|
198
|
-
await page.setContent(html, { waitUntil: "networkidle" });
|
|
199
|
-
}
|
|
200
|
-
await page.addStyleTag({
|
|
201
|
-
content: `*, *::before, *::after { transition: none !important; animation: none !important; }`,
|
|
202
|
-
});
|
|
203
|
-
samples = await page.evaluate(A11Y_TOUCH_SAMPLE_SCRIPT) as A11yTouchRawSample[];
|
|
204
|
-
screenshotPath = join(outputDir, "page.png");
|
|
205
|
-
await page.screenshot({ path: screenshotPath, fullPage: false });
|
|
206
|
-
await page.close();
|
|
207
|
-
} finally {
|
|
208
|
-
await browser.close();
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
// Dedupe by path.
|
|
212
|
-
const byPath = new Map<string, A11yTouchRawSample>();
|
|
213
|
-
for (const s of samples) if (!byPath.has(s.path)) byPath.set(s.path, s);
|
|
214
|
-
|
|
215
|
-
// Cluster detection: if two below-threshold targets are within
|
|
216
|
-
// 24 px center-to-center, the WCAG 2.5.8 AA "with spacing" leniency
|
|
217
|
-
// is forfeited. (Strict-AAA doesn't have the leniency anyway, but
|
|
218
|
-
// we still surface clusters for context.)
|
|
219
|
-
const findings: TouchTargetFinding[] = [];
|
|
220
|
-
const elements = [...byPath.values()];
|
|
221
|
-
for (let i = 0; i < elements.length; i++) {
|
|
222
|
-
const e = elements[i]!;
|
|
223
|
-
const minSide = Math.min(e.bbox.width, e.bbox.height);
|
|
224
|
-
if (minSide >= required) continue;
|
|
225
|
-
let cluster = false;
|
|
226
|
-
for (let j = 0; j < elements.length; j++) {
|
|
227
|
-
if (i === j) continue;
|
|
228
|
-
const o = elements[j]!;
|
|
229
|
-
const cx1 = e.bbox.x + e.bbox.width / 2, cy1 = e.bbox.y + e.bbox.height / 2;
|
|
230
|
-
const cx2 = o.bbox.x + o.bbox.width / 2, cy2 = o.bbox.y + o.bbox.height / 2;
|
|
231
|
-
const dx = cx2 - cx1, dy = cy2 - cy1;
|
|
232
|
-
if (Math.sqrt(dx * dx + dy * dy) < 24) { cluster = true; break; }
|
|
233
|
-
}
|
|
234
|
-
findings.push({
|
|
235
|
-
path: e.path,
|
|
236
|
-
tag: e.tag,
|
|
237
|
-
text: e.text,
|
|
238
|
-
bbox: e.bbox,
|
|
239
|
-
minSide: Math.round(minSide),
|
|
240
|
-
required,
|
|
241
|
-
cluster,
|
|
242
|
-
});
|
|
243
|
-
}
|
|
244
|
-
findings.sort((a, b) => a.minSide - b.minSide);
|
|
245
|
-
|
|
246
|
-
const reportPath = options.reportPath ?? join(outputDir, "report.md");
|
|
247
|
-
const md = renderReport({
|
|
248
|
-
source: options.source,
|
|
249
|
-
level,
|
|
250
|
-
viewport,
|
|
251
|
-
screenshot: screenshotPath,
|
|
252
|
-
inspectedCount: byPath.size,
|
|
253
|
-
failures: findings,
|
|
254
|
-
});
|
|
255
|
-
await writeFile(reportPath, md);
|
|
256
|
-
|
|
257
|
-
console.log(` ${BOLD}${CYAN}vrt a11y-touch${RESET}`);
|
|
258
|
-
console.log(` ${DIM}source: ${options.source} level: WCAG ${level} (${required}×${required} min)${RESET}`);
|
|
259
|
-
console.log(` ${DIM}inspected ${byPath.size} interactive element(s)${RESET}`);
|
|
260
|
-
const icon = findings.length === 0 ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;
|
|
261
|
-
console.log(` ${icon} ${findings.length} undersized target(s)`);
|
|
262
|
-
for (const f of findings.slice(0, 5)) {
|
|
263
|
-
const cl = f.cluster ? " (clustered)" : "";
|
|
264
|
-
console.log(` ${DIM}${f.path} — ${Math.round(f.bbox.width)}×${Math.round(f.bbox.height)}${cl} — "${f.text}"${RESET}`);
|
|
265
|
-
}
|
|
266
|
-
console.log(` ${DIM}report: ${reportPath}${RESET}`);
|
|
267
|
-
|
|
268
|
-
return {
|
|
269
|
-
source: options.source, level, viewport, screenshot: screenshotPath,
|
|
270
|
-
inspectedCount: byPath.size, failures: findings, reportPath,
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
function renderReport(r: Omit<TouchReport, "reportPath">): string {
|
|
275
|
-
const lines: string[] = [];
|
|
276
|
-
lines.push("# A11y touch-target report");
|
|
277
|
-
lines.push("");
|
|
278
|
-
lines.push(`Source: \`${r.source}\``);
|
|
279
|
-
lines.push(`WCAG level: **${r.level}** — requires ${r.level === "AAA" ? "44×44 px" : "24×24 px (with spacing)"} for every interactive element.`);
|
|
280
|
-
lines.push("");
|
|
281
|
-
lines.push(`Inspected **${r.inspectedCount}** interactive element(s). ` +
|
|
282
|
-
`Screenshot: \`${r.screenshot}\``);
|
|
283
|
-
lines.push("");
|
|
284
|
-
if (r.failures.length === 0) {
|
|
285
|
-
lines.push("## All interactive elements meet the size threshold.");
|
|
286
|
-
return lines.join("\n");
|
|
287
|
-
}
|
|
288
|
-
lines.push(`## ${r.failures.length} undersized target(s)`);
|
|
289
|
-
lines.push("");
|
|
290
|
-
lines.push("Targets below the threshold are hard to tap on touchscreens and " +
|
|
291
|
-
"unreachable for users with motor impairments. The `cluster` flag fires " +
|
|
292
|
-
"when another interactive element's center is within 24 px — the WCAG " +
|
|
293
|
-
"AA-with-spacing leniency does not apply.");
|
|
294
|
-
lines.push("");
|
|
295
|
-
lines.push("| Element | Text | Size | Min side | Need | Cluster |");
|
|
296
|
-
lines.push("|---|---|---|---|---|---|");
|
|
297
|
-
for (const f of r.failures.slice(0, 30)) {
|
|
298
|
-
const sz = `${Math.round(f.bbox.width)}×${Math.round(f.bbox.height)}`;
|
|
299
|
-
lines.push(`| \`${f.path}\` | \`${f.text}\` | ${sz} | **${f.minSide}** | ${f.required} | ${f.cluster ? "yes" : "no"} |`);
|
|
300
|
-
}
|
|
301
|
-
if (r.failures.length > 30) lines.push(`| _…${r.failures.length - 30} more_ | | | | | |`);
|
|
302
|
-
lines.push("");
|
|
303
|
-
lines.push("## Suggested next step");
|
|
304
|
-
lines.push("");
|
|
305
|
-
lines.push("1. For each failing row, expand the element's bbox to ≥ " +
|
|
306
|
-
`${r.failures[0]!.required}×${r.failures[0]!.required} px. Common fixes:`);
|
|
307
|
-
lines.push(" - Increase `padding`. A 12px padding on an icon-only button " +
|
|
308
|
-
"grows a 16×16 icon to 40×40 reach-bbox.");
|
|
309
|
-
lines.push(" - Set `min-width` / `min-height` explicitly: " +
|
|
310
|
-
`\`min-width: ${r.failures[0]!.required}px; min-height: ${r.failures[0]!.required}px;\`.`);
|
|
311
|
-
lines.push(" - For inline links, wrap them in a block with hit padding " +
|
|
312
|
-
"and use `display: inline-block`.");
|
|
313
|
-
lines.push("2. Re-run `vrt a11y-touch`. The failure list should empty out.");
|
|
314
|
-
lines.push("");
|
|
315
|
-
return lines.join("\n");
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
async function main(argv = process.argv.slice(2)) {
|
|
319
|
-
if (argv[0] === "--help" || argv[0] === "-h") argv = [];
|
|
320
|
-
const { positional, outputDir, report, level } = parseArgs(argv);
|
|
321
|
-
if (positional.length === 0) {
|
|
322
|
-
console.log("Usage: vrt a11y-touch <html-or-url> [--level AAA|AA] [--output-dir dir]");
|
|
323
|
-
console.log("Options:");
|
|
324
|
-
console.log(" --level AAA|AA WCAG threshold — AAA=44px (default), AA=24px-with-spacing.");
|
|
325
|
-
console.log(" --output-dir <dir> Default: ./test-results/a11y-touch");
|
|
326
|
-
console.log(" --report <path> Markdown report path");
|
|
327
|
-
process.exit(1);
|
|
328
|
-
}
|
|
329
|
-
await runA11yTouch({
|
|
330
|
-
source: positional[0]!,
|
|
331
|
-
outputDir: outputDir || join(process.cwd(), "test-results", "a11y-touch"),
|
|
332
|
-
reportPath: report || undefined,
|
|
333
|
-
level,
|
|
334
|
-
});
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
const isCliEntry = process.env.__VRT_DISPATCHER_LEAF__ === "a11y-touch" || (process.argv[1] ? resolve(process.argv[1]) === fileURLToPath(import.meta.url) : false);
|
|
338
|
-
if (isCliEntry) {
|
|
339
|
-
main().catch(handleCliError);
|
|
340
|
-
}
|
package/src/grid-ratio.ts
DELETED
|
@@ -1,251 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Grid `fr`-ratio inference.
|
|
3
|
-
*
|
|
4
|
-
* Closes the dogfood/eval gap from Subagent C/D: when a grid container's
|
|
5
|
-
* children have different widths between baseline and variant, the
|
|
6
|
-
* agent currently has to compute the implied `fr` ratio by hand
|
|
7
|
-
* (D: "393.172/298.812 = 1.3158 is a weird ratio. I guessed `1.316fr 1fr`
|
|
8
|
-
* but the actual baseline could be `7fr 5fr`.").
|
|
9
|
-
*
|
|
10
|
-
* This module pairs baseline bboxes against variant bboxes, finds
|
|
11
|
-
* parent elements whose direct children have a non-uniform width
|
|
12
|
-
* distribution, computes the implied ratio, and suggests both a
|
|
13
|
-
* decimal-fr representation and a low-integer fraction approximation.
|
|
14
|
-
*
|
|
15
|
-
* Pure module — bboxes are supplied by the caller.
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
import type { BboxElement } from "./shift-origin.ts";
|
|
19
|
-
|
|
20
|
-
export interface GridSuggestion {
|
|
21
|
-
/** Parent path (the grid container's DOM position). */
|
|
22
|
-
parentPath: string;
|
|
23
|
-
parentTag: string;
|
|
24
|
-
baselineClasses: string;
|
|
25
|
-
variantClasses: string;
|
|
26
|
-
viewport: string;
|
|
27
|
-
/** Direct child widths in baseline (document order). */
|
|
28
|
-
baselineWidths: number[];
|
|
29
|
-
/** Direct child widths in variant (document order). */
|
|
30
|
-
variantWidths: number[];
|
|
31
|
-
/** Decimal ratios for baseline relative to the smallest child. */
|
|
32
|
-
baselineRatioDecimal: string;
|
|
33
|
-
/** Decimal ratios for variant relative to the smallest child. */
|
|
34
|
-
variantRatioDecimal: string;
|
|
35
|
-
/** Best integer approximation of the baseline ratio (e.g. "7fr 5fr"). */
|
|
36
|
-
baselineFrSuggestion: string;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export interface FindGridSuggestionsOptions {
|
|
40
|
-
/** Minimum width tolerance (px) below which two children are considered equal-width. */
|
|
41
|
-
equalityTolerance?: number;
|
|
42
|
-
/** Only consider parents with at least this many direct children. */
|
|
43
|
-
minChildren?: number;
|
|
44
|
-
/** Cap on integer-approximation search (try denominators 1..maxFrDenominator). */
|
|
45
|
-
maxFrDenominator?: number;
|
|
46
|
-
/**
|
|
47
|
-
* Minimum max/min ratio for baseline children to count as "non-uniform."
|
|
48
|
-
* Below this, we treat the spread as flexbox subpixel rendering noise
|
|
49
|
-
* (e.g. 3 equal-flex buttons that come out 130/140/143 due to gap rounding).
|
|
50
|
-
* 1.15 ≈ require a 15% width gap before flagging as a grid-ratio candidate.
|
|
51
|
-
*/
|
|
52
|
-
minRatioSpread?: number;
|
|
53
|
-
/**
|
|
54
|
-
* Maximum allowed sum(children-widths) / parent-width. A row-direction
|
|
55
|
-
* grid/flex container should have sum ≈ parent width (the children tile
|
|
56
|
-
* horizontally). When the sum is much larger, the children are
|
|
57
|
-
* column-stacked (each fills 100%) and the per-child width is
|
|
58
|
-
* content-driven, not a grid ratio. Default 1.3.
|
|
59
|
-
*/
|
|
60
|
-
maxSumOverParent?: number;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
const DEFAULT_TOLERANCE = 2; // 2px subpixel slack
|
|
64
|
-
const DEFAULT_MIN_CHILDREN = 2;
|
|
65
|
-
const DEFAULT_MAX_FR_DENOM = 12;
|
|
66
|
-
const DEFAULT_MIN_RATIO_SPREAD = 1.15;
|
|
67
|
-
const DEFAULT_MAX_SUM_OVER_PARENT = 1.3;
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Heuristic: a parent is a "grid candidate" iff:
|
|
71
|
-
* - it has >= minChildren direct children with a bbox
|
|
72
|
-
* - in the baseline, children widths are NOT all equal (the ratio is
|
|
73
|
-
* informative; uniform widths are noise)
|
|
74
|
-
* - the baseline widths differ from the variant widths (else there's
|
|
75
|
-
* nothing to suggest)
|
|
76
|
-
*/
|
|
77
|
-
function pathOf(parent: string, _child: BboxElement): string {
|
|
78
|
-
// `child.path` already encodes parent. Helper exists for clarity.
|
|
79
|
-
return parent;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function findDirectChildren(parent: string, all: BboxElement[]): BboxElement[] {
|
|
83
|
-
if (!parent) return [];
|
|
84
|
-
const prefix = `${parent}>`;
|
|
85
|
-
const out: BboxElement[] = [];
|
|
86
|
-
for (const el of all) {
|
|
87
|
-
if (!el.path.startsWith(prefix)) continue;
|
|
88
|
-
const rest = el.path.slice(prefix.length);
|
|
89
|
-
if (rest.includes(">")) continue; // not a direct child
|
|
90
|
-
out.push(el);
|
|
91
|
-
}
|
|
92
|
-
// Sort by sibling index encoded in `tag[N]` so document order is preserved.
|
|
93
|
-
out.sort((a, b) => {
|
|
94
|
-
const ia = parseInt(a.path.match(/\[(\d+)\]$/)?.[1] ?? "0", 10);
|
|
95
|
-
const ib = parseInt(b.path.match(/\[(\d+)\]$/)?.[1] ?? "0", 10);
|
|
96
|
-
return ia - ib;
|
|
97
|
-
});
|
|
98
|
-
return out;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
function allEqual(widths: number[], tol: number): boolean {
|
|
102
|
-
if (widths.length < 2) return true;
|
|
103
|
-
const min = Math.min(...widths);
|
|
104
|
-
const max = Math.max(...widths);
|
|
105
|
-
return max - min <= tol;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
function arraysClose(a: number[], b: number[], tol: number): boolean {
|
|
109
|
-
if (a.length !== b.length) return false;
|
|
110
|
-
for (let i = 0; i < a.length; i++) {
|
|
111
|
-
if (Math.abs(a[i]! - b[i]!) > tol) return false;
|
|
112
|
-
}
|
|
113
|
-
return true;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Return a "Nfr Mfr" string approximating the ratio of `widths` using
|
|
118
|
-
* small integers, or undefined if no clean integer ratio fits within
|
|
119
|
-
* `maxDenom`. For widths [393, 298] → "7fr 5fr" (since 7/5 ≈ 1.4 vs
|
|
120
|
-
* 393/298 ≈ 1.319 — actually no, 7/5 is too rough. Let's check: closest
|
|
121
|
-
* within 12: 19/14 ≈ 1.357, 4/3 ≈ 1.333, 5/4 = 1.25. None within 2%.
|
|
122
|
-
* Fall through to decimal in that case.
|
|
123
|
-
*/
|
|
124
|
-
function approximateAsIntegerFr(widths: number[], maxDenom: number): string | undefined {
|
|
125
|
-
if (widths.length === 0) return undefined;
|
|
126
|
-
const min = Math.min(...widths);
|
|
127
|
-
if (min <= 0) return undefined;
|
|
128
|
-
const ratios = widths.map((w) => w / min);
|
|
129
|
-
|
|
130
|
-
let best: { denoms: number[]; err: number } | undefined;
|
|
131
|
-
// Iterate over a common denominator: for each candidate denom D, round
|
|
132
|
-
// each ratio*D to nearest integer, check overall error.
|
|
133
|
-
for (let D = 1; D <= maxDenom; D++) {
|
|
134
|
-
const ints = ratios.map((r) => Math.round(r * D));
|
|
135
|
-
if (ints.some((n) => n <= 0)) continue;
|
|
136
|
-
// Compute relative error per child.
|
|
137
|
-
let err = 0;
|
|
138
|
-
for (let i = 0; i < ratios.length; i++) {
|
|
139
|
-
const approxRatio = ints[i]! / D;
|
|
140
|
-
err += Math.abs(approxRatio - ratios[i]!) / ratios[i]!;
|
|
141
|
-
}
|
|
142
|
-
err /= ratios.length;
|
|
143
|
-
if (err < 0.01 && (!best || err < best.err)) {
|
|
144
|
-
// Reduce the gcd so we get the minimum integer form.
|
|
145
|
-
const allInts = [...ints];
|
|
146
|
-
const g = allInts.reduce((acc, n) => gcd(acc, n), allInts[0]!);
|
|
147
|
-
const reduced = allInts.map((n) => n / g);
|
|
148
|
-
best = { denoms: reduced, err };
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
if (!best) return undefined;
|
|
152
|
-
return best.denoms.map((n) => `${n}fr`).join(" ");
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
function gcd(a: number, b: number): number {
|
|
156
|
-
return b === 0 ? a : gcd(b, a % b);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
function ratiosToDecimal(widths: number[]): string {
|
|
160
|
-
if (widths.length === 0) return "";
|
|
161
|
-
const min = Math.min(...widths);
|
|
162
|
-
if (min <= 0) return widths.join(" : ");
|
|
163
|
-
return widths.map((w) => (w / min).toFixed(3)).join(" : ");
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/**
|
|
167
|
-
* Walk baseline bboxes and find every parent whose direct children have
|
|
168
|
-
* a *non-uniform* width distribution that *differs* from the variant.
|
|
169
|
-
* One suggestion per parent per viewport.
|
|
170
|
-
*/
|
|
171
|
-
export function findGridSuggestions(
|
|
172
|
-
baseline: BboxElement[],
|
|
173
|
-
variant: BboxElement[],
|
|
174
|
-
viewport: string,
|
|
175
|
-
options: FindGridSuggestionsOptions = {},
|
|
176
|
-
): GridSuggestion[] {
|
|
177
|
-
const tol = options.equalityTolerance ?? DEFAULT_TOLERANCE;
|
|
178
|
-
const minChildren = options.minChildren ?? DEFAULT_MIN_CHILDREN;
|
|
179
|
-
const maxDenom = options.maxFrDenominator ?? DEFAULT_MAX_FR_DENOM;
|
|
180
|
-
const minSpread = options.minRatioSpread ?? DEFAULT_MIN_RATIO_SPREAD;
|
|
181
|
-
const maxSumOverParent = options.maxSumOverParent ?? DEFAULT_MAX_SUM_OVER_PARENT;
|
|
182
|
-
|
|
183
|
-
if (baseline.length === 0 || variant.length === 0) return [];
|
|
184
|
-
|
|
185
|
-
const variantByPath = new Map<string, BboxElement>();
|
|
186
|
-
for (const v of variant) variantByPath.set(v.path, v);
|
|
187
|
-
|
|
188
|
-
// Distinct parent paths derived from baseline (each child's path's
|
|
189
|
-
// prefix-up-to-last-`>`).
|
|
190
|
-
const parentPaths = new Set<string>();
|
|
191
|
-
for (const b of baseline) {
|
|
192
|
-
const lastGt = b.path.lastIndexOf(">");
|
|
193
|
-
if (lastGt > 0) parentPaths.add(b.path.slice(0, lastGt));
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
const out: GridSuggestion[] = [];
|
|
197
|
-
for (const parent of parentPaths) {
|
|
198
|
-
const baselineChildren = findDirectChildren(parent, baseline);
|
|
199
|
-
if (baselineChildren.length < minChildren) continue;
|
|
200
|
-
const baselineWidths = baselineChildren.map((c) => Math.round(c.width * 100) / 100);
|
|
201
|
-
if (allEqual(baselineWidths, tol)) continue;
|
|
202
|
-
// Reject flexbox subpixel-rendering noise: require a meaningful spread
|
|
203
|
-
// before we believe the baseline truly has a `grid-template-columns`
|
|
204
|
-
// (or similar) ratio worth suggesting.
|
|
205
|
-
const minW = Math.min(...baselineWidths);
|
|
206
|
-
const maxW = Math.max(...baselineWidths);
|
|
207
|
-
if (minW <= 0 || maxW / minW < minSpread) continue;
|
|
208
|
-
|
|
209
|
-
// Reject column-stacked containers (flex-direction: column or block
|
|
210
|
-
// siblings). Their children fill 100% width and any per-child width
|
|
211
|
-
// differences are content-sized, not from a grid-template-columns
|
|
212
|
-
// rule. Heuristic: sum(children) ≫ parent.width.
|
|
213
|
-
const parentBboxForCheck = baseline.find((b) => b.path === parent);
|
|
214
|
-
if (parentBboxForCheck && parentBboxForCheck.width > 0) {
|
|
215
|
-
const sum = baselineWidths.reduce((a, b) => a + b, 0);
|
|
216
|
-
if (sum / parentBboxForCheck.width > maxSumOverParent) continue;
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
const variantChildren = baselineChildren
|
|
220
|
-
.map((bc) => variantByPath.get(bc.path))
|
|
221
|
-
.filter((v): v is BboxElement => v !== undefined);
|
|
222
|
-
if (variantChildren.length !== baselineChildren.length) continue;
|
|
223
|
-
const variantWidths = variantChildren.map((c) => Math.round(c.width * 100) / 100);
|
|
224
|
-
if (arraysClose(baselineWidths, variantWidths, tol)) continue;
|
|
225
|
-
|
|
226
|
-
const parentBaseline = baseline.find((b) => b.path === parent);
|
|
227
|
-
const parentVariant = variantByPath.get(parent);
|
|
228
|
-
out.push({
|
|
229
|
-
parentPath: pathOf(parent, baselineChildren[0]!),
|
|
230
|
-
parentTag: parentBaseline?.tag ?? "",
|
|
231
|
-
baselineClasses: parentBaseline?.classes ?? "",
|
|
232
|
-
variantClasses: parentVariant?.classes ?? "",
|
|
233
|
-
viewport,
|
|
234
|
-
baselineWidths,
|
|
235
|
-
variantWidths,
|
|
236
|
-
baselineRatioDecimal: ratiosToDecimal(baselineWidths),
|
|
237
|
-
variantRatioDecimal: ratiosToDecimal(variantWidths),
|
|
238
|
-
baselineFrSuggestion: approximateAsIntegerFr(baselineWidths, maxDenom)
|
|
239
|
-
?? baselineWidths.map((w, i, arr) => `${(w / Math.min(...arr)).toFixed(3)}fr`).join(" "),
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// Sort by ratio mismatch magnitude (largest first).
|
|
244
|
-
out.sort((a, b) => {
|
|
245
|
-
const aGap = a.baselineWidths.reduce((s, w, i) => s + Math.abs(w - a.variantWidths[i]!), 0);
|
|
246
|
-
const bGap = b.baselineWidths.reduce((s, w, i) => s + Math.abs(w - b.variantWidths[i]!), 0);
|
|
247
|
-
return bGap - aGap;
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
return out;
|
|
251
|
-
}
|