@whzxc/agent-design-gallery 0.7.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 +10 -1
- package/package.json +1 -1
- package/src/cli-output.mjs +23 -1
- package/src/cli.mjs +7 -3
- package/src/toolkit/arch-git.mjs +135 -4
- package/src/toolkit/browser.mjs +14 -0
- package/src/toolkit/build.mjs +10 -0
- package/src/toolkit/config.mjs +5 -3
- package/src/toolkit/diff-inputs.mjs +239 -0
- package/src/toolkit/diff-policy.mjs +28 -0
- package/src/toolkit/diff.mjs +258 -0
- package/src/toolkit/part-diff.mjs +118 -0
- package/src/toolkit/part-snapshot.mjs +264 -0
- package/src/toolkit/pixel-diff.mjs +103 -0
- package/src/toolkit/results.mjs +1 -1
- package/src/toolkit/runtime.d.ts +2 -1
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { availableParallelism } from 'node:os';
|
|
5
|
+
import { launch, loadFrame, browserTask, readyResources } from './browser.mjs';
|
|
6
|
+
import { prepareDiffInputs } from './diff-inputs.mjs';
|
|
7
|
+
import { currentHead } from './arch-git.mjs';
|
|
8
|
+
import { pixelComparator, imageDifference } from './pixel-diff.mjs';
|
|
9
|
+
import { partContext, captureEvidence, capturePart, isolateParent, frameIdentity, comparisonIdentity } from './part-diff.mjs';
|
|
10
|
+
import { commandFailure, cleanup, emptySelection } from './results.mjs';
|
|
11
|
+
import { CliError, classifyError, asCliError, nextActions } from '../cli-output.mjs';
|
|
12
|
+
import { resolveDiffPolicy } from './diff-policy.mjs';
|
|
13
|
+
|
|
14
|
+
const metadata = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
15
|
+
const safeName = name => encodeURIComponent(name).replace(/\./g, '%2E');
|
|
16
|
+
const classNames = ['imperceptible', 'antialiasing', 'boundary_bleed', 'bitmap_resampling', 'other'];
|
|
17
|
+
|
|
18
|
+
function frameFailure(error, row, theme) {
|
|
19
|
+
const failure = asCliError(error, 'RENDER_FAILED');
|
|
20
|
+
failure.message = `${row.source}: ${row.frame}: ${theme}: ${failure.message}`;
|
|
21
|
+
return failure;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function capturePair(browser, row, theme, scale, context) {
|
|
25
|
+
const captures = { before: null, after: null };
|
|
26
|
+
let page;
|
|
27
|
+
try {
|
|
28
|
+
for (const side of ['before', 'after']) {
|
|
29
|
+
if (!row[side]) continue;
|
|
30
|
+
page ??= await browserTask(browser, () => browser.newPage({ deviceScaleFactor: scale, locale: 'en-US', timezoneId: 'UTC' }));
|
|
31
|
+
await loadFrame(page, row[side], theme);
|
|
32
|
+
captures[side] = await browserTask(browser, async () => {
|
|
33
|
+
await page.evaluate(readyResources);
|
|
34
|
+
const element = page.locator('[data-adg-frame]');
|
|
35
|
+
const box = await element.boundingBox();
|
|
36
|
+
if (!box || box.width <= 0 || box.height <= 0) throw new Error('Frame has no visible bounds.');
|
|
37
|
+
const capture = () => element.screenshot({ animations: 'disabled', caret: 'hide' });
|
|
38
|
+
const targets = context?.targets.get(frameIdentity(row));
|
|
39
|
+
const evidence = targets ? await captureEvidence(page, targets, row, side, theme, context, capture) : { png: await capture() };
|
|
40
|
+
const png = evidence.png;
|
|
41
|
+
return { ...evidence, size: { width: box.width, height: box.height, pixelWidth: png.readUInt32BE(16), pixelHeight: png.readUInt32BE(20) } };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
if (context?.targets.has(frameIdentity(row))) context.parents.set(comparisonIdentity(row, theme), captures);
|
|
45
|
+
return { row, theme, page, ...captures };
|
|
46
|
+
} catch (error) {
|
|
47
|
+
const failure = frameFailure(error, row, theme);
|
|
48
|
+
await cleanup(() => page?.close(), failure);
|
|
49
|
+
throw failure;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function comparePair(browser, pair, thresholds, context) {
|
|
54
|
+
try {
|
|
55
|
+
return await browserTask(browser, async () => {
|
|
56
|
+
const compare = await pair.page.evaluateHandle(pixelComparator);
|
|
57
|
+
try {
|
|
58
|
+
const encoded = side => pair[side] ? `data:image/png;base64,${pair[side].png.toString('base64')}` : null;
|
|
59
|
+
const args = { before: encoded('before'), after: encoded('after'), compare, crop: pair.crop ?? null,
|
|
60
|
+
evidence: pair.evidence ? { ...pair.evidence, thresholds } : null };
|
|
61
|
+
let result = await pair.page.evaluate(imageDifference, args);
|
|
62
|
+
if (result.needsIsolation) {
|
|
63
|
+
await compare.dispose();
|
|
64
|
+
const isolated = await isolateParent(pair, context);
|
|
65
|
+
// Reloading the parent replaces the document and its function handle.
|
|
66
|
+
const isolatedCompare = await pair.page.evaluateHandle(pixelComparator);
|
|
67
|
+
try { result = await pair.page.evaluate(imageDifference, { ...args, compare: isolatedCompare, isolated: `data:image/png;base64,${isolated.toString('base64')}` }); }
|
|
68
|
+
finally { await isolatedCompare.dispose(); }
|
|
69
|
+
}
|
|
70
|
+
return { ...pair, ...result,
|
|
71
|
+
before: result.beforePng ? { ...pair.before, png: Buffer.from(result.beforePng, 'base64') } : pair.before,
|
|
72
|
+
isolated: result.isolatedPng ? Buffer.from(result.isolatedPng, 'base64') : null,
|
|
73
|
+
bleedMask: result.bleedPng ? Buffer.from(result.bleedPng, 'base64') : null,
|
|
74
|
+
difference: Buffer.from(result.png, 'base64') };
|
|
75
|
+
} finally { await compare.dispose(); }
|
|
76
|
+
});
|
|
77
|
+
} catch (error) { throw frameFailure(error, pair.row, pair.theme); }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function writePair(output, pair, thresholds) {
|
|
81
|
+
const { row, theme } = pair;
|
|
82
|
+
const directory = path.join(output, row.support ? 'support' : 'frames', ...row.source.split('/').map(safeName), safeName(row.frame), theme);
|
|
83
|
+
await mkdir(directory, { recursive: true });
|
|
84
|
+
const paths = {
|
|
85
|
+
before: pair.before ? path.join(directory, 'before.png') : null,
|
|
86
|
+
after: pair.after ? path.join(directory, 'after.png') : null,
|
|
87
|
+
difference: path.join(directory, 'difference.png'),
|
|
88
|
+
beforeSnapshot: pair.snapshots ? path.join(directory, 'before.snapshot.json') : null,
|
|
89
|
+
afterSnapshot: pair.snapshots ? path.join(directory, 'after.snapshot.json') : null,
|
|
90
|
+
parentCurrentSnapshot: pair.snapshots ? path.join(directory, 'parent-current.snapshot.json') : null,
|
|
91
|
+
report: path.join(directory, 'comparison.json'), parentIsolated: pair.isolated ? path.join(directory, 'parent-isolated.png') : null,
|
|
92
|
+
bleedMask: pair.bleedMask ? path.join(directory, 'bleed-mask.png') : null,
|
|
93
|
+
};
|
|
94
|
+
const beforeSize = pair.before?.size ?? null, afterSize = pair.after?.size ?? null;
|
|
95
|
+
const reasons = [];
|
|
96
|
+
if (!pair.parent && row.status !== 'matched') reasons.push(row.status);
|
|
97
|
+
if (row.matchKind === 'renamed_or_unknown') reasons.push('renamed_or_unknown');
|
|
98
|
+
if (beforeSize && afterSize && Object.keys(beforeSize).some(key => beforeSize[key] !== afterSize[key])) reasons.push('size_changed');
|
|
99
|
+
if (pair.parent) {
|
|
100
|
+
if (pair.snapshots.findings.length) reasons.push('snapshot_mismatch');
|
|
101
|
+
if (pair.parentChanged) reasons.push('parent_changed');
|
|
102
|
+
if (pair.singleTheme) reasons.push('theme_coverage_incomplete');
|
|
103
|
+
if (pair.pixels.classes.other.pixels) reasons.push('other_pixels');
|
|
104
|
+
if (!pair.pixels.classes.antialiasing.withinThreshold || !pair.pixels.classes.bitmap_resampling.withinThreshold) reasons.push('threshold_exceeded');
|
|
105
|
+
} else if (pair.pixels.differentPixels) reasons.push('pixels_changed');
|
|
106
|
+
const ref = { source: row.source, frame: row.frame };
|
|
107
|
+
const comparison = {
|
|
108
|
+
id: JSON.stringify([row.source, row.frame, theme, ...(row.support ? ['support'] : [])]), ...ref, theme,
|
|
109
|
+
status: row.status, matchKind: row.matchKind, matchCandidates: row.matchCandidates,
|
|
110
|
+
relation: pair.parent ? 'parent_crop' : 'revision', before: pair.parent?.ref ?? (pair.before ? ref : null), after: pair.after ? ref : null,
|
|
111
|
+
beforeSize, afterSize, parent: pair.parent ?? null, snapshots: pair.snapshots ?? null, pixels: pair.pixels,
|
|
112
|
+
verdict: reasons.length ? 'changed' : pair.parent ? 'structural' : 'identical', reasons,
|
|
113
|
+
note: { before: row.before?.note ?? null, after: row.after?.note ?? null }, paths,
|
|
114
|
+
};
|
|
115
|
+
await Promise.all([
|
|
116
|
+
pair.before && writeFile(paths.before, pair.before.png),
|
|
117
|
+
pair.after && writeFile(paths.after, pair.after.png),
|
|
118
|
+
writeFile(paths.difference, pair.difference),
|
|
119
|
+
]);
|
|
120
|
+
if (pair.snapshotFiles) await Promise.all(Object.entries(pair.snapshotFiles).map(([name, value]) => writeFile(paths[name], JSON.stringify(value, null, 2) + '\n')));
|
|
121
|
+
if (pair.isolated) await writeFile(paths.parentIsolated, pair.isolated);
|
|
122
|
+
if (pair.bleedMask) await writeFile(paths.bleedMask, pair.bleedMask);
|
|
123
|
+
await writeFile(paths.report, JSON.stringify({ classifierVersion: 1, thresholds, comparison }, null, 2) + '\n');
|
|
124
|
+
return comparison;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Exact ordinary frames and evidence-backed structural part comparisons. */
|
|
128
|
+
export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock } = {}) {
|
|
129
|
+
const started = performance.now(), scale = Number(options.scale ?? 2), themeOption = options.theme ?? 'both';
|
|
130
|
+
if (!Number.isFinite(scale) || scale <= 0) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number.');
|
|
131
|
+
if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
|
|
132
|
+
if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
|
|
133
|
+
const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
|
|
134
|
+
const output = options['out-dir'] === undefined ? path.join(config.output, 'diff') : path.resolve(config.root, options['out-dir']);
|
|
135
|
+
const timings = { prepareMs: 0, buildMs: 0, captureMs: 0, compareMs: 0, writeMs: 0, totalMs: 0 };
|
|
136
|
+
const warnings = [], completed = [];
|
|
137
|
+
const thresholds = config.diff?.thresholds ?? resolveDiffPolicy().thresholds;
|
|
138
|
+
let inputs, browser, data, primary, context;
|
|
139
|
+
const timed = async (name, work) => {
|
|
140
|
+
const start = performance.now();
|
|
141
|
+
try { return await work(); }
|
|
142
|
+
finally { timings[name] += performance.now() - start; }
|
|
143
|
+
};
|
|
144
|
+
try {
|
|
145
|
+
const head = await timed('prepareMs', async () => {
|
|
146
|
+
inputs = await prepareInputs(config, args, options);
|
|
147
|
+
return currentHead(inputs.base);
|
|
148
|
+
});
|
|
149
|
+
warnings.push(...inputs.warnings);
|
|
150
|
+
data = {
|
|
151
|
+
project: config.root, outputDirectory: output, complete: false,
|
|
152
|
+
base: { rev: inputs.base.rev, sha: inputs.base.sha }, current: { kind: 'working_tree', head },
|
|
153
|
+
selection: { sources: inputs.sources, frame: options.frame ?? null, themes, scale,
|
|
154
|
+
existingCoverage: !inputs.sources.length ? 'empty' : args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full' },
|
|
155
|
+
environment: { adg: metadata.version, node: process.version, platform: process.platform, arch: process.arch, chromium: null,
|
|
156
|
+
...metadata.dependencies, locale: 'en-US', timezone: 'UTC', ...inputs.environment, baseThresholds: inputs.before.config.diff.thresholds },
|
|
157
|
+
classifierVersion: 1, thresholds, comparisons: [], support: [], verdict: null, reasons: [],
|
|
158
|
+
summary: { sources: inputs.sources.length, frames: 0, comparisons: 0, supportComparisons: 0, isolationCaptures: 0,
|
|
159
|
+
added: 0, removed: 0, matched: 0, identical: 0, structural: 0, changed: 0,
|
|
160
|
+
classPixels: Object.fromEntries(classNames.map(name => [name, 0])) },
|
|
161
|
+
differencePalette: { equal: '#00000000', imperceptible: '#64748b', antialiasing: '#f59e0b', boundary_bleed: '#0ea5e9', bitmap_resampling: '#a855f7', other: '#ff00ff' }, reportPath: null, timings,
|
|
162
|
+
};
|
|
163
|
+
if (inputs.sources.length) browser = await launchBrowser();
|
|
164
|
+
const built = await timed('buildMs', () => inputs.buildFrames({ browser }));
|
|
165
|
+
context = partContext(built, inputs, scale, themes, clock);
|
|
166
|
+
for (const warning of inputs.warnings) if (!warnings.includes(warning)) warnings.push(warning);
|
|
167
|
+
data.summary.frames = built.frames.length;
|
|
168
|
+
for (const row of built.frames) data.summary[row.status]++;
|
|
169
|
+
if (!built.frames.length) emptySelection(warnings);
|
|
170
|
+
else browser ??= await launchBrowser();
|
|
171
|
+
if (browser) data.environment.chromium = browser.version();
|
|
172
|
+
const selectedOrder = new Map(built.frames.flatMap(row => themes.map(theme => comparisonIdentity(row, theme))).map((key, index) => [key, index]));
|
|
173
|
+
const supportKeys = new Set(built.support.map(frameIdentity));
|
|
174
|
+
const ordinary = [...built.frames.filter(row => !row.parentRow), ...built.support.map(row => ({ ...row, support: true }))];
|
|
175
|
+
const ordinaryJobs = ordinary.flatMap(row => themes.map(theme => ({ row, theme })));
|
|
176
|
+
const partJobs = built.frames.filter(row => row.parentRow).flatMap(row => themes.map(theme => ({ row, theme })));
|
|
177
|
+
const concurrency = Math.min(4, availableParallelism());
|
|
178
|
+
for (const jobs of [ordinaryJobs, partJobs]) for (let start = 0; start < jobs.length; start += concurrency) {
|
|
179
|
+
const failures = [], openPairs = [];
|
|
180
|
+
const phase = async (name, items, work) => {
|
|
181
|
+
const settled = await timed(name, () => Promise.allSettled(items.map(work)));
|
|
182
|
+
return settled.flatMap((result, index) => {
|
|
183
|
+
if (result.status === 'fulfilled') return [result.value];
|
|
184
|
+
failures.push({ index, error: result.reason });
|
|
185
|
+
return [];
|
|
186
|
+
});
|
|
187
|
+
};
|
|
188
|
+
try {
|
|
189
|
+
const batch = jobs.slice(start, start + concurrency);
|
|
190
|
+
openPairs.push(...await phase('captureMs', batch, job => job.row.parentRow
|
|
191
|
+
? browserTask(browser, () => capturePart(browser, job.row, job.theme, context)).catch(error => { throw frameFailure(error, job.row, job.theme); })
|
|
192
|
+
: capturePair(browser, job.row, job.theme, scale, context)));
|
|
193
|
+
const compared = await phase('compareMs', openPairs, pair => comparePair(browser, pair, thresholds, context));
|
|
194
|
+
const rows = await phase('writeMs', compared, pair => writePair(output, pair, thresholds));
|
|
195
|
+
for (const row of rows) {
|
|
196
|
+
context?.comparisons.set(comparisonIdentity(row, row.theme), row);
|
|
197
|
+
if (supportKeys.has(frameIdentity(row))) { data.support.push(row); data.summary.supportComparisons++; }
|
|
198
|
+
else {
|
|
199
|
+
completed.push(row); data.summary.comparisons++; data.summary[row.verdict]++;
|
|
200
|
+
for (const name of classNames) data.summary.classPixels[name] += row.pixels.classes[name].pixels;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
} finally {
|
|
204
|
+
for (const pair of openPairs) {
|
|
205
|
+
try { await cleanup(() => pair.page.close()); }
|
|
206
|
+
catch (error) { failures.push({ index: jobs.length, error }); }
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
data.comparisons = completed;
|
|
210
|
+
completed.sort((a, b) => selectedOrder.get(comparisonIdentity(a, a.theme)) - selectedOrder.get(comparisonIdentity(b, b.theme)));
|
|
211
|
+
data.summary.isolationCaptures = context?.isolation.size ?? 0;
|
|
212
|
+
if (failures.length) {
|
|
213
|
+
failures.sort((a, b) => a.index - b.index);
|
|
214
|
+
for (const item of failures.slice(1)) warnings.push(classifyError(item.error).error);
|
|
215
|
+
throw failures[0].error;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (inputs) {
|
|
220
|
+
if (error.message) error.message = inputs.translateDiagnostic(error.message);
|
|
221
|
+
if (error.context) error.context = inputs.translateDiagnostic(error.context);
|
|
222
|
+
if (error.warnings) error.warnings = inputs.translateDiagnostic(error.warnings);
|
|
223
|
+
}
|
|
224
|
+
primary = data ? commandFailure(error, data, warnings) : error;
|
|
225
|
+
} finally {
|
|
226
|
+
for (const close of [() => browser?.close(), () => inputs?.close()]) {
|
|
227
|
+
try { await cleanup(close, primary); }
|
|
228
|
+
catch (error) { primary = data ? commandFailure(error, data, warnings) : error; }
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (!data) throw primary;
|
|
232
|
+
data.complete = !primary;
|
|
233
|
+
if (!primary) {
|
|
234
|
+
data.verdict = data.summary.changed || data.support.some(row => row.verdict === 'changed') ? 'changed' : data.summary.structural ? 'structural' : 'identical';
|
|
235
|
+
data.reasons = [...new Set([...completed, ...data.support].flatMap(row => row.reasons))];
|
|
236
|
+
if (data.summary.structural && data.selection.existingCoverage !== 'full') {
|
|
237
|
+
data.verdict = 'changed'; data.reasons.push('existing_coverage_incomplete');
|
|
238
|
+
}
|
|
239
|
+
if (data.reasons.includes('existing_coverage_incomplete') || data.reasons.includes('theme_coverage_incomplete')) {
|
|
240
|
+
const next = nextActions('DIFF_FAILED', { command: 'diff', values: { ...options, frame: undefined, theme: 'both' }, positionals: [] }).map(action => ({ ...action, reason: 'Compare all existing frames in both themes before a structural batch verdict.' }));
|
|
241
|
+
warnings.push({ code: 'DIFF_COVERAGE_INCOMPLETE', message: 'A structural batch requires every existing frame in both themes.', next });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
timings.totalMs = performance.now() - started;
|
|
245
|
+
data.reportPath = path.join(output, 'report.json');
|
|
246
|
+
try {
|
|
247
|
+
await mkdir(output, { recursive: true });
|
|
248
|
+
await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
|
|
249
|
+
} catch (error) {
|
|
250
|
+
data.reportPath = null; data.complete = false; data.verdict = null;
|
|
251
|
+
if (primary) primary.warnings.push(classifyError(error).error);
|
|
252
|
+
else primary = commandFailure(error, data, warnings);
|
|
253
|
+
}
|
|
254
|
+
if (primary) throw primary;
|
|
255
|
+
if (!options.json) log(`${data.verdict}: ${data.summary.frames} frames. ${data.reportPath}`);
|
|
256
|
+
if (data.verdict === 'changed') throw new CliError('DIFF_FAILED', 'Design differences require review.', { data, warnings });
|
|
257
|
+
return { data, warnings };
|
|
258
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { loadTokens } from './project.mjs';
|
|
2
|
+
import { loadFrame, readyResources } from './browser.mjs';
|
|
3
|
+
import { collectPartSnapshot, normalizeSnapshot, snapshotFindings, settlePart } from './part-snapshot.mjs';
|
|
4
|
+
import { CliError } from '../cli-output.mjs';
|
|
5
|
+
import { cleanup } from './results.mjs';
|
|
6
|
+
|
|
7
|
+
export const frameIdentity = row => JSON.stringify([row.source, row.frame]);
|
|
8
|
+
export const comparisonIdentity = (row, theme) => JSON.stringify([row.source, row.frame, theme]);
|
|
9
|
+
|
|
10
|
+
export function partContext(built, inputs, scale, themes, clock) {
|
|
11
|
+
const parts = built.frames.filter(row => row.parentRow);
|
|
12
|
+
if (!parts.length) return null;
|
|
13
|
+
const targets = new Map();
|
|
14
|
+
for (const row of parts) {
|
|
15
|
+
const key = frameIdentity(row.parentRow), values = targets.get(key) ?? [];
|
|
16
|
+
if (!values.includes(row.after.parent.selector)) values.push(row.after.parent.selector);
|
|
17
|
+
targets.set(key, values);
|
|
18
|
+
}
|
|
19
|
+
const tokens = {};
|
|
20
|
+
for (const [side, config] of [['before', inputs.before.config], ['after', inputs.after.config]]) {
|
|
21
|
+
const parsed = loadTokens(config);
|
|
22
|
+
tokens[side] = Object.fromEntries(themes.map(theme => [theme, [...new Map([...parsed.light, ...(theme === 'dark' ? parsed.dark : [])])].sort(([a], [b]) => a.localeCompare(b))]));
|
|
23
|
+
}
|
|
24
|
+
return { targets, tokens, scale, themes, clock, parents: new Map(), comparisons: new Map(), isolation: new Map() };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function readSnapshot(page, args) {
|
|
28
|
+
const snapshot = await page.evaluate(collectPartSnapshot, args);
|
|
29
|
+
if (snapshot.referenceError) throw new CliError('DIFF_REFERENCE_INVALID', snapshot.referenceError);
|
|
30
|
+
if (snapshot.unsupported.length) {
|
|
31
|
+
const first = snapshot.unsupported[0];
|
|
32
|
+
throw new CliError('DIFF_SNAPSHOT_UNSUPPORTED', `${first.path}: ${first.property}: ${first.value}`);
|
|
33
|
+
}
|
|
34
|
+
return normalizeSnapshot(snapshot);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function captureEvidence(page, selectors, row, side, theme, context, capture) {
|
|
38
|
+
const read = () => Promise.all(selectors.map(selector => readSnapshot(page, { selector, tokens: context.tokens[side][theme], scale: context.scale, ref: { source: row.source, frame: row.frame }, theme })));
|
|
39
|
+
const { snapshot, png } = await settlePart(read, capture, {
|
|
40
|
+
now: context.clock?.now,
|
|
41
|
+
wait: context.clock?.wait ?? (() => page.evaluate(() => new Promise(requestAnimationFrame))),
|
|
42
|
+
});
|
|
43
|
+
return { png, targets: new Map(selectors.map((selector, index) => [selector, snapshot[index]])) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function capturePart(browser, row, theme, context) {
|
|
47
|
+
const parent = context.parents.get(comparisonIdentity(row.parentRow, theme));
|
|
48
|
+
const selector = row.after.parent.selector;
|
|
49
|
+
const beforeSnapshot = parent.before.targets.get(selector), parentCurrentSnapshot = parent.after.targets.get(selector);
|
|
50
|
+
const page = await browser.newPage({ deviceScaleFactor: context.scale, locale: 'en-US', timezoneId: 'UTC' });
|
|
51
|
+
try {
|
|
52
|
+
await loadFrame(page, row.after, theme);
|
|
53
|
+
await page.evaluate(readyResources);
|
|
54
|
+
const after = await captureEvidence(page, [null], row, 'after', theme, context, () => page.locator('[data-adg-frame]').screenshot({ animations: 'disabled', caret: 'hide' }));
|
|
55
|
+
const afterSnapshot = after.targets.get(null), findings = [
|
|
56
|
+
...snapshotFindings(beforeSnapshot, afterSnapshot),
|
|
57
|
+
...snapshotFindings(beforeSnapshot, parentCurrentSnapshot, 'parent'),
|
|
58
|
+
];
|
|
59
|
+
if (!afterSnapshot.frameAligned) findings.push({ code: 'PART_FRAME_GEOMETRY_CHANGED', kind: 'layout', path: 'part', property: 'frameAlignment', before: true, after: false });
|
|
60
|
+
if (beforeSnapshot.frameClipped || parentCurrentSnapshot.frameClipped) findings.push({ code: 'CLIPPING_CHANGED', kind: 'layout', path: 'parent', property: 'frameClipped', before: beforeSnapshot.frameClipped, after: parentCurrentSnapshot.frameClipped });
|
|
61
|
+
const beforeSize = beforeSnapshot.size;
|
|
62
|
+
const afterSize = { width: afterSnapshot.size.width, height: afterSnapshot.size.height, pixelWidth: after.png.readUInt32BE(16), pixelHeight: after.png.readUInt32BE(20) };
|
|
63
|
+
const currentRaster = new Set(afterSnapshot.rasterMask);
|
|
64
|
+
const edgeBoxes = [beforeSnapshot, afterSnapshot].flatMap(snapshot => snapshot.edgeBoxes.map(box => ({
|
|
65
|
+
x: box.x * context.scale + snapshot.fractionalOrigin.x, y: box.y * context.scale + snapshot.fractionalOrigin.y,
|
|
66
|
+
width: box.width * context.scale, height: box.height * context.scale,
|
|
67
|
+
})));
|
|
68
|
+
const supportRows = context.themes.map(theme => context.comparisons.get(comparisonIdentity(row.parentRow, theme)));
|
|
69
|
+
return { row, theme, page,
|
|
70
|
+
before: { png: parent.before.png, size: beforeSize }, after: { png: after.png, size: afterSize },
|
|
71
|
+
crop: beforeSnapshot.deviceCrop,
|
|
72
|
+
parent: { ref: { source: row.after.parent.source, frame: row.after.parent.frame }, selector,
|
|
73
|
+
cssCrop: beforeSnapshot.cssCrop, deviceCrop: beforeSnapshot.deviceCrop, fractionalOrigin: beforeSnapshot.fractionalOrigin,
|
|
74
|
+
clipping: { before: beforeSnapshot.contextEffects.clipping, current: parentCurrentSnapshot.contextEffects.clipping, after: afterSnapshot.contextEffects.clipping },
|
|
75
|
+
supportIds: supportRows.map(row => row.id) },
|
|
76
|
+
snapshots: { elementEqual: !findings.some(item => item.kind === 'element' || item.kind === 'resource'), layoutEqual: !findings.some(item => item.kind === 'layout'), colorEqual: !findings.some(item => item.kind === 'color'), findings },
|
|
77
|
+
snapshotFiles: { beforeSnapshot, afterSnapshot, parentCurrentSnapshot },
|
|
78
|
+
parentChanged: supportRows.some(row => row.verdict !== 'identical'),
|
|
79
|
+
singleTheme: context.themes.length !== 2,
|
|
80
|
+
evidence: { snapshotsMatch: !findings.length, rasterMask: beforeSnapshot.rasterMask.filter(pixel => currentRaster.has(pixel)), edgeBoxes },
|
|
81
|
+
};
|
|
82
|
+
} catch (error) { await cleanup(() => page.close(), error); throw error; }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function isolateParent(pair, context) {
|
|
86
|
+
const key = JSON.stringify([frameIdentity(pair.row.parentRow), pair.parent.selector, pair.theme]);
|
|
87
|
+
if (!context.isolation.has(key)) context.isolation.set(key, (async () => {
|
|
88
|
+
const page = pair.page, row = pair.row.parentRow;
|
|
89
|
+
await loadFrame(page, row.before, pair.theme);
|
|
90
|
+
await page.evaluate(readyResources);
|
|
91
|
+
const args = { selector: pair.parent.selector, tokens: context.tokens.before[pair.theme], scale: context.scale, ref: pair.parent.ref, theme: pair.theme };
|
|
92
|
+
const before = await readSnapshot(page, args);
|
|
93
|
+
if (snapshotFindings(pair.snapshotFiles.beforeSnapshot, before).length || JSON.stringify(before.deviceCrop) !== JSON.stringify(pair.crop)) throw new CliError('DIFF_UNSETTLED', 'The parent target changed before isolation.');
|
|
94
|
+
await page.evaluate(selector => {
|
|
95
|
+
const frame = document.querySelector('[data-adg-frame]'), target = frame.querySelector(selector);
|
|
96
|
+
window.__adgIsolation = [...frame.querySelectorAll('*')].filter(node => !target.contains(node) && !node.contains(target)).map(node => [node, node.getAttribute('style')]);
|
|
97
|
+
for (const [node] of window.__adgIsolation) node.style.setProperty('visibility', 'hidden', 'important');
|
|
98
|
+
}, pair.parent.selector);
|
|
99
|
+
let primary;
|
|
100
|
+
try {
|
|
101
|
+
const after = await readSnapshot(page, args);
|
|
102
|
+
if (snapshotFindings(before, after).length) throw new CliError('DIFF_UNSETTLED', 'Isolation changed the target snapshots.');
|
|
103
|
+
const png = await page.locator('[data-adg-frame]').screenshot({ animations: 'disabled', caret: 'hide' });
|
|
104
|
+
const captured = await readSnapshot(page, args);
|
|
105
|
+
if (snapshotFindings(after, captured).length) throw new CliError('DIFF_UNSETTLED', 'The target changed during isolation capture.');
|
|
106
|
+
return png;
|
|
107
|
+
} catch (error) { primary = error; throw error; }
|
|
108
|
+
finally {
|
|
109
|
+
await cleanup(() => page.evaluate(() => {
|
|
110
|
+
for (const [node, style] of window.__adgIsolation) {
|
|
111
|
+
if (style === null) node.removeAttribute('style'); else node.setAttribute('style', style);
|
|
112
|
+
}
|
|
113
|
+
delete window.__adgIsolation;
|
|
114
|
+
}), primary);
|
|
115
|
+
}
|
|
116
|
+
})());
|
|
117
|
+
return context.isolation.get(key);
|
|
118
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { CliError } from '../cli-output.mjs';
|
|
3
|
+
|
|
4
|
+
/** Runs only in pages contributing part evidence. */
|
|
5
|
+
export async function collectPartSnapshot({ selector, tokens, scale, ref, theme }) {
|
|
6
|
+
const frame = document.querySelector('[data-adg-frame]');
|
|
7
|
+
let roots;
|
|
8
|
+
try { roots = selector === null ? [...frame.children] : [...frame.querySelectorAll(selector)]; }
|
|
9
|
+
catch { return { referenceError: `Invalid parent selector ${selector}.` }; }
|
|
10
|
+
if (roots.length !== 1) return { referenceError: `Expected one target for ${selector ?? 'the part root'}, found ${roots.length}.` };
|
|
11
|
+
const root = roots[0], origin = root.getBoundingClientRect(), frameBox = frame.getBoundingClientRect();
|
|
12
|
+
if (!origin.width || !origin.height || getComputedStyle(root).visibility !== 'visible') return { referenceError: 'The parent/part target must be visible.' };
|
|
13
|
+
const clean = number => number === 0 ? 0 : number;
|
|
14
|
+
const box = rect => ({ x: clean(rect.x - origin.x), y: clean(rect.y - origin.y), width: rect.width, height: rect.height });
|
|
15
|
+
const cssCrop = { x: origin.x - frameBox.x, y: origin.y - frameBox.y, width: origin.width, height: origin.height };
|
|
16
|
+
const left = Math.floor(cssCrop.x * scale), top = Math.floor(cssCrop.y * scale);
|
|
17
|
+
const deviceCrop = { x: left, y: top, width: Math.ceil((cssCrop.x + origin.width) * scale) - left, height: Math.ceil((cssCrop.y + origin.height) * scale) - top };
|
|
18
|
+
const fractionalOrigin = { x: cssCrop.x * scale - left, y: cssCrop.y * scale - top };
|
|
19
|
+
const nodes = [root, ...root.querySelectorAll('*')], paths = new Map(nodes.map((node, index) => [node, String(index)]));
|
|
20
|
+
const ids = new Map(nodes.filter(node => node.id).map(node => [node.id, `node-${paths.get(node)}`]));
|
|
21
|
+
const unsupported = [], resources = [], resourceCache = new Map(), decoded = new Map();
|
|
22
|
+
const internalIds = value => value.replace(/url\(["']?#([^)'"\s]+)["']?\)/g, (_, id) => `url(#${ids.get(id) ?? id})`);
|
|
23
|
+
const resource = async url => {
|
|
24
|
+
if (resourceCache.has(url)) return resourceCache.get(url);
|
|
25
|
+
let content = url;
|
|
26
|
+
if (!url.startsWith('data:')) {
|
|
27
|
+
try {
|
|
28
|
+
const response = await fetch(url);
|
|
29
|
+
if (!response.ok) throw Error(`HTTP ${response.status}`);
|
|
30
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
31
|
+
let binary = '';
|
|
32
|
+
for (let offset = 0; offset < bytes.length; offset += 8192) binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
|
|
33
|
+
content = `data:${response.headers.get('content-type') ?? ''};base64,${btoa(binary)}`;
|
|
34
|
+
} catch { unsupported.push({ path: 'resources', property: 'bytes', value: url }); }
|
|
35
|
+
}
|
|
36
|
+
const id = `resource-${resources.length}`;
|
|
37
|
+
const kind = /^data:image\/svg\+xml/i.test(content) ? 'vector' : /^data:(?:image\/|application\/octet-stream)/i.test(content) ? 'raster' : 'font';
|
|
38
|
+
const entry = { id, source: url.startsWith('data:') ? `embedded:${kind}` : url, kind, contentIdentity: content, intrinsicWidth: null, intrinsicHeight: null };
|
|
39
|
+
if (kind === 'raster') {
|
|
40
|
+
const comma = content.indexOf(',');
|
|
41
|
+
const bytes = content.slice(0, comma).includes(';base64') ? atob(content.slice(comma + 1)) : decodeURIComponent(content.slice(comma + 1));
|
|
42
|
+
if (bytes.startsWith('GIF8') && /NETSCAPE2\.0|ANIMEXTS1\.0/.test(bytes) || bytes.startsWith('\x89PNG') && bytes.includes('acTL') || bytes.startsWith('RIFF') && bytes.includes('ANIM')) unsupported.push({ path: 'resources', property: 'paint', value: 'animated raster' });
|
|
43
|
+
}
|
|
44
|
+
resources.push(entry); resourceCache.set(url, entry);
|
|
45
|
+
return entry;
|
|
46
|
+
};
|
|
47
|
+
const normalizeStyle = async style => {
|
|
48
|
+
const values = {};
|
|
49
|
+
for (const property of [...style].sort()) {
|
|
50
|
+
let value = internalIds(style.getPropertyValue(property));
|
|
51
|
+
if (/url\(/.test(value)) {
|
|
52
|
+
for (const match of [...value.matchAll(/url\(["']?([^)'"\s]+)["']?\)/g)]) {
|
|
53
|
+
if (match[1].startsWith('#')) continue;
|
|
54
|
+
const entry = await resource(match[1]);
|
|
55
|
+
value = value.replace(match[0], `url(${entry.id})`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
values[property] = value;
|
|
59
|
+
}
|
|
60
|
+
return values;
|
|
61
|
+
};
|
|
62
|
+
const inspectPaint = (style, path) => {
|
|
63
|
+
for (const property of ['filter', 'backdrop-filter', 'clip-path', 'mask-image', 'mix-blend-mode', 'perspective']) {
|
|
64
|
+
const value = style.getPropertyValue(property);
|
|
65
|
+
if (value && !['none', 'normal'].includes(value)) unsupported.push({ path, property, value });
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const paintProperty = property => /color|background|fill|stroke|shadow|opacity|filter|blend|mask|clip-path/.test(property);
|
|
69
|
+
const ignored = /^(?:--|animation|transition|cursor$|pointer-events$|user-select$|touch-action$|scroll-behavior$|caret-color$)/;
|
|
70
|
+
const tokenRules = [];
|
|
71
|
+
const visitRules = rules => {
|
|
72
|
+
for (const rule of rules) {
|
|
73
|
+
if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
|
|
74
|
+
if (rule.selectorText && rule.style) tokenRules.push(rule);
|
|
75
|
+
if (rule.cssRules) visitRules(rule.cssRules);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
for (const sheet of document.styleSheets) visitRules(sheet.cssRules);
|
|
79
|
+
const elements = [], texts = [], rasters = [], edgeBoxes = [];
|
|
80
|
+
for (const node of nodes) {
|
|
81
|
+
const path = paths.get(node), style = getComputedStyle(node), rect = node.getBoundingClientRect();
|
|
82
|
+
inspectPaint(style, path);
|
|
83
|
+
if (node.matches('canvas,video,object,embed,foreignObject')) unsupported.push({ path, property: 'paint', value: node.localName });
|
|
84
|
+
const computedStyle = await normalizeStyle(style), layout = {}, paint = {};
|
|
85
|
+
for (const [property, value] of Object.entries(computedStyle)) {
|
|
86
|
+
if (!ignored.test(property)) (paintProperty(property) ? paint : layout)[property] = value;
|
|
87
|
+
}
|
|
88
|
+
const attributes = {};
|
|
89
|
+
for (const attr of [...node.attributes].sort((a, b) => a.name.localeCompare(b.name))) {
|
|
90
|
+
if (['class', 'style', 'id'].includes(attr.name) || attr.name.startsWith('data-')) continue;
|
|
91
|
+
let value = internalIds(attr.value);
|
|
92
|
+
if (['src', 'href', 'xlink:href'].includes(attr.name) && !value.startsWith('#') && node.matches('img,image')) value = (await resource(value)).id;
|
|
93
|
+
if (value.startsWith('#') && ids.has(value.slice(1))) value = `#${ids.get(value.slice(1))}`;
|
|
94
|
+
attributes[attr.name] = value;
|
|
95
|
+
}
|
|
96
|
+
if (node.matches('input,textarea,select')) {
|
|
97
|
+
attributes.value = node.value;
|
|
98
|
+
if ('checked' in node) attributes.checked = String(node.checked);
|
|
99
|
+
}
|
|
100
|
+
for (const property of [...node.style].filter(name => name.startsWith('--'))) layout[property] = node.style.getPropertyValue(property);
|
|
101
|
+
const tokenExpressions = [];
|
|
102
|
+
for (const declaration of [...tokenRules.filter(rule => { try { return node.matches(rule.selectorText); } catch { return false; } }).map(rule => rule.style), node.style]) {
|
|
103
|
+
for (const property of declaration) {
|
|
104
|
+
const expression = declaration.getPropertyValue(property);
|
|
105
|
+
if (property.startsWith('--') || expression.includes('var(')) tokenExpressions.push({ property, expression, resolved: style.getPropertyValue(property) });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const pseudo = {};
|
|
109
|
+
for (const name of ['before', 'after']) {
|
|
110
|
+
const style = getComputedStyle(node, `::${name}`);
|
|
111
|
+
pseudo[name] = ['none', 'normal'].includes(style.content) ? null : { content: style.content, computedStyle: await normalizeStyle(style) };
|
|
112
|
+
if (pseudo[name]) inspectPaint(style, `${path}::${name}`);
|
|
113
|
+
if (/counter\(|attr\(/.test(style.content)) unsupported.push({ path, property: 'content', value: style.content });
|
|
114
|
+
}
|
|
115
|
+
elements.push({ path, parentPath: node === root ? null : paths.get(node.parentElement), tag: node.localName, namespace: node.namespaceURI,
|
|
116
|
+
attributes, childOrder: [...node.childNodes].filter(child => child.nodeType === 1 || child.nodeType === 3 && child.textContent.trim()).map((child, index) => child.nodeType === 1 ? paths.get(child) : `${path}/text-${index}`),
|
|
117
|
+
box: box(rect), clientRects: [...node.getClientRects()].map(box), layout, paint, computedStyle, pseudo, tokenExpressions,
|
|
118
|
+
owners: JSON.parse(node.getAttribute('data-adg-owners') ?? '[]') });
|
|
119
|
+
for (const [index, child] of [...node.childNodes].entries()) {
|
|
120
|
+
if (child.nodeType !== 3 || !child.textContent.trim()) continue;
|
|
121
|
+
const range = document.createRange(); range.selectNodeContents(child);
|
|
122
|
+
const lines = [...range.getClientRects()].map(rect => ({ text: child.textContent, box: box(rect) }));
|
|
123
|
+
texts.push({ path: `${path}/text-${index}`, parentPath: path, text: child.textContent, lines });
|
|
124
|
+
edgeBoxes.push(...lines.map(line => line.box));
|
|
125
|
+
}
|
|
126
|
+
if (node instanceof SVGElement && /^(path|rect|circle|ellipse|polygon|polyline|line|text)$/.test(node.localName) || parseFloat(style.borderTopWidth) || parseFloat(style.borderRadius)) edgeBoxes.push(box(rect));
|
|
127
|
+
if (!node.matches('img,image')) continue;
|
|
128
|
+
const url = node.currentSrc || node.getAttribute('href') || node.getAttribute('xlink:href') || node.getAttribute('src');
|
|
129
|
+
if (!url) continue;
|
|
130
|
+
const entry = await resource(url);
|
|
131
|
+
let image = decoded.get(url);
|
|
132
|
+
if (!image) {
|
|
133
|
+
image = new Image(); image.src = url;
|
|
134
|
+
await image.decode(); decoded.set(url, image);
|
|
135
|
+
}
|
|
136
|
+
entry.intrinsicWidth = image.naturalWidth; entry.intrinsicHeight = image.naturalHeight;
|
|
137
|
+
if (entry.kind === 'raster' && style.display !== 'none' && style.visibility === 'visible' && Number(style.opacity) > 0) {
|
|
138
|
+
const transform = node instanceof SVGElement ? node.getScreenCTM() : new DOMMatrixReadOnly(style.transform === 'none' ? undefined : style.transform);
|
|
139
|
+
if (transform && (transform.b || transform.c || transform.a <= 0 || transform.d <= 0)) unsupported.push({ path, property: 'raster-transform', value: style.transform });
|
|
140
|
+
rasters.push({ node, path, box: box(rect) });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
for (const sheet of document.styleSheets) for (const rule of sheet.cssRules) {
|
|
144
|
+
if (rule.type !== CSSRule.FONT_FACE_RULE) continue;
|
|
145
|
+
for (const match of rule.style.src.matchAll(/url\(["']?([^)'"\s]+)["']?\)/g)) await resource(match[1]);
|
|
146
|
+
}
|
|
147
|
+
let visible = { left: Math.max(origin.left, frameBox.left), top: Math.max(origin.top, frameBox.top), right: Math.min(origin.right, frameBox.right), bottom: Math.min(origin.bottom, frameBox.bottom) };
|
|
148
|
+
const compositing = {}, backgrounds = [], clipShapes = [];
|
|
149
|
+
for (let parent = root.parentElement; parent; parent = parent.parentElement) {
|
|
150
|
+
const style = getComputedStyle(parent), rect = parent.getBoundingClientRect();
|
|
151
|
+
inspectPaint(style, 'ancestor');
|
|
152
|
+
if (style.transform !== 'none') {
|
|
153
|
+
const matrix = new DOMMatrixReadOnly(style.transform);
|
|
154
|
+
if (!matrix.is2D || matrix.a !== 1 || matrix.b || matrix.c || matrix.d !== 1) unsupported.push({ path: 'ancestor', property: 'transform', value: style.transform });
|
|
155
|
+
}
|
|
156
|
+
if (style.opacity !== '1') compositing.opacity = String(Number(compositing.opacity ?? 1) * Number(style.opacity));
|
|
157
|
+
if (style.backgroundColor !== 'rgba(0, 0, 0, 0)') backgrounds.push(style.backgroundColor);
|
|
158
|
+
if (style.backgroundImage !== 'none') {
|
|
159
|
+
compositing.backgroundImages ??= [];
|
|
160
|
+
compositing.backgroundImages.push({ box: box(rect), value: (await normalizeStyle(style))['background-image'] });
|
|
161
|
+
}
|
|
162
|
+
if (style.boxShadow !== 'none') {
|
|
163
|
+
compositing.shadows ??= [];
|
|
164
|
+
compositing.shadows.push({ box: box(rect), value: style.boxShadow });
|
|
165
|
+
}
|
|
166
|
+
if (/(hidden|clip|auto|scroll)/.test(style.overflowX + style.overflowY)) {
|
|
167
|
+
const radii = ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-left-radius', 'border-bottom-right-radius'].map(name => style.getPropertyValue(name));
|
|
168
|
+
if (radii.some(radius => parseFloat(radius))) clipShapes.push({ box: box(rect), radii });
|
|
169
|
+
}
|
|
170
|
+
if (/(hidden|clip|auto|scroll)/.test(style.overflowX)) { visible.left = Math.max(visible.left, rect.left + parent.clientLeft); visible.right = Math.min(visible.right, rect.left + parent.clientLeft + parent.clientWidth); }
|
|
171
|
+
if (/(hidden|clip|auto|scroll)/.test(style.overflowY)) { visible.top = Math.max(visible.top, rect.top + parent.clientTop); visible.bottom = Math.min(visible.bottom, rect.top + parent.clientTop + parent.clientHeight); }
|
|
172
|
+
}
|
|
173
|
+
const clipped = visible.left > origin.left || visible.top > origin.top || visible.right < origin.right || visible.bottom < origin.bottom;
|
|
174
|
+
const clipping = clipped ? [{ x: visible.left - origin.left, y: visible.top - origin.top, width: Math.max(0, visible.right - visible.left), height: Math.max(0, visible.bottom - visible.top) }] : [];
|
|
175
|
+
const backgroundCanvas = document.createElement('canvas'); backgroundCanvas.width = backgroundCanvas.height = 1;
|
|
176
|
+
const backgroundContext = backgroundCanvas.getContext('2d');
|
|
177
|
+
for (const color of backgrounds.reverse()) { backgroundContext.fillStyle = color; backgroundContext.fillRect(0, 0, 1, 1); }
|
|
178
|
+
const backdrop = [...backgroundContext.getImageData(0, 0, 1, 1).data].join(',');
|
|
179
|
+
const rasterMask = [];
|
|
180
|
+
if (rasters.length) {
|
|
181
|
+
const restored = nodes.map(node => [node, node.getAttribute('style')]);
|
|
182
|
+
const inert = new Map(nodes.filter(node => node.hasAttribute('inert')).map(node => [node, node.getAttribute('inert')]));
|
|
183
|
+
for (let node = root; node; node = node.parentElement) if (node.hasAttribute('inert')) inert.set(node, node.getAttribute('inert'));
|
|
184
|
+
for (const [node] of inert) node.removeAttribute('inert');
|
|
185
|
+
try {
|
|
186
|
+
for (const node of nodes) node.style.setProperty('pointer-events', 'auto', 'important');
|
|
187
|
+
for (const raster of rasters) {
|
|
188
|
+
const r = raster.box;
|
|
189
|
+
const x0 = Math.max(0, Math.floor(r.x * scale + fractionalOrigin.x)), y0 = Math.max(0, Math.floor(r.y * scale + fractionalOrigin.y));
|
|
190
|
+
const x1 = Math.min(deviceCrop.width, Math.ceil((r.x + r.width) * scale + fractionalOrigin.x)), y1 = Math.min(deviceCrop.height, Math.ceil((r.y + r.height) * scale + fractionalOrigin.y));
|
|
191
|
+
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
|
|
192
|
+
const stack = document.elementsFromPoint(frameBox.x + (left + x + 0.5) / scale, frameBox.y + (top + y + 0.5) / scale);
|
|
193
|
+
if (stack[0] === raster.node) rasterMask.push(y * deviceCrop.width + x);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
} finally {
|
|
197
|
+
for (const [node, style] of restored) { node.getAttribute('style'); if (style === null) node.removeAttribute('style'); else node.setAttribute('style', style); }
|
|
198
|
+
for (const [node, value] of inert) node.setAttribute('inert', value);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return { snapshotVersion: 1, ref, theme, size: { width: origin.width, height: origin.height, pixelWidth: deviceCrop.width, pixelHeight: deviceCrop.height },
|
|
202
|
+
origin: { x: origin.x, y: origin.y }, elements, texts,
|
|
203
|
+
tokens: tokens.map(([name, declaration]) => ({ name, declaration, resolved: getComputedStyle(root).getPropertyValue(name).trim() })), resources,
|
|
204
|
+
contextEffects: { clipping, clipShapes, compositing, backdrop },
|
|
205
|
+
cssCrop, deviceCrop, fractionalOrigin, clipped,
|
|
206
|
+
frameClipped: origin.left < frameBox.left || origin.top < frameBox.top || origin.right > frameBox.right || origin.bottom > frameBox.bottom,
|
|
207
|
+
edgeBoxes, rasterMask, unsupported,
|
|
208
|
+
frameAligned: selector !== null || cssCrop.x === 0 && cssCrop.y === 0 && origin.width === frameBox.width && origin.height === frameBox.height };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function normalizeSnapshot(snapshot) {
|
|
212
|
+
for (const resource of snapshot.resources) {
|
|
213
|
+
let content = resource.contentIdentity;
|
|
214
|
+
if (content.startsWith('data:')) {
|
|
215
|
+
const comma = content.indexOf(',');
|
|
216
|
+
content = content.slice(0, comma).includes(';base64') ? Buffer.from(content.slice(comma + 1), 'base64') : Buffer.from(decodeURIComponent(content.slice(comma + 1)));
|
|
217
|
+
}
|
|
218
|
+
resource.contentIdentity = createHash('sha256').update(content).digest('hex');
|
|
219
|
+
}
|
|
220
|
+
return snapshot;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function snapshotFindings(before, after, context = 'part') {
|
|
224
|
+
const findings = [];
|
|
225
|
+
const compare = (a, b, path, kind, code) => {
|
|
226
|
+
if (JSON.stringify(a) === JSON.stringify(b)) return;
|
|
227
|
+
if (a && b && typeof a === 'object' && typeof b === 'object') {
|
|
228
|
+
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) compare(a[key], b[key], `${path}.${key}`, kind, code);
|
|
229
|
+
} else findings.push({ code, kind, path: context, property: path, before: a ?? null, after: b ?? null });
|
|
230
|
+
};
|
|
231
|
+
compare(before.tokens, after.tokens, 'tokens', 'color', 'TOKEN_CHANGED');
|
|
232
|
+
compare(before.resources, after.resources, 'resources', 'resource', 'RESOURCE_CHANGED');
|
|
233
|
+
compare(before.contextEffects.clipping, after.contextEffects.clipping, 'clipping', 'layout', 'CLIPPING_CHANGED');
|
|
234
|
+
compare(before.contextEffects.clipShapes, after.contextEffects.clipShapes, 'clipShapes', 'layout', 'CLIPPING_CHANGED');
|
|
235
|
+
compare(before.contextEffects.compositing, after.contextEffects.compositing, 'compositing', 'color', 'COLOR_CHANGED');
|
|
236
|
+
compare(before.contextEffects.backdrop, after.contextEffects.backdrop, 'backdrop', 'color', 'COLOR_CHANGED');
|
|
237
|
+
const count = Math.max(before.elements.length, after.elements.length);
|
|
238
|
+
for (let index = 0; index < count; index++) {
|
|
239
|
+
const a = before.elements[index], b = after.elements[index];
|
|
240
|
+
if (!a || !b) { findings.push({ code: a ? 'ELEMENT_REMOVED' : 'ELEMENT_ADDED', kind: 'element', path: context, property: `elements.${index}`, before: a ?? null, after: b ?? null }); continue; }
|
|
241
|
+
for (const property of ['tag', 'namespace', 'attributes', 'childOrder']) compare(a[property], b[property], `elements.${index}.${property}`, 'element', 'ELEMENT_CHANGED');
|
|
242
|
+
for (const property of ['box', 'clientRects', 'layout']) compare(a[property], b[property], `elements.${index}.${property}`, 'layout', 'LAYOUT_CHANGED');
|
|
243
|
+
compare(a.paint, b.paint, `elements.${index}.paint`, 'color', 'COLOR_CHANGED');
|
|
244
|
+
compare(a.pseudo, b.pseudo, `elements.${index}.pseudo`, 'element', 'ELEMENT_CHANGED');
|
|
245
|
+
}
|
|
246
|
+
compare(before.texts, after.texts, 'texts', 'element', 'TEXT_CHANGED');
|
|
247
|
+
return findings;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Two equal observations and an unchanged post-capture observation share one deadline. */
|
|
251
|
+
export async function settlePart(read, capture, { now = () => performance.now(), wait = () => new Promise(resolve => setTimeout(resolve, 0)) } = {}) {
|
|
252
|
+
const start = now();
|
|
253
|
+
let previous;
|
|
254
|
+
for (;;) {
|
|
255
|
+
const snapshot = await read(), state = JSON.stringify(snapshot);
|
|
256
|
+
if (state === previous) {
|
|
257
|
+
const png = await capture(), after = await read();
|
|
258
|
+
if (JSON.stringify(after) === state && now() - start < 5000) return { snapshot: after, png };
|
|
259
|
+
previous = JSON.stringify(after);
|
|
260
|
+
} else previous = state;
|
|
261
|
+
if (now() - start >= 5000) throw new CliError('DIFF_UNSETTLED', 'Part snapshots did not settle within five seconds.');
|
|
262
|
+
await wait();
|
|
263
|
+
}
|
|
264
|
+
}
|