2026-08-06 09f01778d5a034e2af50ae05da8908f7b6a871c8
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
function sanitizeScreenshotClip(clip, viewport) {
  if (!clip) return null;
  const x = Math.max(0, Math.floor(clip.x || 0));
  const y = Math.max(0, Math.floor(clip.y || 0));
  const width = Math.min(
    Math.max(1, Math.ceil(clip.width || 0)),
    Math.max(1, viewport?.width || 1600),
  );
  const height = Math.min(
    Math.max(1, Math.ceil(clip.height || 0)),
    320,
  );
  if (width < 1 || height < 1) return null;
  return { x, y, width, height };
}
 
async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
  return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
    const loadImage = (base64) => new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve(img);
      img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
      img.src = `data:image/png;base64,${base64}`;
    });
    const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
    const width = Math.min(before.width, after.width);
    const height = Math.min(before.height, after.height);
    if (width < 1 || height < 1) return null;
 
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d', { willReadFrequently: true });
    if (!ctx) return null;
 
    ctx.drawImage(before, 0, 0, width, height);
    const beforePixels = ctx.getImageData(0, 0, width, height).data;
    ctx.clearRect(0, 0, width, height);
    ctx.drawImage(after, 0, 0, width, height);
    const afterPixels = ctx.getImageData(0, 0, width, height).data;
 
    const luminance = ({ r, g, b }) => {
      const convert = c => {
        const v = c / 255;
        return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
      };
      return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
    };
    const ratio = (a, b) => {
      const l1 = luminance(a);
      const l2 = luminance(b);
      return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
    };
 
    const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
      ? {
          r: candidate.textColor.r,
          g: candidate.textColor.g,
          b: candidate.textColor.b,
        }
      : null;
    const ratios = [];
    let glyphPixels = 0;
    let strongestDelta = 0;
    for (let i = 0; i < beforePixels.length; i += 4) {
      const delta = Math.abs(beforePixels[i] - afterPixels[i])
        + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
        + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
        + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
      strongestDelta = Math.max(strongestDelta, delta);
      if (delta < 10) continue;
      glyphPixels++;
      const fg = cssTextColor || {
        r: beforePixels[i],
        g: beforePixels[i + 1],
        b: beforePixels[i + 2],
      };
      const bg = {
        r: afterPixels[i],
        g: afterPixels[i + 1],
        b: afterPixels[i + 2],
      };
      ratios.push(ratio(fg, bg));
    }
 
    if (ratios.length < 8) {
      return {
        glyphPixels,
        strongestDelta,
        worstRatio: null,
        p10Ratio: null,
        medianRatio: null,
      };
    }
 
    ratios.sort((a, b) => a - b);
    const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
    return {
      glyphPixels,
      strongestDelta,
      worstRatio: ratios[0],
      p10Ratio: pick(10),
      medianRatio: pick(50),
    };
  }, { beforeBase64, afterBase64, candidate });
}
 
async function captureVisualContrastCandidate(page, candidate, viewport) {
  const clip = sanitizeScreenshotClip(candidate.clip, viewport);
  if (!clip) return null;
 
  const beforeBase64 = await page.screenshot({
    encoding: 'base64',
    clip,
    captureBeyondViewport: true,
  });
  const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
  const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
    let el;
    try {
      el = document.querySelector(selector);
    } catch {
      return false;
    }
    if (!el) return false;
    let style = document.getElementById('impeccable-visual-contrast-hide-style');
    if (!style) {
      style = document.createElement('style');
      style.id = 'impeccable-visual-contrast-hide-style';
      style.textContent = [
        '[data-impeccable-visual-contrast-target] {',
        '  color: transparent !important;',
        '  -webkit-text-fill-color: transparent !important;',
        '  text-shadow: none !important;',
        '}',
        '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
        '  background-image: none !important;',
        '}',
      ].join('\n');
      document.head.appendChild(style);
    }
    el.setAttribute('data-impeccable-visual-contrast-target', token);
    if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
    return true;
  }, {
    selector: candidate.selector,
    token,
    backgroundClipText: candidate.backgroundClipText,
  });
  if (!applied) return null;
 
  let afterBase64;
  try {
    afterBase64 = await page.screenshot({
      encoding: 'base64',
      clip,
      captureBeyondViewport: true,
    });
  } finally {
    await page.evaluate(({ selector }) => {
      try {
        const el = document.querySelector(selector);
        if (el) {
          el.removeAttribute('data-impeccable-visual-contrast-target');
          el.removeAttribute('data-impeccable-bgclip-text');
        }
      } catch {
        // Ignore invalid or stale selectors during cleanup.
      }
    }, { selector: candidate.selector }).catch(() => {});
  }
 
  const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
  if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
  const measuredRatio = metrics.p10Ratio;
  if (measuredRatio >= candidate.threshold) return null;
  const textLabel = candidate.text ? ` "${candidate.text}"` : '';
  const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
  return {
    id: 'low-contrast',
    snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
  };
}
 
export {
  sanitizeScreenshotClip,
  compareScreenshotContrast,
  captureVisualContrastCandidate,
};