@mizchi/vlmkit-core 0.7.0 → 0.8.1
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/dist/a11y-semantic.d.mts +34 -0
- package/dist/a11y-semantic.mjs +261 -0
- package/dist/authored-style-capture.d.mts +42 -0
- package/dist/authored-style-capture.mjs +117 -0
- package/dist/authored-style-diff.d.mts +15 -0
- package/dist/authored-style-diff.mjs +16 -0
- package/dist/cli-args.d.mts +11 -0
- package/dist/cli-args.mjs +21 -0
- package/dist/cli-error.d.mts +4 -0
- package/dist/cli-error.mjs +59 -0
- package/dist/computed-style-capture.d.mts +41 -0
- package/dist/computed-style-capture.mjs +589 -0
- package/dist/computed-style-diff.d.mts +83 -0
- package/dist/computed-style-diff.mjs +123 -0
- package/dist/diff-regions.d.mts +8 -0
- package/dist/diff-regions.mjs +52 -0
- package/dist/dom-equivalence.d.mts +51 -0
- package/dist/dom-equivalence.mjs +91 -0
- package/dist/dom-position-styles.d.mts +166 -0
- package/dist/dom-position-styles.mjs +296 -0
- package/dist/element-compare.d.mts +71 -0
- package/dist/element-compare.mjs +269 -0
- package/dist/heatmap-regions.d.mts +57 -0
- package/dist/heatmap-regions.mjs +158 -0
- package/dist/heatmap.d.mts +86 -0
- package/dist/heatmap.mjs +510 -0
- package/dist/image-resize.d.mts +34 -0
- package/dist/image-resize.mjs +92 -0
- package/dist/index.d.mts +15 -0
- package/dist/index.mjs +14 -0
- package/dist/mask.d.mts +18 -0
- package/dist/mask.mjs +27 -0
- package/dist/png-utils.d.mts +30 -0
- package/dist/png-utils.mjs +80 -0
- package/dist/region-shift.d.mts +20 -0
- package/dist/region-shift.mjs +128 -0
- package/dist/run-ledger.d.mts +14 -0
- package/dist/run-ledger.mjs +31 -0
- package/dist/terminal-colors.d.mts +12 -0
- package/dist/terminal-colors.mjs +14 -0
- package/dist/text-rows.d.mts +121 -0
- package/dist/text-rows.mjs +246 -0
- package/{src/types.ts → dist/types.d.mts} +88 -206
- package/dist/types.mjs +1 -0
- package/package.json +17 -5
- package/src/a11y-semantic.ts +0 -384
- package/src/authored-style-capture.ts +0 -185
- package/src/authored-style-diff.ts +0 -32
- package/src/cli-args.ts +0 -29
- package/src/cli-error.ts +0 -85
- package/src/computed-style-capture.ts +0 -717
- package/src/computed-style-diff.ts +0 -192
- package/src/diff-regions.ts +0 -70
- package/src/dom-equivalence.ts +0 -158
- package/src/dom-position-styles.ts +0 -457
- package/src/element-compare.ts +0 -354
- package/src/heatmap-regions.ts +0 -245
- package/src/heatmap.ts +0 -670
- package/src/image-resize.ts +0 -112
- package/src/index.ts +0 -105
- package/src/mask.ts +0 -41
- package/src/png-utils.ts +0 -86
- package/src/region-shift.ts +0 -173
- package/src/terminal-colors.ts +0 -13
- package/src/text-rows.ts +0 -412
package/src/element-compare.ts
DELETED
|
@@ -1,354 +0,0 @@
|
|
|
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
|
-
function formatUsage(): string {
|
|
264
|
-
return [
|
|
265
|
-
"Usage:",
|
|
266
|
-
" vrt diff component --url <baseline> --current-url <current> --selectors \"header,main,footer\"",
|
|
267
|
-
" vrt diff component before.html after.html --selectors \"header,.content\"",
|
|
268
|
-
"",
|
|
269
|
-
"Aliases:",
|
|
270
|
-
" vrt diff elements",
|
|
271
|
-
" vrt elements",
|
|
272
|
-
"",
|
|
273
|
-
"Options:",
|
|
274
|
-
" --selectors <sel1,sel2,...> CSS selectors to compare (required)",
|
|
275
|
-
" --viewport <WxH> Viewport size (default: 1280x900)",
|
|
276
|
-
" --output <dir> Output directory",
|
|
277
|
-
" --mask <selectors> Mask dynamic content",
|
|
278
|
-
" --threshold <0-1> pixelmatch threshold (default: 0.1)",
|
|
279
|
-
].join("\n");
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
async function main() {
|
|
283
|
-
const cliArgs = process.argv.slice(2);
|
|
284
|
-
if (cliArgs.includes("--help") || cliArgs.includes("-h") || cliArgs.includes("help")) {
|
|
285
|
-
console.log(formatUsage());
|
|
286
|
-
return;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
const options = parseArgs(cliArgs);
|
|
290
|
-
|
|
291
|
-
if (!options.baselineUrl && !options.baselineFile) {
|
|
292
|
-
console.log(formatUsage());
|
|
293
|
-
process.exit(1);
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
console.log();
|
|
297
|
-
console.log(`${BOLD}${CYAN}╔════════════════════════════════════════════════════════════════════════╗${RESET}`);
|
|
298
|
-
console.log(`${BOLD}${CYAN}║ Element-level VRT Compare ║${RESET}`);
|
|
299
|
-
console.log(`${BOLD}${CYAN}╚════════════════════════════════════════════════════════════════════════╝${RESET}`);
|
|
300
|
-
console.log(` ${DIM}Selectors: ${options.selectors.join(", ")}${RESET}`);
|
|
301
|
-
console.log(` ${DIM}Viewport: ${options.viewport?.width}x${options.viewport?.height}${RESET}`);
|
|
302
|
-
console.log();
|
|
303
|
-
|
|
304
|
-
const report = await runElementCompare(options);
|
|
305
|
-
|
|
306
|
-
// Print results
|
|
307
|
-
for (const el of report.elements) {
|
|
308
|
-
if (!el.found.baseline && !el.found.current) {
|
|
309
|
-
console.log(` ${DIM}${el.selector.padEnd(30)}${RESET} ${YELLOW}not found${RESET}`);
|
|
310
|
-
} else if (!el.found.baseline || !el.found.current) {
|
|
311
|
-
const side = el.found.baseline ? "current" : "baseline";
|
|
312
|
-
console.log(` ${DIM}${el.selector.padEnd(30)}${RESET} ${RED}missing in ${side}${RESET}`);
|
|
313
|
-
} else if (el.diffRatio === 0) {
|
|
314
|
-
console.log(` ${el.selector.padEnd(30)} ${GREEN}0.0%${RESET}`);
|
|
315
|
-
} else {
|
|
316
|
-
const color = el.diffRatio < 0.01 ? YELLOW : RED;
|
|
317
|
-
const pct = (el.diffRatio * 100).toFixed(2);
|
|
318
|
-
const bbox = el.currentBBox;
|
|
319
|
-
const bboxStr = bbox ? ` ${DIM}(${bbox.width}x${bbox.height} @${bbox.x},${bbox.y})${RESET}` : "";
|
|
320
|
-
console.log(` ${el.selector.padEnd(30)} ${color}${pct}%${RESET}${bboxStr}`);
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// Summary
|
|
325
|
-
console.log();
|
|
326
|
-
hr();
|
|
327
|
-
console.log();
|
|
328
|
-
|
|
329
|
-
const { summary } = report;
|
|
330
|
-
if (summary.fullPageDiffRatio !== undefined) {
|
|
331
|
-
const fpColor = summary.fullPageDiffRatio === 0 ? GREEN : summary.fullPageDiffRatio < 0.01 ? YELLOW : RED;
|
|
332
|
-
console.log(` Full-page diff: ${fpColor}${(summary.fullPageDiffRatio * 100).toFixed(2)}%${RESET}`);
|
|
333
|
-
}
|
|
334
|
-
const elColor = summary.elementDiffRatio === 0 ? GREEN : summary.elementDiffRatio < 0.01 ? YELLOW : RED;
|
|
335
|
-
console.log(` Element diff: ${elColor}${(summary.elementDiffRatio * 100).toFixed(2)}%${RESET}`);
|
|
336
|
-
console.log(` ${DIM}Elements: ${summary.total} total, ${summary.matched} matched, ${summary.changed} changed, ${summary.missing} missing${RESET}`);
|
|
337
|
-
|
|
338
|
-
if (summary.fullPageDiffRatio !== undefined && summary.fullPageDiffRatio > 0 && summary.elementDiffRatio < summary.fullPageDiffRatio) {
|
|
339
|
-
const reduction = ((1 - summary.elementDiffRatio / summary.fullPageDiffRatio) * 100).toFixed(0);
|
|
340
|
-
console.log(` ${GREEN}Element-level reduces noise by ${reduction}%${RESET}`);
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
console.log();
|
|
344
|
-
|
|
345
|
-
// Write report
|
|
346
|
-
const reportPath = join(options.outputDir, "element-compare-report.json");
|
|
347
|
-
await writeFile(reportPath, JSON.stringify(report, null, 2));
|
|
348
|
-
console.log(` ${DIM}Report: ${reportPath}${RESET}`);
|
|
349
|
-
console.log();
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
if (process.env.__VRT_DISPATCHER_LEAF__ === "element-compare" || process.argv[1]?.endsWith("element-compare.ts")) {
|
|
353
|
-
main().catch((e) => { console.error(e); process.exit(1); });
|
|
354
|
-
}
|
package/src/heatmap-regions.ts
DELETED
|
@@ -1,245 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Heatmap region clustering.
|
|
3
|
-
*
|
|
4
|
-
* `detectBandShifts` (see `heatmap.ts`) reports per-band Y-shifts —
|
|
5
|
-
* useful for global translations but loses horizontal localization.
|
|
6
|
-
* Subagent F wished for "heatmap region clustering": group connected
|
|
7
|
-
* hot pixels in `*_heatmap.png` into clusters with rectangular
|
|
8
|
-
* bounding boxes, so "a text run at y=420 shifted up 4px" becomes
|
|
9
|
-
* one row instead of being smeared across a tall band.
|
|
10
|
-
*
|
|
11
|
-
* Reuses the connected-component algorithm from `component-bbox.ts`
|
|
12
|
-
* — the input is just a different mask (foreground = "hot pixel").
|
|
13
|
-
*
|
|
14
|
-
* Pixelmatch heatmaps use a fixed palette: bright red for "diff
|
|
15
|
-
* pixel", original (resized) baseline tinted for context. We treat
|
|
16
|
-
* any pixel whose red channel is strongly elevated relative to the
|
|
17
|
-
* other two channels as a hot pixel.
|
|
18
|
-
*/
|
|
19
|
-
import { PNG } from "pngjs";
|
|
20
|
-
import { readFile } from "node:fs/promises";
|
|
21
|
-
|
|
22
|
-
export interface HeatmapRegion {
|
|
23
|
-
top: number;
|
|
24
|
-
left: number;
|
|
25
|
-
width: number;
|
|
26
|
-
height: number;
|
|
27
|
-
/** Hot-pixel count inside the bbox. */
|
|
28
|
-
area: number;
|
|
29
|
-
/**
|
|
30
|
-
* Dominant color of the region as sampled from a *source* image
|
|
31
|
-
* (the baseline / target PNG that the heatmap was generated against).
|
|
32
|
-
* Only populated when `findHeatmapRegionsFromFile` was called with a
|
|
33
|
-
* `sourceImagePath`. Lets the agent close the loop between
|
|
34
|
-
* "this region differs" and "fill it with this color".
|
|
35
|
-
*/
|
|
36
|
-
dominantColor?: { r: number; g: number; b: number; hex: string };
|
|
37
|
-
/**
|
|
38
|
-
* Content classification of the region inside the source image —
|
|
39
|
-
* `text` / `filled-rect` / `icon` / `image` / `unknown`. Helps the
|
|
40
|
-
* agent decide whether to paint a flat background, write a text
|
|
41
|
-
* run, or place an icon. Only populated when callers run an
|
|
42
|
-
* explicit annotation pass (see `annotateHeatmapRegionKinds` in
|
|
43
|
-
* `@mizchi/vlmkit-markup/heatmap-region-kinds.ts`); the bare
|
|
44
|
-
* `findHeatmapRegionsFromFile` no longer fills it in to keep
|
|
45
|
-
* vlmkit-core free of MoonBit policy.
|
|
46
|
-
*/
|
|
47
|
-
kind?: "text" | "filled-rect" | "icon" | "image" | "unknown";
|
|
48
|
-
/** Classifier confidence ∈ [0, 1]. */
|
|
49
|
-
kindConfidence?: number;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export interface FindHeatmapRegionsOptions {
|
|
53
|
-
/** Minimum hot-pixel count for a region to be kept. Default 80. */
|
|
54
|
-
minArea?: number;
|
|
55
|
-
/** Cap on returned regions, sorted by area desc. Default 8. */
|
|
56
|
-
topN?: number;
|
|
57
|
-
/** Hot-pixel threshold: red − max(green, blue) >= this. Default 60. */
|
|
58
|
-
redOverGreenBlue?: number;
|
|
59
|
-
/**
|
|
60
|
-
* Skip regions whose bbox covers ≥ this fraction of the image. When
|
|
61
|
-
* baseline and variant are almost entirely different (e.g. blank
|
|
62
|
-
* page vs full target), the CC pass produces one giant region
|
|
63
|
-
* spanning 0,0 → W,H. That region is uninformative ("the whole
|
|
64
|
-
* page differs" is already obvious from diff %) and wastes
|
|
65
|
-
* iteration. Default 0.8 — drop regions covering ≥80% of the image.
|
|
66
|
-
* From subagent dogfood eval.
|
|
67
|
-
*/
|
|
68
|
-
maxRegionFraction?: number;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const DEFAULT_MIN_AREA = 80;
|
|
72
|
-
const DEFAULT_TOP_N = 8;
|
|
73
|
-
const DEFAULT_RED_OVER = 60;
|
|
74
|
-
const DEFAULT_MAX_REGION_FRACTION = 0.8;
|
|
75
|
-
|
|
76
|
-
function buildHotMask(
|
|
77
|
-
data: Uint8Array,
|
|
78
|
-
width: number,
|
|
79
|
-
height: number,
|
|
80
|
-
redOver: number,
|
|
81
|
-
): Uint8Array {
|
|
82
|
-
const mask = new Uint8Array(width * height);
|
|
83
|
-
for (let y = 0; y < height; y++) {
|
|
84
|
-
for (let x = 0; x < width; x++) {
|
|
85
|
-
const idx = (y * width + x) * 4;
|
|
86
|
-
const r = data[idx]!, g = data[idx + 1]!, b = data[idx + 2]!;
|
|
87
|
-
if (r - Math.max(g, b) >= redOver) {
|
|
88
|
-
mask[y * width + x] = 1;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return mask;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function labelComponents(mask: Uint8Array, width: number, height: number): HeatmapRegion[] {
|
|
96
|
-
const labels = new Int32Array(width * height);
|
|
97
|
-
const parent: number[] = [0];
|
|
98
|
-
const find = (x: number): number => {
|
|
99
|
-
while (parent[x] !== x) {
|
|
100
|
-
parent[x] = parent[parent[x]!]!;
|
|
101
|
-
x = parent[x]!;
|
|
102
|
-
}
|
|
103
|
-
return x;
|
|
104
|
-
};
|
|
105
|
-
const union = (a: number, b: number): void => {
|
|
106
|
-
const ra = find(a), rb = find(b);
|
|
107
|
-
if (ra !== rb) parent[Math.max(ra, rb)] = Math.min(ra, rb);
|
|
108
|
-
};
|
|
109
|
-
let next = 1;
|
|
110
|
-
for (let y = 0; y < height; y++) {
|
|
111
|
-
for (let x = 0; x < width; x++) {
|
|
112
|
-
const idx = y * width + x;
|
|
113
|
-
if (!mask[idx]) continue;
|
|
114
|
-
const up = y > 0 ? labels[idx - width]! : 0;
|
|
115
|
-
const left = x > 0 ? labels[idx - 1]! : 0;
|
|
116
|
-
if (up && left) {
|
|
117
|
-
const a = Math.min(up, left);
|
|
118
|
-
labels[idx] = a;
|
|
119
|
-
if (up !== left) union(up, left);
|
|
120
|
-
} else if (up) {
|
|
121
|
-
labels[idx] = up;
|
|
122
|
-
} else if (left) {
|
|
123
|
-
labels[idx] = left;
|
|
124
|
-
} else {
|
|
125
|
-
labels[idx] = next;
|
|
126
|
-
parent[next] = next;
|
|
127
|
-
next++;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
type Stat = { minX: number; minY: number; maxX: number; maxY: number; area: number };
|
|
132
|
-
const byRoot = new Map<number, Stat>();
|
|
133
|
-
for (let y = 0; y < height; y++) {
|
|
134
|
-
for (let x = 0; x < width; x++) {
|
|
135
|
-
const l = labels[y * width + x];
|
|
136
|
-
if (!l) continue;
|
|
137
|
-
const root = find(l);
|
|
138
|
-
let s = byRoot.get(root);
|
|
139
|
-
if (!s) {
|
|
140
|
-
s = { minX: x, minY: y, maxX: x, maxY: y, area: 0 };
|
|
141
|
-
byRoot.set(root, s);
|
|
142
|
-
}
|
|
143
|
-
if (x < s.minX) s.minX = x;
|
|
144
|
-
if (x > s.maxX) s.maxX = x;
|
|
145
|
-
if (y < s.minY) s.minY = y;
|
|
146
|
-
if (y > s.maxY) s.maxY = y;
|
|
147
|
-
s.area++;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
const out: HeatmapRegion[] = [];
|
|
151
|
-
for (const s of byRoot.values()) {
|
|
152
|
-
out.push({
|
|
153
|
-
top: s.minY,
|
|
154
|
-
left: s.minX,
|
|
155
|
-
width: s.maxX - s.minX + 1,
|
|
156
|
-
height: s.maxY - s.minY + 1,
|
|
157
|
-
area: s.area,
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
return out;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
export function findHeatmapRegionsFromRgba(
|
|
164
|
-
data: Uint8Array,
|
|
165
|
-
width: number,
|
|
166
|
-
height: number,
|
|
167
|
-
options: FindHeatmapRegionsOptions = {},
|
|
168
|
-
): HeatmapRegion[] {
|
|
169
|
-
const minArea = options.minArea ?? DEFAULT_MIN_AREA;
|
|
170
|
-
const topN = options.topN ?? DEFAULT_TOP_N;
|
|
171
|
-
const redOver = options.redOverGreenBlue ?? DEFAULT_RED_OVER;
|
|
172
|
-
const maxFraction = options.maxRegionFraction ?? DEFAULT_MAX_REGION_FRACTION;
|
|
173
|
-
|
|
174
|
-
if (width <= 0 || height <= 0) return [];
|
|
175
|
-
const mask = buildHotMask(data, width, height, redOver);
|
|
176
|
-
const imageArea = width * height;
|
|
177
|
-
return labelComponents(mask, width, height)
|
|
178
|
-
.filter((r) => r.area >= minArea)
|
|
179
|
-
.filter((r) => (r.width * r.height) / imageArea < maxFraction)
|
|
180
|
-
.sort((a, b) => b.area - a.area)
|
|
181
|
-
.slice(0, topN);
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function toHex(r: number, g: number, b: number): string {
|
|
185
|
-
const c = (n: number) => n.toString(16).padStart(2, "0");
|
|
186
|
-
return `#${c(r)}${c(g)}${c(b)}`;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** Sample the dominant color inside `region` from the source image data. */
|
|
190
|
-
function sampleRegionColor(
|
|
191
|
-
sourceData: Uint8Array,
|
|
192
|
-
sourceWidth: number,
|
|
193
|
-
sourceHeight: number,
|
|
194
|
-
region: HeatmapRegion,
|
|
195
|
-
): { r: number; g: number; b: number; hex: string } | undefined {
|
|
196
|
-
// Sample on a 5×5 grid inside the region. Skip transparent pixels.
|
|
197
|
-
// Use the median per-channel rather than mean — robust against
|
|
198
|
-
// boundary pixels that might pick up surrounding bg color.
|
|
199
|
-
const inset = 2;
|
|
200
|
-
const x0 = Math.max(0, region.left + inset);
|
|
201
|
-
const x1 = Math.min(sourceWidth, region.left + region.width - inset);
|
|
202
|
-
const y0 = Math.max(0, region.top + inset);
|
|
203
|
-
const y1 = Math.min(sourceHeight, region.top + region.height - inset);
|
|
204
|
-
if (x1 <= x0 || y1 <= y0) return undefined;
|
|
205
|
-
const stepX = Math.max(1, Math.floor((x1 - x0) / 5));
|
|
206
|
-
const stepY = Math.max(1, Math.floor((y1 - y0) / 5));
|
|
207
|
-
const rs: number[] = [], gs: number[] = [], bs: number[] = [];
|
|
208
|
-
for (let y = y0; y < y1; y += stepY) {
|
|
209
|
-
for (let x = x0; x < x1; x += stepX) {
|
|
210
|
-
const i = (y * sourceWidth + x) * 4;
|
|
211
|
-
if (sourceData[i + 3]! === 0) continue;
|
|
212
|
-
rs.push(sourceData[i]!);
|
|
213
|
-
gs.push(sourceData[i + 1]!);
|
|
214
|
-
bs.push(sourceData[i + 2]!);
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
if (rs.length === 0) return undefined;
|
|
218
|
-
rs.sort((a, b) => a - b); gs.sort((a, b) => a - b); bs.sort((a, b) => a - b);
|
|
219
|
-
const mid = rs.length >> 1;
|
|
220
|
-
const r = rs[mid]!, g = gs[mid]!, b = bs[mid]!;
|
|
221
|
-
return { r, g, b, hex: toHex(r, g, b) };
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
export async function findHeatmapRegionsFromFile(
|
|
225
|
-
path: string,
|
|
226
|
-
options: FindHeatmapRegionsOptions = {},
|
|
227
|
-
sourceImagePath?: string,
|
|
228
|
-
): Promise<HeatmapRegion[]> {
|
|
229
|
-
const buf = await readFile(path);
|
|
230
|
-
const png = PNG.sync.read(buf);
|
|
231
|
-
const regions = findHeatmapRegionsFromRgba(png.data, png.width, png.height, options);
|
|
232
|
-
if (sourceImagePath) {
|
|
233
|
-
try {
|
|
234
|
-
const sourceBuf = await readFile(sourceImagePath);
|
|
235
|
-
const sourcePng = PNG.sync.read(sourceBuf);
|
|
236
|
-
for (const region of regions) {
|
|
237
|
-
const color = sampleRegionColor(sourcePng.data, sourcePng.width, sourcePng.height, region);
|
|
238
|
-
if (color) region.dominantColor = color;
|
|
239
|
-
}
|
|
240
|
-
} catch {
|
|
241
|
-
// Source image unavailable — leave regions without annotations.
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
return regions;
|
|
245
|
-
}
|