Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | 1x 1x 1x 10x 9x 7x 6x 2x 4x 3x 1x 1x | import { Page } from '@playwright/test';
import { StyleDiff } from './flow';
import { isUntestableSelector } from './css-diff';
// Pixel diff of two screenshots, done entirely in the browser (canvas decode/compare/paint) so no Node-side image libraries are needed.
export interface DiffResult {
// Pixels that differ between A and B (above the per-channel threshold).
changedPixels: number;
totalPixels: number;
// changedPixels / totalPixels, 0..1.
ratio: number;
// PNG highlighting changed pixels in magenta over a dimmed copy of B; null if shot dimensions differ.
diffPng: Buffer | null;
// Compared canvas size (shared by both shots when dimensions match); zero on mismatch.
width: number;
height: number;
// Set when A and B differ in dimensions (page reflowed; can't diff pixel-for-pixel).
dimensionMismatch?: { a: [number, number]; b: [number, number] };
}
// threshold: per-channel delta (0..255) below which a pixel counts as unchanged, to swallow antialiasing jitter between captures.
export async function diffScreenshots(
page: Page,
shotA: Buffer,
shotB: Buffer,
threshold = 16,
): Promise<DiffResult> {
const a64 = shotA.toString('base64');
const b64 = shotB.toString('base64');
// Serialized into the browser via page.evaluate, so it must be self-contained with no nested named functions —
// esbuild's keepNames transform wraps them in a `__name` helper that doesn't exist in the page context.
const result = await page.evaluate(
async ({ a64, b64, threshold }) => {
const imgA = new Image();
await new Promise<void>((res, rej) => {
imgA.onload = () => res();
imgA.onerror = () => rej(new Error('failed to decode shot A'));
imgA.src = `data:image/png;base64,${a64}`;
});
const ca = document.createElement('canvas');
ca.width = imgA.naturalWidth;
ca.height = imgA.naturalHeight;
ca.getContext('2d')!.drawImage(imgA, 0, 0);
const imgB = new Image();
await new Promise<void>((res, rej) => {
imgB.onload = () => res();
imgB.onerror = () => rej(new Error('failed to decode shot B'));
imgB.src = `data:image/png;base64,${b64}`;
});
const cb = document.createElement('canvas');
cb.width = imgB.naturalWidth;
cb.height = imgB.naturalHeight;
cb.getContext('2d')!.drawImage(imgB, 0, 0);
if (ca.width !== cb.width || ca.height !== cb.height) {
return {
changedPixels: 0,
totalPixels: 0,
ratio: 0,
width: 0,
height: 0,
diffDataUrl: null,
dimensionMismatch: {
a: [ca.width, ca.height] as [number, number],
b: [cb.width, cb.height] as [number, number],
},
};
}
const w = cb.width;
const h = cb.height;
const da = ca.getContext('2d')!.getImageData(0, 0, w, h);
const db = cb.getContext('2d')!.getImageData(0, 0, w, h);
const out = document.createElement('canvas');
out.width = w;
out.height = h;
const octx = out.getContext('2d')!;
const diff = octx.createImageData(w, h);
let changed = 0;
for (let i = 0; i < da.data.length; i += 4) {
const dr = Math.abs(da.data[i] - db.data[i]);
const dg = Math.abs(da.data[i + 1] - db.data[i + 1]);
const dbl = Math.abs(da.data[i + 2] - db.data[i + 2]);
if (dr > threshold || dg > threshold || dbl > threshold) {
// Changed → solid magenta.
diff.data[i] = 255;
diff.data[i + 1] = 0;
diff.data[i + 2] = 255;
diff.data[i + 3] = 255;
changed++;
} else {
// Unchanged → dimmed grayscale of shot B for context.
const gray = (db.data[i] + db.data[i + 1] + db.data[i + 2]) / 3;
const dim = 200 + gray * 0.2;
diff.data[i] = dim;
diff.data[i + 1] = dim;
diff.data[i + 2] = dim;
diff.data[i + 3] = 255;
}
}
octx.putImageData(diff, 0, 0);
return {
changedPixels: changed,
totalPixels: (da.data.length / 4) | 0,
ratio: changed / (da.data.length / 4),
width: w,
height: h,
diffDataUrl: out.toDataURL('image/png'),
dimensionMismatch: undefined as { a: [number, number]; b: [number, number] } | undefined,
};
},
{ a64, b64, threshold },
);
const diffPng = result.diffDataUrl
? Buffer.from(result.diffDataUrl.replace(/^data:image\/png;base64,/, ''), 'base64')
: null;
return {
changedPixels: result.changedPixels,
totalPixels: result.totalPixels,
ratio: result.ratio,
width: result.width,
height: result.height,
diffPng,
dimensionMismatch: result.dimensionMismatch,
};
}
// --- Computed-style diff ----------------------------------------------------
// Component name -> selector matching its elements. Used to attribute a changed element to a component.
export const COMPONENT_SELECTORS: Record<string, string> = {
Accordion: '.slds-accordion',
Avatar: '.slds-avatar',
Badge: '.slds-badge',
Breadcrumbs: '.slds-breadcrumb',
'Button Brand': '.slds-button_brand',
'Button Group': '.slds-button-group, .slds-button-group-list',
'Button Icon': '.slds-button_icon, .slds-button__icon',
Card: '.slds-card',
Checkbox: '.slds-checkbox',
'Color Picker': '.slds-color-picker',
Combobox: '.slds-combobox',
'Data Table': '.slds-table',
Datepicker: '.slds-datepicker',
'Docked Form Footer': '.slds-docked-form-footer',
'Dropdown Menu': '.slds-dropdown',
'Dueling Picklist': '.slds-dueling-list',
'File Selector': '.slds-file-selector',
'Form Element': '.slds-form-element',
'Global Navigation': '.slds-context-bar',
Illustration: '.slds-illustration',
Input: '.slds-input',
'Input Error': '.slds-has-error',
Modal: '.slds-modal',
'Button Neutral': '.slds-button_neutral',
'Page Header': '.slds-page-header',
Path: '.slds-path',
Popover: '.slds-popover',
'Popover Error': '.slds-popover_error',
'Progress Bar': '.slds-progress-bar',
'Progress Indicator': '.slds-progress',
'Progress Ring': '.slds-progress-ring',
Radio: '.slds-radio',
Select: '.slds-select',
Tabs: '[class*="slds-tabs"]',
Textarea: '.slds-textarea',
Tile: '.slds-tile',
Timepicker: '.slds-timepicker',
Toast: '.slds-notify_toast',
Toggle: '.slds-checkbox_toggle',
Tree: '.slds-tree',
'Utility Bar': '.slds-utility-bar, [class*="utilityBar"]',
'Vertical Navigation': '.slds-nav-vertical',
'Visual Picker': '.slds-visual-picker',
'Welcome Mat': '.slds-welcome-mat',
};
// In-page code is passed as strings: tsx's keepNames injects __name helpers that don't exist in the page.
const SNAPSHOT = (slot: string) => `(() => {
const SKIP = new Set(['SCRIPT','STYLE','META','LINK','HEAD','TITLE','NOSCRIPT','TEMPLATE','BASE']);
const els = [];
const stack = [document];
while (stack.length) {
const root = stack.pop();
for (const el of root.querySelectorAll('*')) {
if (!SKIP.has(el.tagName)) els.push(el);
if (el.shadowRoot) stack.push(el.shadowRoot);
}
}
// Jump in-flight transitions to their end, else a read right after a CSS swap sees the old value as drift.
// document.getAnimations() already covers shadow trees; ShadowRoot.getAnimations is missing in Lightning's synthetic shadow.
try {
for (const anim of document.getAnimations()) {
// One animation that can't finish shouldn't block the rest.
try { if (anim.effect.getComputedTiming().iterations !== Infinity) anim.finish(); } catch (e) {}
}
} catch (e) {
// Best-effort: without it, the C re-read still subtracts in-flight values as drift.
}
// Standard props only, read by name: inherited --custom props multiply the cost and surface via the props they feed.
const names = Array.from(getComputedStyle(document.documentElement)).filter((n) => !n.startsWith('--'));
const read = (cs) => names.map((n) => cs.getPropertyValue(n));
const pseudo = (el, p) => { const cs = getComputedStyle(el, p); const c = cs.content; return c && c !== 'none' && c !== 'normal' ? read(cs) : null; };
const vals = els.map((el) => {
const cs = getComputedStyle(el);
return { e: read(cs), b: pseudo(el, '::before'), a: pseudo(el, '::after') };
});
window.__vrtSnaps = window.__vrtSnaps || {};
window.__vrtSnaps[${JSON.stringify(slot)}] = { els, names, vals };
return els.length;
})()`;
const COMPARE = (components: Record<string, string>, rules: Record<string, string[]>) => `(() => {
const S = window.__vrtSnaps || {};
const A = S.A, B = S.B, C = S.C;
delete window.__vrtSnaps;
const none = { comparable: false, total: 0, listed: 0, shifted: 0, components: [], elements: [] };
if (!A || !B || A.els.length !== B.els.length) return none;
for (let i = 0; i < A.els.length; i++) if (A.els[i].tagName !== B.els[i].tagName) return none;
const COMPONENTS = ${JSON.stringify(components)};
const RULE_PROPS = ${JSON.stringify(rules)};
const RULES = Object.keys(RULE_PROPS);
// The PR's changed selectors this element matches, so the report can show the authored declaration.
const matchedRules = (el) => RULES.filter((r) => { try { return el.matches(r); } catch (e) { return false; } });
// Origins depend on box size, so they only echo a size change already reported elsewhere.
const IGN = new Set(['transform-origin', 'perspective-origin']);
const cut = (v) => String(v).slice(0, 60);
const describe = (el) => {
const cls = String(el.getAttribute('class') || '').split(/\\s+/).filter(Boolean).slice(0, 3).join('.');
return el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (cls ? '.' + cls : '');
};
// A vs a later re-read of A: anything that moves with identical CSS is runtime drift (scroll, toasts), not the bundle.
const drift = new Set();
if (C && C.els.length === A.els.length) {
for (let i = 0; i < A.els.length; i++) {
for (const key of ['e', 'b', 'a']) {
const x = A.vals[i][key], y = C.vals[i][key];
if (!x || !y) continue;
for (let k = 0; k < x.length; k++) if (x[k] !== y[k]) drift.add(i + '|' + key + '|' + k);
}
}
}
// Size/position props are layout results: when an element only changes these, it was pushed by a change elsewhere.
const GEOM = new Set(['width', 'height', 'block-size', 'inline-size', 'top', 'right', 'bottom', 'left',
'inset-block-start', 'inset-block-end', 'inset-inline-start', 'inset-inline-end',
'grid-template-rows', 'grid-template-columns']);
// Innermost component wins: walk up (across shadow roots) to the first node matching any component.
const owner = (el) => {
for (let n = el; n; n = n.parentElement || (n.getRootNode() && n.getRootNode().host)) {
const hit = [];
for (const name of Object.keys(COMPONENTS)) {
try { if (n.matches(COMPONENTS[name])) hit.push(name); } catch (e) {}
}
if (hit.length) return hit;
}
return [];
};
const parts = [['e', ''], ['b', '::before '], ['a', '::after ']];
const changed = [];
for (let i = 0; i < A.els.length; i++) {
const props = [];
for (const [key, pre] of parts) {
const x = A.vals[i][key], y = B.vals[i][key];
if (!x && !y) continue;
if (!x || !y) { props.push({ prop: pre + 'content', a: x ? 'present' : 'none', b: y ? 'present' : 'none' }); continue; }
for (let k = 0; k < x.length; k++) {
if (x[k] !== y[k] && !IGN.has(A.names[k]) && !drift.has(i + '|' + key + '|' + k)) props.push({ prop: pre + A.names[k], a: cut(x[k]), b: cut(y[k]) });
}
}
if (!props.length) continue;
// Geometry counts as direct when a changed rule on this element declares it (authored width, not a push).
let direct = props.some((p) => !GEOM.has(p.prop));
if (!direct) {
const declared = matchedRules(A.els[i]).flatMap((r) => RULE_PROPS[r]);
direct = props.some((p) => declared.some((d) => d === p.prop || p.prop.startsWith(d + '-')));
}
changed.push({ el: A.els[i], props, direct });
}
const total = changed.length;
// With any direct change on the page, geometry-only elements are knock-on and only counted.
const hasDirect = changed.some((c) => c.direct);
const listed = hasDirect ? changed.filter((c) => c.direct) : changed;
const shifted = total - listed.length;
const found = new Set();
const elements = [];
for (const c of listed) {
const names = owner(c.el);
names.forEach((n) => found.add(n));
if (elements.length < 40) elements.push({ element: describe(c.el), components: names, props: c.props, more: 0, rules: matchedRules(c.el) });
}
return { comparable: true, total, listed: listed.length, shifted, components: Array.from(found), elements };
})()`;
export type NoiseReason = 'no-css' | 'unreachable' | 'style';
// Pixels moved but SLDS can't be the cause: the PR changes no CSS, no changed rule reaches the page
// (so any style change is Core runtime), or no component style changed. Pseudo/state rules can't be ruled out.
export function isNoise(
styleDiff: StyleDiff | undefined,
matchedCount: number,
changedSelectors: string[],
diff: { changedPixels: number; dimensionMismatch?: unknown },
): { noise: boolean; reason?: NoiseReason } {
if (diff.changedPixels === 0 && !diff.dimensionMismatch) return { noise: false };
if (!changedSelectors.length) return { noise: true, reason: 'no-css' };
if (diff.dimensionMismatch) return { noise: false };
if (matchedCount === 0 && !changedSelectors.some(isUntestableSelector))
return { noise: true, reason: 'unreachable' };
if (styleDiff?.comparable && styleDiff.components.length === 0) return { noise: true, reason: 'style' };
return { noise: false };
}
// Returns the element count captured.
export const snapshotStyles = async (page: Page, slot: 'A' | 'B' | 'C'): Promise<number> =>
(await page.evaluate(SNAPSHOT(slot))) as number;
// changedRules: changed selector -> the props the PR declares on it.
export const compareStyles = async (page: Page, changedRules: Record<string, string[]>): Promise<StyleDiff> =>
(await page.evaluate(COMPARE(COMPONENT_SELECTORS, changedRules))) as StyleDiff;
|