@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.
- package/LICENSE +21 -0
- package/README.md +38 -0
- package/package.json +35 -0
- package/src/a11y-contrast.ts +387 -0
- package/src/a11y-focus-order.ts +397 -0
- package/src/a11y-semantic.ts +384 -0
- package/src/a11y-touch.ts +340 -0
- package/src/cli-args.ts +29 -0
- package/src/cli-error.ts +85 -0
- package/src/computed-style-capture.ts +596 -0
- package/src/computed-style-diff.ts +192 -0
- package/src/diff-regions.ts +70 -0
- package/src/dom-equivalence.ts +158 -0
- package/src/dom-position-styles.ts +457 -0
- package/src/element-compare.ts +339 -0
- package/src/grid-ratio.ts +251 -0
- package/src/heatmap-regions.ts +246 -0
- package/src/heatmap.ts +516 -0
- package/src/image-resize.ts +112 -0
- package/src/index.ts +108 -0
- package/src/mask.ts +41 -0
- package/src/png-diff.ts +165 -0
- package/src/png-utils.ts +56 -0
- package/src/quality.ts +209 -0
- package/src/region-classify.ts +189 -0
- package/src/shift-origin.ts +204 -0
- package/src/terminal-colors.ts +13 -0
- package/src/text-rows.ts +410 -0
- package/src/types.ts +468 -0
- package/src/visual-semantic.ts +185 -0
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Element-level VRT comparison
|
|
4
|
+
*
|
|
5
|
+
* Instead of full-page pixel diff (which cascades when a header shifts),
|
|
6
|
+
* compares individual DOM elements independently via locator.screenshot().
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* vrt elements --url http://localhost:3000/ --current-url http://localhost:8080/ \
|
|
10
|
+
* --selectors "header,main,footer"
|
|
11
|
+
* vrt elements before.html after.html --selectors "header,.content,.sidebar"
|
|
12
|
+
*/
|
|
13
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
14
|
+
import { join, resolve } from "node:path";
|
|
15
|
+
import { chromium, type Page } from "playwright";
|
|
16
|
+
import { compareScreenshots } from "./heatmap.ts";
|
|
17
|
+
import { applyMask, parseMaskSelectors } from "./mask.ts";
|
|
18
|
+
import { DIM, RESET, GREEN, RED, YELLOW, CYAN, BOLD, hr } from "./terminal-colors.ts";
|
|
19
|
+
import type { VrtSnapshot } from "./types.ts";
|
|
20
|
+
|
|
21
|
+
// ---- Types ----
|
|
22
|
+
|
|
23
|
+
export interface ElementCompareOptions {
|
|
24
|
+
/** CSS selectors for elements to compare */
|
|
25
|
+
selectors: string[];
|
|
26
|
+
/** Baseline HTML file path */
|
|
27
|
+
baselineFile?: string;
|
|
28
|
+
/** Current HTML file path */
|
|
29
|
+
currentFile?: string;
|
|
30
|
+
/** Baseline URL */
|
|
31
|
+
baselineUrl?: string;
|
|
32
|
+
/** Current URL */
|
|
33
|
+
currentUrl?: string;
|
|
34
|
+
/** Viewport width/height */
|
|
35
|
+
viewport?: { width: number; height: number };
|
|
36
|
+
/** Output directory */
|
|
37
|
+
outputDir: string;
|
|
38
|
+
/** Selectors to mask before screenshot */
|
|
39
|
+
maskSelectors?: string[];
|
|
40
|
+
/** pixelmatch threshold */
|
|
41
|
+
threshold?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ElementDiffResult {
|
|
45
|
+
selector: string;
|
|
46
|
+
found: { baseline: boolean; current: boolean };
|
|
47
|
+
/** Bounding box of the element in baseline */
|
|
48
|
+
baselineBBox?: { x: number; y: number; width: number; height: number };
|
|
49
|
+
/** Bounding box of the element in current */
|
|
50
|
+
currentBBox?: { x: number; y: number; width: number; height: number };
|
|
51
|
+
diffPixels: number;
|
|
52
|
+
totalPixels: number;
|
|
53
|
+
diffRatio: number;
|
|
54
|
+
heatmapPath?: string;
|
|
55
|
+
baselinePath?: string;
|
|
56
|
+
currentPath?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ElementCompareReport {
|
|
60
|
+
baselineSource: string;
|
|
61
|
+
currentSource: string;
|
|
62
|
+
viewport: { width: number; height: number };
|
|
63
|
+
elements: ElementDiffResult[];
|
|
64
|
+
summary: {
|
|
65
|
+
total: number;
|
|
66
|
+
matched: number;
|
|
67
|
+
changed: number;
|
|
68
|
+
missing: number;
|
|
69
|
+
/** Full-page diff ratio (for comparison) */
|
|
70
|
+
fullPageDiffRatio?: number;
|
|
71
|
+
/** Sum of element-level diff pixels (isolates actual changes from cascading shifts) */
|
|
72
|
+
elementDiffRatio: number;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---- Core ----
|
|
77
|
+
|
|
78
|
+
async function captureElementScreenshot(
|
|
79
|
+
page: Page,
|
|
80
|
+
selector: string,
|
|
81
|
+
outputPath: string,
|
|
82
|
+
): Promise<{ found: boolean; bbox?: { x: number; y: number; width: number; height: number } }> {
|
|
83
|
+
const locator = page.locator(selector).first();
|
|
84
|
+
try {
|
|
85
|
+
await locator.waitFor({ state: "visible", timeout: 3000 });
|
|
86
|
+
const bbox = await locator.boundingBox();
|
|
87
|
+
if (!bbox) return { found: false };
|
|
88
|
+
await locator.screenshot({ path: outputPath });
|
|
89
|
+
return { found: true, bbox: { x: Math.round(bbox.x), y: Math.round(bbox.y), width: Math.round(bbox.width), height: Math.round(bbox.height) } };
|
|
90
|
+
} catch {
|
|
91
|
+
return { found: false };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function runElementCompare(
|
|
96
|
+
options: ElementCompareOptions,
|
|
97
|
+
): Promise<ElementCompareReport> {
|
|
98
|
+
const {
|
|
99
|
+
selectors,
|
|
100
|
+
viewport = { width: 1280, height: 900 },
|
|
101
|
+
outputDir,
|
|
102
|
+
maskSelectors = [],
|
|
103
|
+
threshold = 0.1,
|
|
104
|
+
} = options;
|
|
105
|
+
|
|
106
|
+
await mkdir(outputDir, { recursive: true });
|
|
107
|
+
|
|
108
|
+
const browser = await chromium.launch();
|
|
109
|
+
const results: ElementDiffResult[] = [];
|
|
110
|
+
let fullPageDiffRatio: number | undefined;
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
// Setup baseline page
|
|
114
|
+
const baselinePage = await browser.newPage({ viewport });
|
|
115
|
+
if (options.baselineUrl) {
|
|
116
|
+
await baselinePage.goto(options.baselineUrl, { waitUntil: "networkidle", timeout: 30000 });
|
|
117
|
+
} else if (options.baselineFile) {
|
|
118
|
+
const html = await readFile(resolve(options.baselineFile), "utf-8");
|
|
119
|
+
await baselinePage.setContent(html, { waitUntil: "networkidle" });
|
|
120
|
+
}
|
|
121
|
+
await applyMask(baselinePage, maskSelectors);
|
|
122
|
+
|
|
123
|
+
// Setup current page
|
|
124
|
+
const currentPage = await browser.newPage({ viewport });
|
|
125
|
+
if (options.currentUrl) {
|
|
126
|
+
await currentPage.goto(options.currentUrl, { waitUntil: "networkidle", timeout: 30000 });
|
|
127
|
+
} else if (options.currentFile) {
|
|
128
|
+
const html = await readFile(resolve(options.currentFile), "utf-8");
|
|
129
|
+
await currentPage.setContent(html, { waitUntil: "networkidle" });
|
|
130
|
+
}
|
|
131
|
+
await applyMask(currentPage, maskSelectors);
|
|
132
|
+
|
|
133
|
+
// Full-page comparison for reference
|
|
134
|
+
const fullBaselinePath = join(outputDir, "fullpage-baseline.png");
|
|
135
|
+
const fullCurrentPath = join(outputDir, "fullpage-current.png");
|
|
136
|
+
await baselinePage.screenshot({ path: fullBaselinePath, fullPage: true });
|
|
137
|
+
await currentPage.screenshot({ path: fullCurrentPath, fullPage: true });
|
|
138
|
+
|
|
139
|
+
const fullSnap: VrtSnapshot = {
|
|
140
|
+
testId: "fullpage",
|
|
141
|
+
testTitle: "Full Page",
|
|
142
|
+
projectName: "element-compare",
|
|
143
|
+
screenshotPath: fullCurrentPath,
|
|
144
|
+
baselinePath: fullBaselinePath,
|
|
145
|
+
status: "changed",
|
|
146
|
+
};
|
|
147
|
+
const fullDiff = await compareScreenshots(fullSnap, { outputDir, threshold });
|
|
148
|
+
fullPageDiffRatio = fullDiff?.diffRatio ?? 0;
|
|
149
|
+
|
|
150
|
+
// Element-level comparison
|
|
151
|
+
for (const selector of selectors) {
|
|
152
|
+
const safeSelector = selector.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
153
|
+
const baselinePath = join(outputDir, `el-${safeSelector}-baseline.png`);
|
|
154
|
+
const currentPath = join(outputDir, `el-${safeSelector}-current.png`);
|
|
155
|
+
|
|
156
|
+
const baselineResult = await captureElementScreenshot(baselinePage, selector, baselinePath);
|
|
157
|
+
const currentResult = await captureElementScreenshot(currentPage, selector, currentPath);
|
|
158
|
+
|
|
159
|
+
if (!baselineResult.found || !currentResult.found) {
|
|
160
|
+
results.push({
|
|
161
|
+
selector,
|
|
162
|
+
found: { baseline: baselineResult.found, current: currentResult.found },
|
|
163
|
+
diffPixels: 0,
|
|
164
|
+
totalPixels: 0,
|
|
165
|
+
diffRatio: baselineResult.found !== currentResult.found ? 1 : 0,
|
|
166
|
+
});
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const snap: VrtSnapshot = {
|
|
171
|
+
testId: `el-${safeSelector}`,
|
|
172
|
+
testTitle: `Element: ${selector}`,
|
|
173
|
+
projectName: "element-compare",
|
|
174
|
+
screenshotPath: currentPath,
|
|
175
|
+
baselinePath: baselinePath,
|
|
176
|
+
status: "changed",
|
|
177
|
+
};
|
|
178
|
+
const diff = await compareScreenshots(snap, { outputDir, threshold });
|
|
179
|
+
|
|
180
|
+
results.push({
|
|
181
|
+
selector,
|
|
182
|
+
found: { baseline: true, current: true },
|
|
183
|
+
baselineBBox: baselineResult.bbox,
|
|
184
|
+
currentBBox: currentResult.bbox,
|
|
185
|
+
diffPixels: diff?.diffPixels ?? 0,
|
|
186
|
+
totalPixels: diff?.totalPixels ?? 0,
|
|
187
|
+
diffRatio: diff?.diffRatio ?? 0,
|
|
188
|
+
heatmapPath: diff?.heatmapPath,
|
|
189
|
+
baselinePath,
|
|
190
|
+
currentPath,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
await baselinePage.close();
|
|
195
|
+
await currentPage.close();
|
|
196
|
+
} finally {
|
|
197
|
+
await browser.close();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Build summary
|
|
201
|
+
const matched = results.filter((r) => r.found.baseline && r.found.current);
|
|
202
|
+
const changed = matched.filter((r) => r.diffRatio > 0);
|
|
203
|
+
const missing = results.filter((r) => !r.found.baseline || !r.found.current);
|
|
204
|
+
const totalElementPixels = matched.reduce((s, r) => s + r.totalPixels, 0);
|
|
205
|
+
const totalElementDiffPixels = matched.reduce((s, r) => s + r.diffPixels, 0);
|
|
206
|
+
|
|
207
|
+
const report: ElementCompareReport = {
|
|
208
|
+
baselineSource: options.baselineUrl ?? options.baselineFile ?? "",
|
|
209
|
+
currentSource: options.currentUrl ?? options.currentFile ?? "",
|
|
210
|
+
viewport,
|
|
211
|
+
elements: results,
|
|
212
|
+
summary: {
|
|
213
|
+
total: selectors.length,
|
|
214
|
+
matched: matched.length,
|
|
215
|
+
changed: changed.length,
|
|
216
|
+
missing: missing.length,
|
|
217
|
+
fullPageDiffRatio,
|
|
218
|
+
elementDiffRatio: totalElementPixels > 0 ? totalElementDiffPixels / totalElementPixels : 0,
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
return report;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ---- CLI ----
|
|
226
|
+
|
|
227
|
+
function parseArgs(args: string[]): ElementCompareOptions {
|
|
228
|
+
function getArg(name: string, fallback = ""): string {
|
|
229
|
+
const idx = args.indexOf(`--${name}`);
|
|
230
|
+
return idx >= 0 && args[idx + 1] ? args[idx + 1] : fallback;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const selectorsRaw = getArg("selectors");
|
|
234
|
+
if (!selectorsRaw) {
|
|
235
|
+
throw new Error("--selectors is required (comma-separated CSS selectors)");
|
|
236
|
+
}
|
|
237
|
+
const selectors = selectorsRaw.split(",").map((s) => s.trim()).filter(Boolean);
|
|
238
|
+
|
|
239
|
+
const baselineUrl = getArg("url") || undefined;
|
|
240
|
+
const currentUrl = getArg("current-url") || undefined;
|
|
241
|
+
|
|
242
|
+
// Positional args for file mode
|
|
243
|
+
const positional = args.filter((a) => !a.startsWith("--") && !args.some((b, i) => b.startsWith("--") && args[i + 1] === a));
|
|
244
|
+
const baselineFile = !baselineUrl ? positional[0] : undefined;
|
|
245
|
+
const currentFile = !currentUrl ? positional[1] : undefined;
|
|
246
|
+
|
|
247
|
+
const vpArg = getArg("viewport", "1280x900");
|
|
248
|
+
const [w, h] = vpArg.split("x").map(Number);
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
selectors,
|
|
252
|
+
baselineFile,
|
|
253
|
+
currentFile,
|
|
254
|
+
baselineUrl,
|
|
255
|
+
currentUrl,
|
|
256
|
+
viewport: { width: w || 1280, height: h || 900 },
|
|
257
|
+
outputDir: resolve(getArg("output", join(process.cwd(), "test-results", "element-compare"))),
|
|
258
|
+
maskSelectors: parseMaskSelectors(args),
|
|
259
|
+
threshold: parseFloat(getArg("threshold", "0.1")),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async function main() {
|
|
264
|
+
const cliArgs = process.argv.slice(2);
|
|
265
|
+
const options = parseArgs(cliArgs);
|
|
266
|
+
|
|
267
|
+
if (!options.baselineUrl && !options.baselineFile) {
|
|
268
|
+
console.log(`Usage:`);
|
|
269
|
+
console.log(` vrt elements --url <baseline> --current-url <current> --selectors "header,main,footer"`);
|
|
270
|
+
console.log(` vrt elements before.html after.html --selectors "header,.content"`);
|
|
271
|
+
console.log();
|
|
272
|
+
console.log(`Options:`);
|
|
273
|
+
console.log(` --selectors <sel1,sel2,...> CSS selectors to compare (required)`);
|
|
274
|
+
console.log(` --viewport <WxH> Viewport size (default: 1280x900)`);
|
|
275
|
+
console.log(` --output <dir> Output directory`);
|
|
276
|
+
console.log(` --mask <selectors> Mask dynamic content`);
|
|
277
|
+
console.log(` --threshold <0-1> pixelmatch threshold (default: 0.1)`);
|
|
278
|
+
process.exit(1);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
console.log();
|
|
282
|
+
console.log(`${BOLD}${CYAN}╔════════════════════════════════════════════════════════════════════════╗${RESET}`);
|
|
283
|
+
console.log(`${BOLD}${CYAN}║ Element-level VRT Compare ║${RESET}`);
|
|
284
|
+
console.log(`${BOLD}${CYAN}╚════════════════════════════════════════════════════════════════════════╝${RESET}`);
|
|
285
|
+
console.log(` ${DIM}Selectors: ${options.selectors.join(", ")}${RESET}`);
|
|
286
|
+
console.log(` ${DIM}Viewport: ${options.viewport?.width}x${options.viewport?.height}${RESET}`);
|
|
287
|
+
console.log();
|
|
288
|
+
|
|
289
|
+
const report = await runElementCompare(options);
|
|
290
|
+
|
|
291
|
+
// Print results
|
|
292
|
+
for (const el of report.elements) {
|
|
293
|
+
if (!el.found.baseline && !el.found.current) {
|
|
294
|
+
console.log(` ${DIM}${el.selector.padEnd(30)}${RESET} ${YELLOW}not found${RESET}`);
|
|
295
|
+
} else if (!el.found.baseline || !el.found.current) {
|
|
296
|
+
const side = el.found.baseline ? "current" : "baseline";
|
|
297
|
+
console.log(` ${DIM}${el.selector.padEnd(30)}${RESET} ${RED}missing in ${side}${RESET}`);
|
|
298
|
+
} else if (el.diffRatio === 0) {
|
|
299
|
+
console.log(` ${el.selector.padEnd(30)} ${GREEN}0.0%${RESET}`);
|
|
300
|
+
} else {
|
|
301
|
+
const color = el.diffRatio < 0.01 ? YELLOW : RED;
|
|
302
|
+
const pct = (el.diffRatio * 100).toFixed(2);
|
|
303
|
+
const bbox = el.currentBBox;
|
|
304
|
+
const bboxStr = bbox ? ` ${DIM}(${bbox.width}x${bbox.height} @${bbox.x},${bbox.y})${RESET}` : "";
|
|
305
|
+
console.log(` ${el.selector.padEnd(30)} ${color}${pct}%${RESET}${bboxStr}`);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Summary
|
|
310
|
+
console.log();
|
|
311
|
+
hr();
|
|
312
|
+
console.log();
|
|
313
|
+
|
|
314
|
+
const { summary } = report;
|
|
315
|
+
if (summary.fullPageDiffRatio !== undefined) {
|
|
316
|
+
const fpColor = summary.fullPageDiffRatio === 0 ? GREEN : summary.fullPageDiffRatio < 0.01 ? YELLOW : RED;
|
|
317
|
+
console.log(` Full-page diff: ${fpColor}${(summary.fullPageDiffRatio * 100).toFixed(2)}%${RESET}`);
|
|
318
|
+
}
|
|
319
|
+
const elColor = summary.elementDiffRatio === 0 ? GREEN : summary.elementDiffRatio < 0.01 ? YELLOW : RED;
|
|
320
|
+
console.log(` Element diff: ${elColor}${(summary.elementDiffRatio * 100).toFixed(2)}%${RESET}`);
|
|
321
|
+
console.log(` ${DIM}Elements: ${summary.total} total, ${summary.matched} matched, ${summary.changed} changed, ${summary.missing} missing${RESET}`);
|
|
322
|
+
|
|
323
|
+
if (summary.fullPageDiffRatio !== undefined && summary.fullPageDiffRatio > 0 && summary.elementDiffRatio < summary.fullPageDiffRatio) {
|
|
324
|
+
const reduction = ((1 - summary.elementDiffRatio / summary.fullPageDiffRatio) * 100).toFixed(0);
|
|
325
|
+
console.log(` ${GREEN}Element-level reduces noise by ${reduction}%${RESET}`);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
console.log();
|
|
329
|
+
|
|
330
|
+
// Write report
|
|
331
|
+
const reportPath = join(options.outputDir, "element-compare-report.json");
|
|
332
|
+
await writeFile(reportPath, JSON.stringify(report, null, 2));
|
|
333
|
+
console.log(` ${DIM}Report: ${reportPath}${RESET}`);
|
|
334
|
+
console.log();
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (process.env.__VRT_DISPATCHER_LEAF__ === "element-compare" || process.argv[1]?.endsWith("element-compare.ts")) {
|
|
338
|
+
main().catch((e) => { console.error(e); process.exit(1); });
|
|
339
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
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
|
+
}
|