impeccable 2.1.8 → 2.2.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.
@@ -1,2496 +0,0 @@
1
- /**
2
- * Anti-Pattern Browser Detector for Impeccable
3
- * Copyright (c) 2026 Paul Bakaus
4
- * SPDX-License-Identifier: Apache-2.0
5
- *
6
- * GENERATED -- do not edit. Source: detect-antipatterns.mjs
7
- * Rebuild: node scripts/build-browser-detector.js
8
- *
9
- * Usage: <script src="detect-antipatterns-browser.js"></script>
10
- * Re-scan: window.impeccableScan()
11
- */
12
- (function () {
13
- if (typeof window === 'undefined') return;
14
-
15
- /**
16
- * Anti-Pattern Detector for Impeccable
17
- * Copyright (c) 2026 Paul Bakaus
18
- * SPDX-License-Identifier: Apache-2.0
19
- *
20
- * Universal file — auto-detects environment (browser vs Node) and adapts.
21
- *
22
- * Node usage:
23
- * node detect-antipatterns.mjs [file-or-dir...] # jsdom for HTML, regex for rest
24
- * node detect-antipatterns.mjs https://... # Puppeteer (auto)
25
- * node detect-antipatterns.mjs --fast [files...] # regex-only (skip jsdom)
26
- * node detect-antipatterns.mjs --json # JSON output
27
- *
28
- * Browser usage:
29
- * <script src="detect-antipatterns-browser.js"></script>
30
- * Re-scan: window.impeccableScan()
31
- *
32
- * Exit codes: 0 = clean, 2 = findings
33
- */
34
-
35
- // ─── Environment ────────────────────────────────────────────────────────────
36
-
37
- const IS_BROWSER = true;
38
- const IS_NODE = !IS_BROWSER;
39
-
40
-
41
- // ─── Section 1: Constants ───────────────────────────────────────────────────
42
-
43
- const SAFE_TAGS = new Set([
44
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
45
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
46
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
47
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
48
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
49
- ]);
50
-
51
- // Per-check safe-tags override for the border (side-tab / border-accent)
52
- // rule. We intentionally re-allow <label> here because card-shaped clickable
53
- // labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
54
- // canonical side-tab anti-pattern shapes and must be detected. The rule's
55
- // other preconditions (non-neutral color, width >= 2px on a single side,
56
- // radius > 0 or width >= 3, element size >= 20x20 in the browser path)
57
- // already filter out plain inline form labels so this does not introduce
58
- // false positives. See modern-color-borders.html for the test matrix.
59
- const BORDER_SAFE_TAGS = new Set(
60
- [...SAFE_TAGS].filter(t => t !== 'label')
61
- );
62
-
63
- const OVERUSED_FONTS = new Set([
64
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
65
- ]);
66
-
67
- // Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
68
- // Keys are font names, values are arrays of hostname suffixes where the font is allowed.
69
- const GOOGLE_DOMAINS = [
70
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
71
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
72
- ];
73
- const BRAND_FONT_DOMAINS = {
74
- 'roboto': GOOGLE_DOMAINS,
75
- 'google sans': GOOGLE_DOMAINS,
76
- 'product sans': GOOGLE_DOMAINS,
77
- };
78
-
79
- function isBrandFontOnOwnDomain(font) {
80
- if (typeof location === 'undefined') return false;
81
- const allowed = BRAND_FONT_DOMAINS[font];
82
- if (!allowed) return false;
83
- const host = location.hostname.toLowerCase();
84
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
85
- }
86
-
87
- const GENERIC_FONTS = new Set([
88
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
89
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
90
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
91
- 'inherit', 'initial', 'unset', 'revert',
92
- ]);
93
-
94
- const ANTIPATTERNS = [
95
- // ── AI slop: tells that something was AI-generated ──
96
- {
97
- id: 'side-tab',
98
- category: 'slop',
99
- name: 'Side-tab accent border',
100
- description:
101
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
102
- skillSection: 'Visual Details',
103
- skillGuideline: 'colored accent stripe',
104
- },
105
- {
106
- id: 'border-accent-on-rounded',
107
- category: 'slop',
108
- name: 'Border accent on rounded element',
109
- description:
110
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
111
- skillSection: 'Visual Details',
112
- skillGuideline: 'colored accent stripe',
113
- },
114
- {
115
- id: 'overused-font',
116
- category: 'slop',
117
- name: 'Overused font',
118
- description:
119
- 'Inter, Roboto, Open Sans, Lato, Montserrat, and Arial are used on millions of sites. Choose a distinctive font that gives your interface personality.',
120
- skillSection: 'Typography',
121
- skillGuideline: 'overused fonts like Inter',
122
- },
123
- {
124
- id: 'single-font',
125
- category: 'slop',
126
- name: 'Single font for everything',
127
- description:
128
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
129
- skillSection: 'Typography',
130
- skillGuideline: 'only one font family for the entire page',
131
- },
132
- {
133
- id: 'flat-type-hierarchy',
134
- category: 'slop',
135
- name: 'Flat type hierarchy',
136
- description:
137
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
138
- skillSection: 'Typography',
139
- skillGuideline: 'flat type hierarchy',
140
- },
141
- {
142
- id: 'gradient-text',
143
- category: 'slop',
144
- name: 'Gradient text',
145
- description:
146
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
147
- skillSection: 'Color & Contrast',
148
- skillGuideline: 'gradient text for',
149
- },
150
- {
151
- id: 'ai-color-palette',
152
- category: 'slop',
153
- name: 'AI color palette',
154
- description:
155
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
156
- skillSection: 'Color & Contrast',
157
- skillGuideline: 'AI color palette',
158
- },
159
- {
160
- id: 'nested-cards',
161
- category: 'slop',
162
- name: 'Nested cards',
163
- description:
164
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
165
- skillSection: 'Layout & Space',
166
- skillGuideline: 'Nest cards inside cards',
167
- },
168
- {
169
- id: 'monotonous-spacing',
170
- category: 'slop',
171
- name: 'Monotonous spacing',
172
- description:
173
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
174
- skillSection: 'Layout & Space',
175
- skillGuideline: 'same spacing everywhere',
176
- },
177
- {
178
- id: 'everything-centered',
179
- category: 'slop',
180
- name: 'Everything centered',
181
- description:
182
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
183
- skillSection: 'Layout & Space',
184
- skillGuideline: 'Center everything',
185
- },
186
- {
187
- id: 'bounce-easing',
188
- category: 'slop',
189
- name: 'Bounce or elastic easing',
190
- description:
191
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
192
- skillSection: 'Motion',
193
- skillGuideline: 'bounce or elastic easing',
194
- },
195
- {
196
- id: 'dark-glow',
197
- category: 'slop',
198
- name: 'Dark mode with glowing accents',
199
- description:
200
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
201
- skillSection: 'Color & Contrast',
202
- skillGuideline: 'dark mode with glowing accents',
203
- },
204
- {
205
- id: 'icon-tile-stack',
206
- category: 'slop',
207
- name: 'Icon tile stacked above heading',
208
- description:
209
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
210
- skillSection: 'Typography',
211
- skillGuideline: 'large icons with rounded corners above every heading',
212
- },
213
-
214
- // ── Quality: general design and accessibility issues ──
215
- {
216
- id: 'pure-black-white',
217
- category: 'quality',
218
- name: 'Pure black background',
219
- description:
220
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
221
- skillSection: 'Color & Contrast',
222
- skillGuideline: 'pure black (#000)',
223
- },
224
- {
225
- id: 'gray-on-color',
226
- category: 'quality',
227
- name: 'Gray text on colored background',
228
- description:
229
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
230
- skillSection: 'Color & Contrast',
231
- skillGuideline: 'gray text on colored backgrounds',
232
- },
233
- {
234
- id: 'low-contrast',
235
- category: 'quality',
236
- name: 'Low contrast text',
237
- description:
238
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
239
- },
240
- {
241
- id: 'layout-transition',
242
- category: 'quality',
243
- name: 'Layout property animation',
244
- description:
245
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
246
- skillSection: 'Motion',
247
- skillGuideline: 'Animate layout properties',
248
- },
249
- {
250
- id: 'line-length',
251
- category: 'quality',
252
- name: 'Line length too long',
253
- description:
254
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
255
- skillSection: 'Layout & Space',
256
- skillGuideline: 'wrap beyond ~80 characters',
257
- },
258
- {
259
- id: 'cramped-padding',
260
- category: 'quality',
261
- name: 'Cramped padding',
262
- description:
263
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
264
- },
265
- {
266
- id: 'tight-leading',
267
- category: 'quality',
268
- name: 'Tight line height',
269
- description:
270
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
271
- },
272
- {
273
- id: 'skipped-heading',
274
- category: 'quality',
275
- name: 'Skipped heading level',
276
- description:
277
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
278
- },
279
- {
280
- id: 'justified-text',
281
- category: 'quality',
282
- name: 'Justified text',
283
- description:
284
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
285
- },
286
- {
287
- id: 'tiny-text',
288
- category: 'quality',
289
- name: 'Tiny body text',
290
- description:
291
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
292
- },
293
- {
294
- id: 'all-caps-body',
295
- category: 'quality',
296
- name: 'All-caps body text',
297
- description:
298
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
299
- skillSection: 'Typography',
300
- skillGuideline: 'long body passages in uppercase',
301
- },
302
- {
303
- id: 'wide-tracking',
304
- category: 'quality',
305
- name: 'Wide letter spacing on body text',
306
- description:
307
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
308
- },
309
- ];
310
-
311
- // ─── Section 2: Color Utilities ─────────────────────────────────────────────
312
-
313
- function isNeutralColor(color) {
314
- if (!color || color === 'transparent') return true;
315
-
316
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
317
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
318
- if (rgb) {
319
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
320
- }
321
-
322
- // oklch()/lch() — chroma is the second numeric component.
323
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
324
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
325
- // literally (it does NOT convert them to rgb).
326
- const oklch = color.match(/oklch\(\s*[\d.%-]+\s+([\d.-]+)/i);
327
- if (oklch) return parseFloat(oklch[1]) < 0.02;
328
- const lch = color.match(/lch\(\s*[\d.%-]+\s+([\d.-]+)/i);
329
- if (lch) return parseFloat(lch[1]) < 3;
330
-
331
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
332
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
333
- const oklab = color.match(/oklab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
334
- if (oklab) {
335
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
336
- return Math.hypot(a, b) < 0.02;
337
- }
338
- const lab = color.match(/lab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
339
- if (lab) {
340
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
341
- return Math.hypot(a, b) < 3;
342
- }
343
-
344
- // hsl/hsla — saturation is the second numeric component (percent).
345
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
346
- // safety across versions and for any engine that preserves the format.
347
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
348
- if (hsl) return parseFloat(hsl[1]) < 10;
349
-
350
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
351
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
352
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
353
- if (hwb) {
354
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
355
- return (1 - Math.min(100, w + b) / 100) < 0.1;
356
- }
357
-
358
- // Unknown / unrecognized format — err on the side of DETECTING rather
359
- // than silently skipping. This is the opposite of the previous default,
360
- // which was the root cause of the oklch bug.
361
- return false;
362
- }
363
-
364
- function parseRgb(color) {
365
- if (!color || color === 'transparent') return null;
366
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
367
- if (!m) return null;
368
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
369
- }
370
-
371
- function relativeLuminance({ r, g, b }) {
372
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
373
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
374
- );
375
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
376
- }
377
-
378
- function contrastRatio(c1, c2) {
379
- const l1 = relativeLuminance(c1);
380
- const l2 = relativeLuminance(c2);
381
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
382
- }
383
-
384
- function parseGradientColors(bgImage) {
385
- if (!bgImage || !bgImage.includes('gradient')) return [];
386
- const colors = [];
387
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
388
- const c = parseRgb(m[0]);
389
- if (c) colors.push(c);
390
- }
391
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
392
- const h = m[1];
393
- if (h.length === 6) {
394
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
395
- } else {
396
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
397
- }
398
- }
399
- return colors;
400
- }
401
-
402
- function hasChroma(c, threshold = 30) {
403
- if (!c) return false;
404
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
405
- }
406
-
407
- function getHue(c) {
408
- if (!c) return 0;
409
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
410
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
411
- if (max === min) return 0;
412
- const d = max - min;
413
- let h;
414
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
415
- else if (max === g) h = ((b - r) / d + 2) / 6;
416
- else h = ((r - g) / d + 4) / 6;
417
- return Math.round(h * 360);
418
- }
419
-
420
- function colorToHex(c) {
421
- if (!c) return '?';
422
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
423
- }
424
-
425
- // ─── Section 3: Pure Detection ──────────────────────────────────────────────
426
-
427
- function checkBorders(tag, widths, colors, radius) {
428
- if (BORDER_SAFE_TAGS.has(tag)) return [];
429
- const findings = [];
430
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
431
-
432
- for (const side of sides) {
433
- const w = widths[side];
434
- if (w < 1 || isNeutralColor(colors[side])) continue;
435
-
436
- const otherSides = sides.filter(s => s !== side);
437
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
438
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
439
-
440
- const sn = side.toLowerCase();
441
- const isSide = side === 'Left' || side === 'Right';
442
-
443
- if (isSide) {
444
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
445
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
446
- } else {
447
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
448
- }
449
- }
450
-
451
- return findings;
452
- }
453
-
454
- // Returns true if the given text is composed entirely of emoji characters
455
- // (plus whitespace / variation selectors). Emojis render as multicolor glyphs
456
- // regardless of CSS `color`, so contrast checks against the element's text
457
- // color are meaningless for these nodes.
458
- const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
459
- const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
460
- function isEmojiOnlyText(text) {
461
- if (!text) return false;
462
- if (!EMOJI_CHAR_RE.test(text)) return false;
463
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
464
- }
465
-
466
- function checkColors(opts) {
467
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
468
- if (SAFE_TAGS.has(tag)) return [];
469
- const findings = [];
470
-
471
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
472
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
473
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
474
- }
475
-
476
- if (hasDirectText && textColor && !isEmojiOnly) {
477
- // Run background-dependent checks against either a solid bg or, if the
478
- // ancestor is a gradient, against every gradient stop (use the worst case).
479
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
480
- if (bgs) {
481
- // Gray on colored background — flag if every stop is chromatic
482
- const textLum = relativeLuminance(textColor);
483
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
484
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
485
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
486
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
487
- }
488
-
489
- // Low contrast (WCAG AA) — worst case across all bg stops
490
- const ratios = bgs.map(b => contrastRatio(textColor, b));
491
- let worstIdx = 0;
492
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
493
- const ratio = ratios[worstIdx];
494
- const isHeading = ['h1', 'h2', 'h3'].includes(tag);
495
- const isLargeText = fontSize >= 18 || (fontSize >= 14 && fontWeight >= 700) || isHeading;
496
- const threshold = isLargeText ? 3.0 : 4.5;
497
- if (ratio < threshold) {
498
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
499
- }
500
- }
501
-
502
- // AI palette: purple/violet on headings
503
- if (hasChroma(textColor, 50)) {
504
- const hue = getHue(textColor);
505
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
506
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
507
- }
508
- }
509
- }
510
-
511
- // Gradient text
512
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
513
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
514
- }
515
-
516
- // Tailwind class checks
517
- if (classList) {
518
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
519
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
520
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
521
- }
522
-
523
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
524
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
525
- if (grayMatch && colorBgMatch) {
526
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
527
- }
528
-
529
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
530
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
531
- }
532
-
533
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
534
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
535
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
536
- }
537
-
538
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
539
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
540
- }
541
- }
542
-
543
- return findings;
544
- }
545
-
546
- function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
547
- if (!hasShadow && !hasBorder) return false;
548
- return hasRadius || hasBg;
549
- }
550
-
551
- const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
552
-
553
- // Pure check: given a heading and metrics about its previousElementSibling,
554
- // decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
555
- //
556
- // Triggers when ALL of the following hold for the sibling:
557
- // • size 32–128px on both axes (not too small, not a hero image)
558
- // • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
559
- // • has a non-transparent background-color, background-image, OR a visible border
560
- // (covers solid colors, white-with-border, gradients — anything that visually
561
- // defines a tile)
562
- // • border-radius < width/2 (excludes round avatars; rounded squares pass)
563
- // • contains an <svg> or icon-class <i> element that's smaller than the tile
564
- // • the tile sits above the heading (its bottom is above the heading's top)
565
- function checkIconTile(opts) {
566
- const { headingTag, headingText, headingTop,
567
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
568
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
569
- hasIconChild, iconChildWidth } = opts;
570
- if (!HEADING_TAGS.has(headingTag)) return [];
571
- if (!siblingTag) return [];
572
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
573
- if (HEADING_TAGS.has(siblingTag)) return [];
574
-
575
- // Size window: 32–128px on each axis
576
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
577
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
578
-
579
- // Squarish aspect ratio
580
- const ratio = siblingWidth / siblingHeight;
581
- if (ratio < 0.7 || ratio > 1.4) return [];
582
-
583
- // Must have something that visually defines the tile
584
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
585
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
586
- const borderVisible = siblingBorderWidth > 0;
587
- if (!bgVisible && !borderVisible) return [];
588
-
589
- // Exclude circles (avatars). Rounded squares pass.
590
- if (siblingBorderRadius >= siblingWidth / 2) return [];
591
-
592
- // Must contain an icon element smaller than the tile
593
- if (!hasIconChild) return [];
594
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
595
-
596
- // Vertical stacking: tile must end above where the heading starts.
597
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
598
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
599
-
600
- const text = (headingText || '').trim().slice(0, 60);
601
- return [{
602
- id: 'icon-tile-stack',
603
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
604
- }];
605
- }
606
-
607
- const LAYOUT_TRANSITION_PROPS = new Set([
608
- 'width', 'height', 'padding', 'margin',
609
- 'max-height', 'max-width', 'min-height', 'min-width',
610
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
611
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
612
- ]);
613
-
614
- function checkMotion(opts) {
615
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
616
- if (SAFE_TAGS.has(tag)) return [];
617
- const findings = [];
618
-
619
- // --- Bounce/elastic easing ---
620
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
621
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
622
- }
623
- if (classList && /\banimate-bounce\b/.test(classList)) {
624
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
625
- }
626
-
627
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
628
- if (timingFunctions) {
629
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
630
- let m;
631
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
632
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
633
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
634
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
635
- break;
636
- }
637
- }
638
- }
639
-
640
- // --- Layout property transition ---
641
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
642
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
643
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
644
- if (layoutFound.length > 0) {
645
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
646
- }
647
- }
648
-
649
- return findings;
650
- }
651
-
652
- function checkGlow(opts) {
653
- const { boxShadow, effectiveBg } = opts;
654
- if (!boxShadow || boxShadow === 'none') return [];
655
- if (!effectiveBg) return [];
656
-
657
- // Only flag on dark backgrounds (luminance < 0.1)
658
- const bgLum = relativeLuminance(effectiveBg);
659
- if (bgLum >= 0.1) return [];
660
-
661
- // Split multiple shadows (commas not inside parentheses)
662
- const parts = boxShadow.split(/,(?![^(]*\))/);
663
- for (const shadow of parts) {
664
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
665
- if (!colorMatch) continue;
666
- const color = parseRgb(colorMatch[0]);
667
- if (!color || !hasChroma(color, 30)) continue;
668
-
669
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
670
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
671
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
672
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
673
- .map(m => parseFloat(m[1]));
674
-
675
- // Third value is blur (offset-x, offset-y, blur, [spread])
676
- if (pxVals.length >= 3 && pxVals[2] > 4) {
677
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
678
- }
679
- }
680
-
681
- return [];
682
- }
683
-
684
- /**
685
- * Regex-on-HTML checks shared between browser and Node page-level detection.
686
- * These don't need DOM access, just the raw HTML string.
687
- */
688
- function checkHtmlPatterns(html) {
689
- const findings = [];
690
-
691
- // --- Color ---
692
-
693
- // Pure black background
694
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
695
- if (pureBlackBgRe.test(html)) {
696
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
697
- }
698
-
699
- // AI color palette: purple/violet
700
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
701
- if (purpleHexRe.test(html)) {
702
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
703
- if (purpleTextRe.test(html)) {
704
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
705
- }
706
- }
707
-
708
- // Gradient text (background-clip: text + gradient)
709
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
710
- let gm;
711
- while ((gm = gradientRe.exec(html)) !== null) {
712
- const start = Math.max(0, gm.index - 200);
713
- const context = html.substring(start, gm.index + gm[0].length + 200);
714
- if (/gradient/i.test(context)) {
715
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
716
- break;
717
- }
718
- }
719
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
720
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
721
- }
722
-
723
- // --- Layout ---
724
-
725
- // Monotonous spacing
726
- const spacingValues = [];
727
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
728
- let sm;
729
- while ((sm = spacingRe.exec(html)) !== null) {
730
- const v = parseInt(sm[1], 10);
731
- if (v > 0 && v < 200) spacingValues.push(v);
732
- }
733
- const gapRe = /gap\s*:\s*(\d+)px/gi;
734
- while ((sm = gapRe.exec(html)) !== null) {
735
- spacingValues.push(parseInt(sm[1], 10));
736
- }
737
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
738
- while ((sm = twSpaceRe.exec(html)) !== null) {
739
- spacingValues.push(parseInt(sm[1], 10) * 4);
740
- }
741
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
742
- while ((sm = remSpacingRe.exec(html)) !== null) {
743
- const v = Math.round(parseFloat(sm[1]) * 16);
744
- if (v > 0 && v < 200) spacingValues.push(v);
745
- }
746
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
747
- if (roundedSpacing.length >= 10) {
748
- const counts = {};
749
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
750
- const maxCount = Math.max(...Object.values(counts));
751
- const dominantPct = maxCount / roundedSpacing.length;
752
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
753
- if (dominantPct > 0.6 && unique.length <= 3) {
754
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
755
- findings.push({
756
- id: 'monotonous-spacing',
757
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
758
- });
759
- }
760
- }
761
-
762
- // --- Motion ---
763
-
764
- // Bounce/elastic animation names
765
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
766
- if (bounceRe.test(html)) {
767
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
768
- }
769
-
770
- // Overshoot cubic-bezier
771
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
772
- let bm;
773
- while ((bm = bezierRe.exec(html)) !== null) {
774
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
775
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
776
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
777
- break;
778
- }
779
- }
780
-
781
- // Layout property transitions
782
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
783
- let tm;
784
- while ((tm = transRe.exec(html)) !== null) {
785
- const val = tm[1].toLowerCase();
786
- if (/\ball\b/.test(val)) continue;
787
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
788
- if (found) {
789
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
790
- break;
791
- }
792
- }
793
-
794
- // --- Dark glow ---
795
-
796
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
797
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
798
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
799
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
800
- let shm;
801
- while ((shm = shadowRe.exec(html)) !== null) {
802
- const val = shm[1];
803
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
804
- if (!colorMatch) continue;
805
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
806
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
807
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
808
- if (pxVals.length >= 3 && pxVals[2] > 4) {
809
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
810
- break;
811
- }
812
- }
813
- }
814
-
815
- return findings;
816
- }
817
-
818
- // ─── Section 4: resolveBackground (unified) ─────────────────────────────────
819
-
820
- function resolveBackground(el, win) {
821
- let current = el;
822
- while (current && current.nodeType === 1) {
823
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
824
-
825
- // If this element has a background-image (gradient or url), it's visually
826
- // opaque but we can't determine the effective color — bail out so callers
827
- // don't get a false solid-color answer.
828
- const bgImage = style.backgroundImage || '';
829
- if (bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage))) {
830
- return null;
831
- }
832
-
833
- let bg = parseRgb(style.backgroundColor);
834
- if (!IS_BROWSER && (!bg || bg.a < 0.1)) {
835
- // jsdom doesn't decompose background shorthand — parse raw style attr
836
- const rawStyle = current.getAttribute?.('style') || '';
837
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
838
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
839
- // Check for gradient or url() image in inline style too
840
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return null;
841
- bg = parseRgb(inlineBg);
842
- if (!bg && inlineBg) {
843
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
844
- if (hexMatch) {
845
- const h = hexMatch[1];
846
- if (h.length === 6) {
847
- bg = { r: parseInt(h.slice(0,2), 16), g: parseInt(h.slice(2,4), 16), b: parseInt(h.slice(4,6), 16), a: 1 };
848
- } else {
849
- bg = { r: parseInt(h[0]+h[0], 16), g: parseInt(h[1]+h[1], 16), b: parseInt(h[2]+h[2], 16), a: 1 };
850
- }
851
- }
852
- }
853
- }
854
- if (bg && bg.a > 0.1) {
855
- if (IS_BROWSER || bg.a >= 0.5) return bg;
856
- }
857
- current = current.parentElement;
858
- }
859
- return { r: 255, g: 255, b: 255 };
860
- }
861
-
862
- // Walk parents looking for a gradient background and return its color stops.
863
- // Used as a fallback when resolveBackground() returns null because the
864
- // effective background is a gradient (no single solid color to compare against).
865
- function resolveGradientStops(el, win) {
866
- let current = el;
867
- while (current && current.nodeType === 1) {
868
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
869
- const bgImage = style.backgroundImage || '';
870
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
871
- const stops = parseGradientColors(bgImage);
872
- if (stops.length > 0) return stops;
873
- }
874
- if (!IS_BROWSER) {
875
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
876
- const rawStyle = current.getAttribute?.('style') || '';
877
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
878
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
879
- const stops = parseGradientColors(bgMatch[1]);
880
- if (stops.length > 0) return stops;
881
- }
882
- }
883
- current = current.parentElement;
884
- }
885
- return null;
886
- }
887
-
888
- // Parse a single CSS length token to pixels. Accepts "12px", "50%", a
889
- // shorthand like "12px 4px" (uses the first value), or empty / null.
890
- // Returns the pixel value, or null when the input is unparseable.
891
- // Percentages convert against `widthPx` when one is supplied. Without a
892
- // usable width (jsdom returns "auto" for many real-world elements,
893
- // which parseFloat collapses to 0), fall back to the raw percentage
894
- // number so callers gating on `> 0` (border-accent-on-rounded,
895
- // isCardLike's hasRadius) still see a positive value, matching the
896
- // original parseFloat("50%") === 50 behavior.
897
- function parseRadiusToPx(value, widthPx) {
898
- if (!value || typeof value !== 'string') return null;
899
- const trimmed = value.trim();
900
- if (!trimmed) return null;
901
- const first = trimmed.split(/\s+/)[0];
902
- const num = parseFloat(first);
903
- if (Number.isNaN(num)) return null;
904
- if (/%$/.test(first)) {
905
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
906
- return num;
907
- }
908
- return num;
909
- }
910
-
911
- // jsdom from 29.0.2 onward returns "" for the `border-radius` shorthand
912
- // in computed style and "0" for longhand reads when the source rule used
913
- // the shorthand. The rule engine relied on parseFloat(style.borderRadius)
914
- // to identify circular avatars (border-radius >= width/2) and rounded
915
- // cards (border-radius > 0); both checks broke silently. This helper
916
- // recovers the radius via a chain of fallbacks. Browsers resolve the
917
- // shorthand correctly and exit on the first line.
918
- function resolveBorderRadiusPx(el, style, widthPx, win) {
919
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
920
- if (fromComputed !== null) return fromComputed;
921
-
922
- if (IS_BROWSER || !win) return 0;
923
-
924
- const fromLonghand = parseRadiusToPx(style.borderTopLeftRadius, widthPx);
925
- if (fromLonghand !== null && fromLonghand > 0) return fromLonghand;
926
-
927
- const fromInlineProp = parseRadiusToPx(el.style?.borderRadius, widthPx);
928
- if (fromInlineProp !== null) return fromInlineProp;
929
-
930
- const rawStyle = el.getAttribute?.('style') || '';
931
- const inlineMatch = rawStyle.match(/border-radius\s*:\s*([^;]+)/i);
932
- if (inlineMatch) {
933
- const fromRaw = parseRadiusToPx(inlineMatch[1].trim(), widthPx);
934
- if (fromRaw !== null) return fromRaw;
935
- }
936
-
937
- // Walk every stylesheet looking for matching rules. Take the maximum
938
- // pixel value across all matches so a circle declaration overridden by
939
- // a more specific rounded-square selector still registers as a circle
940
- // for the exclusion check (better to under-flag than to false-positive
941
- // on round avatars).
942
- let max = 0;
943
- const sheets = win.document?.styleSheets;
944
- if (sheets) {
945
- for (const sheet of sheets) {
946
- let rules;
947
- try { rules = sheet.cssRules || []; } catch { continue; }
948
- for (const rule of rules) {
949
- if (!rule.style || !rule.selectorText) continue;
950
- let matches = false;
951
- try { matches = el.matches(rule.selectorText); } catch { continue; }
952
- if (!matches) continue;
953
- const ruleValue = rule.style.borderRadius
954
- || (rule.style.getPropertyValue && rule.style.getPropertyValue('border-radius'))
955
- || rule.style.borderTopLeftRadius;
956
- const px = parseRadiusToPx(ruleValue, widthPx);
957
- if (px !== null && px > max) max = px;
958
- }
959
- }
960
- }
961
- return max;
962
- }
963
-
964
- // ─── Section 5: Element Adapters ────────────────────────────────────────────
965
-
966
- // Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
967
-
968
- function checkElementBordersDOM(el) {
969
- const tag = el.tagName.toLowerCase();
970
- if (BORDER_SAFE_TAGS.has(tag)) return [];
971
- const rect = el.getBoundingClientRect();
972
- if (rect.width < 20 || rect.height < 20) return [];
973
- const style = getComputedStyle(el);
974
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
975
- const widths = {}, colors = {};
976
- for (const s of sides) {
977
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
978
- colors[s] = style[`border${s}Color`] || '';
979
- }
980
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
981
- }
982
-
983
- function checkElementColorsDOM(el) {
984
- const tag = el.tagName.toLowerCase();
985
- if (SAFE_TAGS.has(tag)) return [];
986
- const rect = el.getBoundingClientRect();
987
- if (rect.width < 10 || rect.height < 10) return [];
988
- const style = getComputedStyle(el);
989
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
990
- const hasDirectText = directText.trim().length > 0;
991
- const effectiveBg = resolveBackground(el);
992
- return checkColors({
993
- tag,
994
- textColor: parseRgb(style.color),
995
- bgColor: parseRgb(style.backgroundColor),
996
- effectiveBg,
997
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
998
- fontSize: parseFloat(style.fontSize) || 16,
999
- fontWeight: parseInt(style.fontWeight) || 400,
1000
- hasDirectText,
1001
- isEmojiOnly: isEmojiOnlyText(directText),
1002
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
1003
- bgImage: style.backgroundImage || '',
1004
- classList: el.getAttribute('class') || '',
1005
- });
1006
- }
1007
-
1008
- function checkElementIconTileDOM(el) {
1009
- const tag = el.tagName.toLowerCase();
1010
- if (!HEADING_TAGS.has(tag)) return [];
1011
- const sibling = el.previousElementSibling;
1012
- if (!sibling) return [];
1013
-
1014
- const sibRect = sibling.getBoundingClientRect();
1015
- const headRect = el.getBoundingClientRect();
1016
- const sibStyle = getComputedStyle(sibling);
1017
-
1018
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
1019
- // may contain an emoji/symbol character directly as its only text content
1020
- // (the "card-icon" pattern from many AI-generated demos).
1021
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
1022
- const iconRect = iconChild?.getBoundingClientRect();
1023
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1024
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
1025
-
1026
- return checkIconTile({
1027
- headingTag: tag,
1028
- headingText: el.textContent || '',
1029
- headingTop: headRect.top,
1030
- siblingTag: sibling.tagName.toLowerCase(),
1031
- siblingWidth: sibRect.width,
1032
- siblingHeight: sibRect.height,
1033
- siblingBottom: sibRect.bottom,
1034
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
1035
- siblingBgImage: sibStyle.backgroundImage || '',
1036
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
1037
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
1038
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
1039
- iconChildWidth: iconRect?.width || 0,
1040
- });
1041
- }
1042
-
1043
- function checkElementMotionDOM(el) {
1044
- const tag = el.tagName.toLowerCase();
1045
- if (SAFE_TAGS.has(tag)) return [];
1046
- const style = getComputedStyle(el);
1047
- return checkMotion({
1048
- tag,
1049
- transitionProperty: style.transitionProperty || '',
1050
- animationName: style.animationName || '',
1051
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
1052
- classList: el.getAttribute('class') || '',
1053
- });
1054
- }
1055
-
1056
- function checkElementGlowDOM(el) {
1057
- const tag = el.tagName.toLowerCase();
1058
- const style = getComputedStyle(el);
1059
- if (!style.boxShadow || style.boxShadow === 'none') return [];
1060
- // Use parent's background — glow radiates outward, so the surrounding context matters
1061
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
1062
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
1063
- if (!parentBg) {
1064
- // Gradient background — sample its colors to determine if it's dark
1065
- let cur = el.parentElement;
1066
- while (cur && cur.nodeType === 1) {
1067
- const bgImage = getComputedStyle(cur).backgroundImage || '';
1068
- const gradColors = parseGradientColors(bgImage);
1069
- if (gradColors.length > 0) {
1070
- // Average the gradient colors
1071
- const avg = { r: 0, g: 0, b: 0 };
1072
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
1073
- avg.r = Math.round(avg.r / gradColors.length);
1074
- avg.g = Math.round(avg.g / gradColors.length);
1075
- avg.b = Math.round(avg.b / gradColors.length);
1076
- parentBg = avg;
1077
- break;
1078
- }
1079
- cur = cur.parentElement;
1080
- }
1081
- }
1082
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
1083
- }
1084
-
1085
- function checkElementAIPaletteDOM(el) {
1086
- const style = getComputedStyle(el);
1087
- const findings = [];
1088
-
1089
- // Check gradient backgrounds for purple/violet or cyan
1090
- const bgImage = style.backgroundImage || '';
1091
- const gradColors = parseGradientColors(bgImage);
1092
- for (const c of gradColors) {
1093
- if (hasChroma(c, 50)) {
1094
- const hue = getHue(c);
1095
- if (hue >= 260 && hue <= 310) {
1096
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
1097
- break;
1098
- }
1099
- if (hue >= 160 && hue <= 200) {
1100
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
1101
- break;
1102
- }
1103
- }
1104
- }
1105
-
1106
- // Check for neon text (vivid cyan/purple color on dark background)
1107
- const textColor = parseRgb(style.color);
1108
- if (textColor && hasChroma(textColor, 80)) {
1109
- const hue = getHue(textColor);
1110
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
1111
- if (isAIPalette) {
1112
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
1113
- // Also check gradient parents
1114
- let effectiveBg = parentBg;
1115
- if (!effectiveBg) {
1116
- let cur = el.parentElement;
1117
- while (cur && cur.nodeType === 1) {
1118
- const gi = getComputedStyle(cur).backgroundImage || '';
1119
- const gc = parseGradientColors(gi);
1120
- if (gc.length > 0) {
1121
- const avg = { r: 0, g: 0, b: 0 };
1122
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
1123
- avg.r = Math.round(avg.r / gc.length);
1124
- avg.g = Math.round(avg.g / gc.length);
1125
- avg.b = Math.round(avg.b / gc.length);
1126
- effectiveBg = avg;
1127
- break;
1128
- }
1129
- cur = cur.parentElement;
1130
- }
1131
- }
1132
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
1133
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
1134
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
1135
- }
1136
- }
1137
- }
1138
-
1139
- return findings;
1140
- }
1141
-
1142
- const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
1143
-
1144
- // Resolve a CSS font-size value to pixels by walking up the parent chain.
1145
- // Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
1146
- // specified value verbatim — so for the Node path we walk parents ourselves.
1147
- function resolveFontSizePx(el, win) {
1148
- const chain = []; // raw font-size strings, leaf → root
1149
- let cur = el;
1150
- while (cur && cur.nodeType === 1) {
1151
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
1152
- chain.push(fs || '');
1153
- cur = cur.parentElement;
1154
- }
1155
- // Walk root → leaf, resolving each value relative to its parent context.
1156
- let px = 16; // root default
1157
- for (let i = chain.length - 1; i >= 0; i--) {
1158
- const v = chain[i];
1159
- if (!v || v === 'inherit') continue;
1160
- const num = parseFloat(v);
1161
- if (isNaN(num)) continue;
1162
- if (v.endsWith('px')) px = num;
1163
- else if (v.endsWith('rem')) px = num * 16;
1164
- else if (v.endsWith('em')) px = num * px;
1165
- else if (v.endsWith('%')) px = (num / 100) * px;
1166
- else px = num; // unitless — already resolved
1167
- }
1168
- return px;
1169
- }
1170
-
1171
- // Resolve a CSS length value (line-height, letter-spacing, etc.) given a
1172
- // known font-size context. Returns null for "normal" / unparseable values.
1173
- function resolveLengthPx(value, fontSizePx) {
1174
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
1175
- const num = parseFloat(value);
1176
- if (isNaN(num)) return null;
1177
- if (value.endsWith('px')) return num;
1178
- if (value.endsWith('rem')) return num * 16;
1179
- if (value.endsWith('em')) return num * fontSizePx;
1180
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
1181
- // Unitless line-height = multiplier, return px equivalent
1182
- return num * fontSizePx;
1183
- }
1184
-
1185
- // Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
1186
- // jsdom and the browser). Two checks (line-length, cramped-padding) gate on
1187
- // element rect dimensions, which jsdom can't compute — pass `rect: null` from
1188
- // the Node adapter to skip those.
1189
- //
1190
- // Both adapters resolve font-size, line-height and letter-spacing to pixels
1191
- // before calling this so the pure function only deals with numbers.
1192
- function checkQuality(opts) {
1193
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80 } = opts;
1194
- const findings = [];
1195
- // Skip browser extension injected elements
1196
- const elId = el.id || '';
1197
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
1198
-
1199
- // --- Line length too long --- (browser-only: needs rect.width)
1200
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
1201
- const charsPerLine = rect.width / (fontSize * 0.5);
1202
- if (charsPerLine > lineMax + 5) {
1203
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
1204
- }
1205
- }
1206
-
1207
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
1208
- // Vertical and horizontal thresholds are independent because line-height
1209
- // already provides built-in vertical breathing room (the line box is taller
1210
- // than the cap height), but horizontal has no equivalent. Both scale with
1211
- // font-size — bigger text demands proportionally more padding.
1212
- // vertical: max(4px, fontSize × 0.3)
1213
- // horizontal: max(8px, fontSize × 0.5)
1214
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
1215
- const borders = {
1216
- top: parseFloat(style.borderTopWidth) || 0,
1217
- right: parseFloat(style.borderRightWidth) || 0,
1218
- bottom: parseFloat(style.borderBottomWidth) || 0,
1219
- left: parseFloat(style.borderLeftWidth) || 0,
1220
- };
1221
- const borderCount = Object.values(borders).filter(w => w > 0).length;
1222
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
1223
- if (borderCount >= 2 || hasBg) {
1224
- const vPads = [], hPads = [];
1225
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
1226
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
1227
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
1228
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
1229
-
1230
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
1231
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
1232
- const vThresh = Math.max(4, fontSize * 0.3);
1233
- const hThresh = Math.max(8, fontSize * 0.5);
1234
-
1235
- // Emit at most one finding per element — pick whichever axis is worse.
1236
- if (vMin < vThresh) {
1237
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
1238
- } else if (hMin < hThresh) {
1239
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
1240
- }
1241
- }
1242
- }
1243
-
1244
- // --- Tight line height ---
1245
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
1246
- if (lineHeightPx != null && fontSize > 0) {
1247
- const ratio = lineHeightPx / fontSize;
1248
- if (ratio > 0 && ratio < 1.3) {
1249
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
1250
- }
1251
- }
1252
- }
1253
-
1254
- // --- Justified text (without hyphens) ---
1255
- if (hasDirectText && style.textAlign === 'justify') {
1256
- const hyphens = style.hyphens || style.webkitHyphens || '';
1257
- if (hyphens !== 'auto') {
1258
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
1259
- }
1260
- }
1261
-
1262
- // --- Tiny body text ---
1263
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
1264
- if (hasDirectText && textLen > 20 && fontSize < 12) {
1265
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
1266
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
1267
- const isUppercase = style.textTransform === 'uppercase';
1268
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
1269
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
1270
- }
1271
- }
1272
-
1273
- // --- All-caps body text ---
1274
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
1275
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
1276
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
1277
- }
1278
- }
1279
-
1280
- // --- Wide letter spacing on body text ---
1281
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
1282
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
1283
- const trackingEm = letterSpacingPx / fontSize;
1284
- if (trackingEm > 0.05) {
1285
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
1286
- }
1287
- }
1288
- }
1289
-
1290
- return findings;
1291
- }
1292
-
1293
- function checkElementQualityDOM(el) {
1294
- const tag = el.tagName.toLowerCase();
1295
- const style = getComputedStyle(el);
1296
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
1297
- const textLen = el.textContent?.trim().length || 0;
1298
- // Browser getComputedStyle resolves everything to px — direct parseFloat
1299
- // works.
1300
- const fontSize = parseFloat(style.fontSize) || 16;
1301
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
1302
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
1303
- const rect = el.getBoundingClientRect();
1304
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
1305
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax });
1306
- }
1307
-
1308
- // Pure page-level skipped-heading walk. Takes a Document so it works in both
1309
- // the browser and jsdom.
1310
- function checkPageQualityFromDoc(doc) {
1311
- const findings = [];
1312
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
1313
- let prevLevel = 0;
1314
- let prevText = '';
1315
- for (const h of headings) {
1316
- const level = parseInt(h.tagName[1]);
1317
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
1318
- if (prevLevel > 0 && level > prevLevel + 1) {
1319
- findings.push({
1320
- id: 'skipped-heading',
1321
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
1322
- });
1323
- }
1324
- prevLevel = level;
1325
- prevText = text;
1326
- }
1327
- return findings;
1328
- }
1329
-
1330
- // Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
1331
- function checkPageQualityDOM() {
1332
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
1333
- }
1334
-
1335
- // Node adapters — take pre-extracted jsdom computed style
1336
-
1337
- // jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
1338
- // CSS length the rule needs ourselves (walking the parent chain for
1339
- // font-size inheritance), and pass `rect: null` to skip the two rules that
1340
- // genuinely need element rects (line-length, cramped-padding).
1341
- function checkElementQuality(el, style, tag, window) {
1342
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
1343
- const textLen = el.textContent?.trim().length || 0;
1344
- const fontSize = resolveFontSizePx(el, window);
1345
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
1346
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
1347
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
1348
- }
1349
-
1350
- function checkElementBorders(tag, style, overrides, resolvedRadius) {
1351
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
1352
- const widths = {}, colors = {};
1353
- for (const s of sides) {
1354
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
1355
- colors[s] = style[`border${s}Color`] || '';
1356
- // jsdom silently drops any border shorthand containing var(), leaving
1357
- // both width and color empty on the computed style. When the detectHtml
1358
- // pre-pass pulled a resolved value off the rule, use it to fill in the
1359
- // missing side so the side-tab check can run. Real browsers resolve
1360
- // var() natively, so this fallback is a no-op in the browser path.
1361
- if (widths[s] === 0 && overrides && overrides[s]) {
1362
- widths[s] = overrides[s].width;
1363
- colors[s] = overrides[s].color;
1364
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
1365
- // Longhand case: jsdom kept the width but left the color as the
1366
- // literal `var(...)` string. Substitute the resolved color.
1367
- colors[s] = overrides[s].color;
1368
- }
1369
- }
1370
- // resolvedRadius lets the caller pre-resolve the radius via
1371
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
1372
- // shorthand serialization. Falls back to the computed value for tests
1373
- // and browser callers that don't pre-resolve.
1374
- const radius = resolvedRadius != null
1375
- ? resolvedRadius
1376
- : (parseFloat(style.borderRadius) || 0);
1377
- return checkBorders(tag, widths, colors, radius);
1378
- }
1379
-
1380
- function checkElementColors(el, style, tag, window) {
1381
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1382
- const hasDirectText = directText.trim().length > 0;
1383
-
1384
- const effectiveBg = resolveBackground(el, window);
1385
- return checkColors({
1386
- tag,
1387
- textColor: parseRgb(style.color),
1388
- bgColor: parseRgb(style.backgroundColor),
1389
- effectiveBg,
1390
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
1391
- fontSize: parseFloat(style.fontSize) || 16,
1392
- fontWeight: parseInt(style.fontWeight) || 400,
1393
- hasDirectText,
1394
- isEmojiOnly: isEmojiOnlyText(directText),
1395
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
1396
- bgImage: style.backgroundImage || '',
1397
- classList: el.getAttribute?.('class') || el.className || '',
1398
- });
1399
- }
1400
-
1401
- function checkElementIconTile(el, tag, window) {
1402
- if (!HEADING_TAGS.has(tag)) return [];
1403
- const sibling = el.previousElementSibling;
1404
- if (!sibling) return [];
1405
-
1406
- const sibStyle = window.getComputedStyle(sibling);
1407
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
1408
- const sibWidth = parseFloat(sibStyle.width) || 0;
1409
- const sibHeight = parseFloat(sibStyle.height) || 0;
1410
-
1411
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
1412
- let iconWidth = 0;
1413
- if (iconChild) {
1414
- const iconStyle = window.getComputedStyle(iconChild);
1415
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
1416
- }
1417
- // Or: tile contains an emoji/symbol character directly as its only content
1418
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1419
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
1420
-
1421
- return checkIconTile({
1422
- headingTag: tag,
1423
- headingText: el.textContent || '',
1424
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
1425
- siblingTag: sibling.tagName.toLowerCase(),
1426
- siblingWidth: sibWidth,
1427
- siblingHeight: sibHeight,
1428
- siblingBottom: 0,
1429
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
1430
- siblingBgImage: sibStyle.backgroundImage || '',
1431
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
1432
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
1433
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
1434
- iconChildWidth: iconWidth,
1435
- });
1436
- }
1437
-
1438
- function checkElementMotion(tag, style) {
1439
- return checkMotion({
1440
- tag,
1441
- transitionProperty: style.transitionProperty || '',
1442
- animationName: style.animationName || '',
1443
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
1444
- classList: '',
1445
- });
1446
- }
1447
-
1448
- function checkElementGlow(tag, style, effectiveBg) {
1449
- if (!style.boxShadow || style.boxShadow === 'none') return [];
1450
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
1451
- }
1452
-
1453
- // ─── Section 6: Page-Level Checks ───────────────────────────────────────────
1454
-
1455
- // Browser page-level checks — use document/getComputedStyle globals
1456
-
1457
- function checkTypography() {
1458
- const findings = [];
1459
-
1460
- // Walk actual text-bearing elements and tally font usage by *computed style*.
1461
- // This is much more accurate than scanning CSS rules — it ignores rules that
1462
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
1463
- // anti-patterns), and counts what the user actually sees.
1464
- const fontUsage = new Map(); // primary font name → count of elements
1465
- let totalTextElements = 0;
1466
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
1467
- // Skip impeccable's own elements
1468
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
1469
- // Only count elements that actually have visible direct text
1470
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
1471
- if (!hasText) continue;
1472
- const style = getComputedStyle(el);
1473
- const ff = style.fontFamily;
1474
- if (!ff) continue;
1475
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
1476
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
1477
- if (!primary) continue;
1478
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
1479
- totalTextElements++;
1480
- }
1481
-
1482
- if (totalTextElements >= 20) {
1483
- // A font is "primary" if it's used by at least 15% of text elements
1484
- const PRIMARY_THRESHOLD = 0.15;
1485
- for (const [font, count] of fontUsage) {
1486
- const share = count / totalTextElements;
1487
- if (share < PRIMARY_THRESHOLD) continue;
1488
- if (!OVERUSED_FONTS.has(font)) continue;
1489
- if (isBrandFontOnOwnDomain(font)) continue;
1490
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
1491
- }
1492
-
1493
- // Single-font check: only one distinct primary font across all text
1494
- if (fontUsage.size === 1) {
1495
- const only = [...fontUsage.keys()][0];
1496
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
1497
- }
1498
- }
1499
-
1500
- const sizes = new Set();
1501
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
1502
- const fs = parseFloat(getComputedStyle(el).fontSize);
1503
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
1504
- }
1505
- if (sizes.size >= 3) {
1506
- const sorted = [...sizes].sort((a, b) => a - b);
1507
- const ratio = sorted[sorted.length - 1] / sorted[0];
1508
- if (ratio < 2.0) {
1509
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
1510
- }
1511
- }
1512
-
1513
- return findings;
1514
- }
1515
-
1516
- function isCardLikeDOM(el) {
1517
- const tag = el.tagName.toLowerCase();
1518
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
1519
- const style = getComputedStyle(el);
1520
- const cls = el.getAttribute('class') || '';
1521
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
1522
- const hasBorder = /\bborder\b/.test(cls);
1523
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
1524
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
1525
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
1526
- }
1527
-
1528
- function checkLayout() {
1529
- const findings = [];
1530
- const flaggedEls = new Set();
1531
-
1532
- for (const el of document.querySelectorAll('*')) {
1533
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
1534
- const cls = el.getAttribute('class') || '';
1535
- const style = getComputedStyle(el);
1536
- if (style.position === 'absolute' || style.position === 'fixed') continue;
1537
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
1538
- if ((el.textContent?.trim().length || 0) < 10) continue;
1539
- const rect = el.getBoundingClientRect();
1540
- if (rect.width < 50 || rect.height < 30) continue;
1541
-
1542
- let parent = el.parentElement;
1543
- while (parent) {
1544
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
1545
- parent = parent.parentElement;
1546
- }
1547
- }
1548
-
1549
- for (const el of flaggedEls) {
1550
- let isAncestor = false;
1551
- for (const other of flaggedEls) {
1552
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
1553
- }
1554
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
1555
- }
1556
-
1557
- return findings;
1558
- }
1559
-
1560
- // Node page-level checks — take document/window as parameters
1561
-
1562
- function checkPageTypography(doc, win) {
1563
- const findings = [];
1564
-
1565
- const fonts = new Set();
1566
- const overusedFound = new Set();
1567
-
1568
- for (const sheet of doc.styleSheets) {
1569
- let rules;
1570
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
1571
- if (!rules) continue;
1572
- for (const rule of rules) {
1573
- if (rule.type !== 1) continue;
1574
- const ff = rule.style?.fontFamily;
1575
- if (!ff) continue;
1576
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
1577
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
1578
- if (primary) {
1579
- fonts.add(primary);
1580
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
1581
- }
1582
- }
1583
- }
1584
-
1585
- // Check Google Fonts links in HTML
1586
- const html = doc.documentElement?.outerHTML || '';
1587
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
1588
- let m;
1589
- while ((m = gfRe.exec(html)) !== null) {
1590
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
1591
- for (const f of families) {
1592
- fonts.add(f);
1593
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
1594
- }
1595
- }
1596
-
1597
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
1598
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
1599
- let fm;
1600
- while ((fm = ffRe.exec(html)) !== null) {
1601
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
1602
- if (f && !GENERIC_FONTS.has(f)) {
1603
- fonts.add(f);
1604
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
1605
- }
1606
- }
1607
- }
1608
-
1609
- for (const font of overusedFound) {
1610
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
1611
- }
1612
-
1613
- // Single font
1614
- if (fonts.size === 1) {
1615
- const els = doc.querySelectorAll('*');
1616
- if (els.length >= 20) {
1617
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
1618
- }
1619
- }
1620
-
1621
- // Flat type hierarchy
1622
- const sizes = new Set();
1623
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
1624
- for (const el of textEls) {
1625
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
1626
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
1627
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
1628
- }
1629
- if (sizes.size >= 3) {
1630
- const sorted = [...sizes].sort((a, b) => a - b);
1631
- const ratio = sorted[sorted.length - 1] / sorted[0];
1632
- if (ratio < 2.0) {
1633
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
1634
- }
1635
- }
1636
-
1637
- return findings;
1638
- }
1639
-
1640
- function isCardLike(el, win) {
1641
- const tag = el.tagName.toLowerCase();
1642
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
1643
-
1644
- const style = win.getComputedStyle(el);
1645
- const rawStyle = el.getAttribute?.('style') || '';
1646
- const cls = el.getAttribute?.('class') || '';
1647
-
1648
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
1649
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
1650
- const hasBorder = /\bborder\b/.test(cls);
1651
- const widthPx = parseFloat(style.width) || 0;
1652
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
1653
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
1654
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
1655
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
1656
-
1657
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
1658
- }
1659
-
1660
- function checkPageLayout(doc, win) {
1661
- const findings = [];
1662
-
1663
- // Nested cards
1664
- const allEls = doc.querySelectorAll('*');
1665
- const flaggedEls = new Set();
1666
- for (const el of allEls) {
1667
- if (!isCardLike(el, win)) continue;
1668
- if (flaggedEls.has(el)) continue;
1669
-
1670
- const tag = el.tagName.toLowerCase();
1671
- const cls = el.getAttribute?.('class') || '';
1672
- const rawStyle = el.getAttribute?.('style') || '';
1673
-
1674
- if (['pre', 'code'].includes(tag)) continue;
1675
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
1676
- if ((el.textContent?.trim().length || 0) < 10) continue;
1677
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
1678
-
1679
- // Walk up to find card-like ancestor
1680
- let parent = el.parentElement;
1681
- while (parent) {
1682
- if (isCardLike(parent, win)) {
1683
- flaggedEls.add(el);
1684
- break;
1685
- }
1686
- parent = parent.parentElement;
1687
- }
1688
- }
1689
-
1690
- // Only report innermost nested cards
1691
- for (const el of flaggedEls) {
1692
- let isAncestorOfFlagged = false;
1693
- for (const other of flaggedEls) {
1694
- if (other !== el && el.contains(other)) {
1695
- isAncestorOfFlagged = true;
1696
- break;
1697
- }
1698
- }
1699
- if (!isAncestorOfFlagged) {
1700
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
1701
- }
1702
- }
1703
-
1704
- // Everything centered
1705
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
1706
- let centeredCount = 0;
1707
- let totalText = 0;
1708
- for (const el of textEls) {
1709
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
1710
- if (!hasDirectText) continue;
1711
- totalText++;
1712
-
1713
- let cur = el;
1714
- let isCentered = false;
1715
- while (cur && cur.nodeType === 1) {
1716
- const rawStyle = cur.getAttribute?.('style') || '';
1717
- const cls = cur.getAttribute?.('class') || '';
1718
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
1719
- isCentered = true;
1720
- break;
1721
- }
1722
- if (cur.tagName === 'BODY') break;
1723
- cur = cur.parentElement;
1724
- }
1725
- if (isCentered) centeredCount++;
1726
- }
1727
-
1728
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
1729
- findings.push({
1730
- id: 'everything-centered',
1731
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
1732
- });
1733
- }
1734
-
1735
- return findings;
1736
- }
1737
-
1738
- // ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
1739
-
1740
- if (IS_BROWSER) {
1741
- // Detect extension mode via the script tag's data attribute or the document element fallback.
1742
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
1743
- const _myScript = document.currentScript;
1744
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
1745
- || document.documentElement.dataset.impeccableExtension === 'true';
1746
-
1747
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
1748
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
1749
- const LABEL_BG = BRAND_COLOR;
1750
- const OUTLINE_COLOR = BRAND_COLOR;
1751
-
1752
- // Inject hover styles via CSS (more reliable than JS event listeners)
1753
- const styleEl = document.createElement('style');
1754
- styleEl.textContent = `
1755
- @keyframes impeccable-reveal {
1756
- from { opacity: 0; }
1757
- to { opacity: 1; }
1758
- }
1759
- .impeccable-overlay:not(.impeccable-banner) {
1760
- pointer-events: none;
1761
- outline: 2px solid ${OUTLINE_COLOR};
1762
- border-radius: 4px;
1763
- transition: outline-color 0.15s ease;
1764
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
1765
- animation-play-state: paused;
1766
- border-top-left-radius: 0;
1767
- }
1768
- .impeccable-overlay.impeccable-visible {
1769
- animation-play-state: running;
1770
- }
1771
- .impeccable-overlay.impeccable-hover {
1772
- outline-color: ${BRAND_COLOR_HOVER};
1773
- z-index: 100001 !important;
1774
- }
1775
- .impeccable-overlay.impeccable-hover .impeccable-label {
1776
- background: ${BRAND_COLOR_HOVER};
1777
- }
1778
- .impeccable-overlay.impeccable-spotlight {
1779
- z-index: 100002 !important;
1780
- }
1781
- .impeccable-overlay.impeccable-spotlight-dimmed {
1782
- opacity: 0.15 !important;
1783
- animation: none !important;
1784
- filter: blur(3px);
1785
- }
1786
- .impeccable-spotlight-backdrop {
1787
- position: fixed;
1788
- top: 0; left: 0; right: 0; bottom: 0;
1789
- backdrop-filter: blur(3px) brightness(0.6);
1790
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
1791
- pointer-events: none;
1792
- z-index: 99998;
1793
- opacity: 0;
1794
- outline: none !important;
1795
- animation: none !important;
1796
- }
1797
- .impeccable-spotlight-backdrop.impeccable-visible {
1798
- opacity: 1;
1799
- }
1800
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
1801
- display: none !important;
1802
- }
1803
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
1804
- display: none !important;
1805
- }
1806
- `;
1807
- (document.head || document.documentElement).appendChild(styleEl);
1808
-
1809
- // Spotlight backdrop element (created lazily on first use)
1810
- let spotlightBackdrop = null;
1811
- let spotlightTarget = null;
1812
- let spotlightTimer = null;
1813
-
1814
- function getSpotlightBackdrop() {
1815
- if (!spotlightBackdrop) {
1816
- spotlightBackdrop = document.createElement('div');
1817
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
1818
- document.body.appendChild(spotlightBackdrop);
1819
- }
1820
- return spotlightBackdrop;
1821
- }
1822
-
1823
- function updateSpotlightClipPath() {
1824
- if (!spotlightBackdrop || !spotlightTarget) return;
1825
- const r = spotlightTarget.getBoundingClientRect();
1826
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
1827
- const inset = 4;
1828
- const radius = 6; // outline border-radius (4) + outline width (2)
1829
- const x1 = r.left - inset;
1830
- const y1 = r.top - inset;
1831
- const x2 = r.right + inset;
1832
- const y2 = r.bottom + inset;
1833
- const vw = window.innerWidth;
1834
- const vh = window.innerHeight;
1835
- // Outer rect + rounded inner rect (evenodd creates a hole)
1836
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
1837
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
1838
- }
1839
-
1840
- function showSpotlight(target) {
1841
- if (!target || !target.getBoundingClientRect) return;
1842
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
1843
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
1844
- spotlightTarget = target;
1845
- return;
1846
- }
1847
- spotlightTarget = target;
1848
- const bd = getSpotlightBackdrop();
1849
- updateSpotlightClipPath();
1850
- bd.classList.add('impeccable-visible');
1851
- }
1852
-
1853
- function hideSpotlight() {
1854
- spotlightTarget = null;
1855
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
1856
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
1857
- }
1858
-
1859
- function isInViewport(el) {
1860
- const r = el.getBoundingClientRect();
1861
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
1862
- }
1863
-
1864
- // Reposition spotlight on scroll/resize
1865
- window.addEventListener('scroll', () => {
1866
- if (spotlightTarget) updateSpotlightClipPath();
1867
- }, { passive: true });
1868
- window.addEventListener('resize', () => {
1869
- if (spotlightTarget) updateSpotlightClipPath();
1870
- });
1871
-
1872
- const overlays = [];
1873
- const TYPE_LABELS = {};
1874
- const RULE_CATEGORY = {};
1875
- for (const ap of ANTIPATTERNS) {
1876
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
1877
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
1878
- }
1879
-
1880
- function isInFixedContext(el) {
1881
- let p = el;
1882
- while (p && p !== document.body) {
1883
- if (getComputedStyle(p).position === 'fixed') return true;
1884
- p = p.parentElement;
1885
- }
1886
- return false;
1887
- }
1888
-
1889
- function positionOverlay(overlay) {
1890
- const el = overlay._targetEl;
1891
- if (!el) return;
1892
- const rect = el.getBoundingClientRect();
1893
- if (overlay._isFixed) {
1894
- // Viewport-relative coords for fixed targets
1895
- overlay.style.top = `${rect.top - 2}px`;
1896
- overlay.style.left = `${rect.left - 2}px`;
1897
- } else {
1898
- // Document-relative coords for normal targets
1899
- overlay.style.top = `${rect.top + scrollY - 2}px`;
1900
- overlay.style.left = `${rect.left + scrollX - 2}px`;
1901
- }
1902
- overlay.style.width = `${rect.width + 4}px`;
1903
- overlay.style.height = `${rect.height + 4}px`;
1904
- }
1905
-
1906
- function repositionOverlays() {
1907
- for (const o of overlays) {
1908
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
1909
- // Skip overlays whose target is currently hidden (display: none on the overlay)
1910
- if (o.style.display === 'none') continue;
1911
- positionOverlay(o);
1912
- }
1913
- }
1914
-
1915
- let resizeRAF;
1916
- const onResize = () => {
1917
- cancelAnimationFrame(resizeRAF);
1918
- resizeRAF = requestAnimationFrame(repositionOverlays);
1919
- };
1920
- window.addEventListener('resize', onResize);
1921
- // Reposition on scroll too -- catches sticky/parallax shifts
1922
- window.addEventListener('scroll', onResize, { passive: true });
1923
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
1924
- if (typeof ResizeObserver !== 'undefined') {
1925
- const bodyResizeObserver = new ResizeObserver(onResize);
1926
- bodyResizeObserver.observe(document.body);
1927
- }
1928
-
1929
- // Track target element visibility via IntersectionObserver.
1930
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
1931
- // while display:none / closed <details> / hidden modals etc. do not.
1932
- // This is event-driven -- no polling needed.
1933
- let overlayIndex = 0;
1934
- const visibilityObserver = new IntersectionObserver((entries) => {
1935
- for (const entry of entries) {
1936
- const overlay = entry.target._impeccableOverlay;
1937
- if (!overlay) continue;
1938
- if (entry.isIntersecting) {
1939
- overlay.style.display = '';
1940
- positionOverlay(overlay);
1941
- if (!overlay._revealed) {
1942
- overlay._revealed = true;
1943
- if (firstScanDone) {
1944
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
1945
- overlay.style.animation = 'none';
1946
- } else {
1947
- // Initial scan: staggered cascade reveal
1948
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
1949
- }
1950
- requestAnimationFrame(() => {
1951
- overlay.classList.add('impeccable-visible');
1952
- if (overlay._checkLabel) overlay._checkLabel();
1953
- });
1954
- }
1955
- } else {
1956
- overlay.style.display = 'none';
1957
- }
1958
- }
1959
- }, { rootMargin: '99999px' });
1960
-
1961
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
1962
- // Listens at document level so it catches transitions on ancestor elements
1963
- // (the transform may be on a parent, not the flagged element itself).
1964
- document.addEventListener('transitionend', (e) => {
1965
- if (e.propertyName !== 'transform') return;
1966
- for (const o of overlays) {
1967
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
1968
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
1969
- positionOverlay(o);
1970
- }
1971
- }
1972
- });
1973
-
1974
- const highlight = function(el, findings) {
1975
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
1976
-
1977
- const fixed = isInFixedContext(el);
1978
- const rect = el.getBoundingClientRect();
1979
- const outline = document.createElement('div');
1980
- outline.className = 'impeccable-overlay';
1981
- outline._targetEl = el;
1982
- outline._isFixed = fixed;
1983
- Object.assign(outline.style, {
1984
- position: fixed ? 'fixed' : 'absolute',
1985
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
1986
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
1987
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
1988
- zIndex: '99999', boxSizing: 'border-box',
1989
- });
1990
-
1991
- // Build per-finding label entries: ✦ prefix for slop
1992
- const entries = findings.map(f => {
1993
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
1994
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
1995
- return { name: prefix + name, detail: f.detail || f.snippet };
1996
- });
1997
- const allText = entries.map(e => e.name).join(', ');
1998
-
1999
- const label = document.createElement('div');
2000
- label.className = 'impeccable-label';
2001
- Object.assign(label.style, {
2002
- position: 'absolute', bottom: '100%', left: '-2px',
2003
- display: 'flex', alignItems: 'center',
2004
- whiteSpace: 'nowrap',
2005
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
2006
- color: 'white', lineHeight: '14px',
2007
- background: LABEL_BG,
2008
- fontFamily: 'system-ui, sans-serif',
2009
- borderRadius: '4px 4px 0 0',
2010
- });
2011
-
2012
- const textSpan = document.createElement('span');
2013
- textSpan.style.padding = '3px 8px';
2014
- textSpan.textContent = allText;
2015
- label.appendChild(textSpan);
2016
-
2017
- // State for cycling mode
2018
- let cycleMode = false;
2019
- let cycleIndex = 0;
2020
- let isHovered = false;
2021
- let prevBtn, nextBtn;
2022
-
2023
- function updateCycleText() {
2024
- const e = entries[cycleIndex];
2025
- textSpan.textContent = isHovered ? e.detail : e.name;
2026
- }
2027
-
2028
- function enableCycleMode() {
2029
- if (cycleMode || entries.length < 2) return;
2030
- cycleMode = true;
2031
-
2032
- const btnStyle = {
2033
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
2034
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
2035
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
2036
- pointerEvents: 'auto',
2037
- };
2038
-
2039
- const navGroup = document.createElement('span');
2040
- Object.assign(navGroup.style, {
2041
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
2042
- });
2043
-
2044
- prevBtn = document.createElement('button');
2045
- prevBtn.textContent = '\u2039';
2046
- Object.assign(prevBtn.style, btnStyle);
2047
- prevBtn.style.paddingLeft = '6px';
2048
- prevBtn.addEventListener('click', (e) => {
2049
- e.stopPropagation();
2050
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
2051
- updateCycleText();
2052
- });
2053
-
2054
- nextBtn = document.createElement('button');
2055
- nextBtn.textContent = '\u203A';
2056
- Object.assign(nextBtn.style, btnStyle);
2057
- nextBtn.style.paddingRight = '2px';
2058
- nextBtn.addEventListener('click', (e) => {
2059
- e.stopPropagation();
2060
- cycleIndex = (cycleIndex + 1) % entries.length;
2061
- updateCycleText();
2062
- });
2063
-
2064
- navGroup.appendChild(prevBtn);
2065
- navGroup.appendChild(nextBtn);
2066
- label.insertBefore(navGroup, textSpan);
2067
- textSpan.style.padding = '3px 8px 3px 4px';
2068
- updateCycleText();
2069
- }
2070
-
2071
- outline.appendChild(label);
2072
-
2073
- // Start hidden; the IntersectionObserver will show it once the target is rendered
2074
- outline.style.display = 'none';
2075
- outline._staggerIndex = overlayIndex++;
2076
- el._impeccableOverlay = outline;
2077
- visibilityObserver.observe(el);
2078
-
2079
- // After first paint, check label width vs outline
2080
- outline._checkLabel = () => {
2081
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
2082
- enableCycleMode();
2083
- }
2084
- };
2085
-
2086
- // Hover: show detail text, darken
2087
- el.addEventListener('mouseenter', () => {
2088
- isHovered = true;
2089
- outline.classList.add('impeccable-hover');
2090
- outline.style.outlineColor = BRAND_COLOR_HOVER;
2091
- label.style.background = BRAND_COLOR_HOVER;
2092
- if (cycleMode) {
2093
- updateCycleText();
2094
- } else {
2095
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
2096
- }
2097
- });
2098
- el.addEventListener('mouseleave', () => {
2099
- isHovered = false;
2100
- outline.classList.remove('impeccable-hover');
2101
- outline.style.outlineColor = '';
2102
- label.style.background = LABEL_BG;
2103
- if (cycleMode) {
2104
- updateCycleText();
2105
- } else {
2106
- textSpan.textContent = allText;
2107
- }
2108
- });
2109
-
2110
- document.body.appendChild(outline);
2111
- overlays.push(outline);
2112
- };
2113
-
2114
- const showPageBanner = function(findings) {
2115
- if (!findings.length) return;
2116
- const banner = document.createElement('div');
2117
- banner.className = 'impeccable-overlay impeccable-banner';
2118
- Object.assign(banner.style, {
2119
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
2120
- background: LABEL_BG, color: 'white',
2121
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
2122
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
2123
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
2124
- transform: 'translateY(-100%)',
2125
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
2126
- });
2127
- requestAnimationFrame(() => requestAnimationFrame(() => {
2128
- banner.style.transform = 'translateY(0)';
2129
- }));
2130
-
2131
- // Scrollable findings area
2132
- const scrollArea = document.createElement('div');
2133
- Object.assign(scrollArea.style, {
2134
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
2135
- display: 'flex', gap: '8px', alignItems: 'center',
2136
- padding: '0 12px', scrollSnapType: 'x mandatory',
2137
- scrollbarWidth: 'none',
2138
- });
2139
- for (const f of findings) {
2140
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
2141
- const tag = document.createElement('span');
2142
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
2143
- Object.assign(tag.style, {
2144
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
2145
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
2146
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
2147
- });
2148
- scrollArea.appendChild(tag);
2149
- }
2150
- banner.appendChild(scrollArea);
2151
-
2152
- // Controls area (only in standalone mode, not extension)
2153
- if (!EXTENSION_MODE) {
2154
- const controls = document.createElement('div');
2155
- Object.assign(controls.style, {
2156
- display: 'flex', alignItems: 'center', gap: '2px',
2157
- padding: '0 8px', flexShrink: '0',
2158
- });
2159
-
2160
- // Toggle visibility button
2161
- const toggle = document.createElement('button');
2162
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
2163
- toggle.title = 'Toggle overlay visibility';
2164
- Object.assign(toggle.style, {
2165
- background: 'none', border: 'none',
2166
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
2167
- opacity: '0.85', transition: 'opacity 0.15s',
2168
- });
2169
- let overlaysVisible = true;
2170
- toggle.addEventListener('click', () => {
2171
- overlaysVisible = !overlaysVisible;
2172
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
2173
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
2174
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
2175
- });
2176
- controls.appendChild(toggle);
2177
-
2178
- // Close button
2179
- const close = document.createElement('button');
2180
- close.textContent = '\u00d7';
2181
- close.title = 'Dismiss banner';
2182
- Object.assign(close.style, {
2183
- background: 'none', border: 'none',
2184
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
2185
- });
2186
- close.addEventListener('click', () => banner.remove());
2187
- controls.appendChild(close);
2188
-
2189
- banner.appendChild(controls);
2190
- }
2191
- document.body.appendChild(banner);
2192
- overlays.push(banner);
2193
- };
2194
-
2195
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
2196
- // These change between builds and produce brittle, ugly selectors.
2197
- function isLikelyHashedClass(c) {
2198
- if (!c) return true;
2199
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
2200
- if (/^_[\w-]{5,}$/.test(c)) return true;
2201
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
2202
- return false;
2203
- }
2204
-
2205
- function buildSelectorSegment(el) {
2206
- const tag = el.tagName.toLowerCase();
2207
- let sel = tag;
2208
-
2209
- if (el.classList && el.classList.length > 0) {
2210
- const classes = [...el.classList]
2211
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
2212
- .slice(0, 2);
2213
- if (classes.length > 0) {
2214
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
2215
- }
2216
- }
2217
-
2218
- // Disambiguate among siblings only if the parent has multiple matches
2219
- const parent = el.parentElement;
2220
- if (parent) {
2221
- try {
2222
- const matching = parent.querySelectorAll(':scope > ' + sel);
2223
- if (matching.length > 1) {
2224
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
2225
- const idx = sameType.indexOf(el) + 1;
2226
- sel += `:nth-of-type(${idx})`;
2227
- }
2228
- } catch {
2229
- const idx = [...parent.children].indexOf(el) + 1;
2230
- sel = `${tag}:nth-child(${idx})`;
2231
- }
2232
- }
2233
- return sel;
2234
- }
2235
-
2236
- function generateSelector(el) {
2237
- if (el === document.body) return 'body';
2238
- if (el === document.documentElement) return 'html';
2239
- if (el.id) return '#' + CSS.escape(el.id);
2240
-
2241
- const parts = [];
2242
- let current = el;
2243
- let depth = 0;
2244
- const MAX_DEPTH = 10;
2245
-
2246
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
2247
- parts.unshift(buildSelectorSegment(current));
2248
-
2249
- // Anchor on an ancestor's ID and stop walking up
2250
- if (current.id) {
2251
- parts[0] = '#' + CSS.escape(current.id);
2252
- break;
2253
- }
2254
-
2255
- // Stop as soon as the partial selector uniquely identifies the target
2256
- const trySelector = parts.join(' > ');
2257
- try {
2258
- const matches = document.querySelectorAll(trySelector);
2259
- if (matches.length === 1 && matches[0] === el) {
2260
- return trySelector;
2261
- }
2262
- } catch { /* invalid selector — keep walking */ }
2263
-
2264
- current = current.parentElement;
2265
- depth++;
2266
- }
2267
-
2268
- return parts.join(' > ');
2269
- }
2270
-
2271
- function isElementHidden(el) {
2272
- if (!el || el === document.body || el === document.documentElement) return false;
2273
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
2274
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
2275
- return el.offsetWidth === 0 && el.offsetHeight === 0;
2276
- }
2277
-
2278
- function serializeFindings(allFindings) {
2279
- return allFindings.map(({ el, findings }) => ({
2280
- selector: generateSelector(el),
2281
- tagName: el.tagName?.toLowerCase() || 'unknown',
2282
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
2283
- ? el.getBoundingClientRect().toJSON() : null,
2284
- isPageLevel: el === document.body || el === document.documentElement,
2285
- isHidden: isElementHidden(el),
2286
- findings: findings.map(f => {
2287
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
2288
- return {
2289
- type: f.type || f.id,
2290
- category: ap ? ap.category : 'quality',
2291
- detail: f.detail || f.snippet,
2292
- name: ap ? ap.name : (f.type || f.id),
2293
- description: ap ? ap.description : '',
2294
- };
2295
- }),
2296
- }));
2297
- }
2298
-
2299
- const printSummary = function(allFindings) {
2300
- if (allFindings.length === 0) {
2301
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
2302
- return;
2303
- }
2304
- console.group(
2305
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
2306
- 'color: oklch(60% 0.25 350); font-weight: bold'
2307
- );
2308
- for (const { el, findings } of allFindings) {
2309
- for (const f of findings) {
2310
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
2311
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
2312
- }
2313
- }
2314
- console.groupEnd();
2315
- };
2316
-
2317
- let firstScanDone = false;
2318
- const scan = function() {
2319
- for (const o of overlays) o.remove();
2320
- overlays.length = 0;
2321
- visibilityObserver.disconnect();
2322
- overlayIndex = 0;
2323
- const allFindings = [];
2324
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
2325
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
2326
-
2327
- for (const el of document.querySelectorAll('*')) {
2328
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
2329
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
2330
- // Skip browser extension elements (Claude, etc.)
2331
- const elId = el.id || '';
2332
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
2333
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
2334
- // These are inspector chrome, not part of the user's design.
2335
- if (el.closest('[id^="impeccable-live-"]')) continue;
2336
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
2337
- if (el === document.body || el === document.documentElement) continue;
2338
-
2339
- const findings = [
2340
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2341
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2342
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2343
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2344
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2345
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2346
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2347
- ].filter(f => _ruleOk(f.type));
2348
-
2349
- if (findings.length > 0) {
2350
- highlight(el, findings);
2351
- allFindings.push({ el, findings });
2352
- }
2353
- }
2354
-
2355
- const pageLevelFindings = [];
2356
-
2357
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
2358
- if (typoFindings.length > 0) {
2359
- pageLevelFindings.push(...typoFindings);
2360
- allFindings.push({ el: document.body, findings: typoFindings });
2361
- }
2362
-
2363
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
2364
- for (const f of layoutFindings) {
2365
- const el = f.el || document.body;
2366
- delete f.el;
2367
- // Merge into existing overlay if this element already has one
2368
- const existing = el._impeccableOverlay;
2369
- if (existing) {
2370
- const nameRow = existing.querySelector('.impeccable-label-name');
2371
- const detailRow = existing.querySelector('.impeccable-label-detail');
2372
- const newType = TYPE_LABELS[f.type] || f.type;
2373
- if (nameRow) nameRow.textContent += ', ' + newType;
2374
- if (detailRow) detailRow.textContent += ' | ' + (f.detail || '');
2375
- } else {
2376
- highlight(el, [f]);
2377
- }
2378
- allFindings.push({ el, findings: [f] });
2379
- }
2380
-
2381
- // Page-level quality checks (headings, etc.)
2382
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
2383
- if (qualityFindings.length > 0) {
2384
- pageLevelFindings.push(...qualityFindings);
2385
- allFindings.push({ el: document.body, findings: qualityFindings });
2386
- }
2387
-
2388
- // Regex-on-HTML checks (shared with Node)
2389
- // Clone the document and strip impeccable-live overlay nodes before the
2390
- // regex scan, so the inspector's own inline styles (transitions on top/
2391
- // left/width/height, etc.) don't register as page anti-patterns.
2392
- const docClone = document.documentElement.cloneNode(true);
2393
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
2394
- node.remove();
2395
- }
2396
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
2397
- if (htmlPatternFindings.length > 0) {
2398
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
2399
- pageLevelFindings.push(...mapped);
2400
- allFindings.push({ el: document.body, findings: mapped });
2401
- }
2402
-
2403
- if (pageLevelFindings.length > 0) {
2404
- showPageBanner(pageLevelFindings);
2405
- }
2406
-
2407
- if (!EXTENSION_MODE) printSummary(allFindings);
2408
-
2409
- // In extension mode, post serialized results for the DevTools panel
2410
- if (EXTENSION_MODE) {
2411
- window.postMessage({
2412
- source: 'impeccable-results',
2413
- findings: serializeFindings(allFindings),
2414
- count: allFindings.length,
2415
- }, '*');
2416
- }
2417
-
2418
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
2419
- setTimeout(() => { firstScanDone = true; }, 1000);
2420
-
2421
- return allFindings;
2422
- };
2423
-
2424
- if (EXTENSION_MODE) {
2425
- // Extension mode: listen for commands, don't auto-scan
2426
- window.addEventListener('message', (e) => {
2427
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
2428
- if (e.data.action === 'scan') {
2429
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
2430
- scan();
2431
- }
2432
- if (e.data.action === 'toggle-overlays') {
2433
- const visible = !document.body.classList.contains('impeccable-hidden');
2434
- document.body.classList.toggle('impeccable-hidden', visible);
2435
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
2436
- }
2437
- if (e.data.action === 'remove') {
2438
- for (const o of overlays) o.remove();
2439
- overlays.length = 0;
2440
- visibilityObserver.disconnect();
2441
- styleEl.remove();
2442
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
2443
- document.body.classList.remove('impeccable-hidden');
2444
- }
2445
- if (e.data.action === 'highlight') {
2446
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
2447
- try {
2448
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
2449
- if (target) {
2450
- // Scroll first so positionOverlay reads the post-scroll rect
2451
- if (!isInViewport(target) && target.scrollIntoView) {
2452
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
2453
- }
2454
- for (const o of overlays) {
2455
- if (o.classList.contains('impeccable-banner')) continue;
2456
- const isMatch = o._targetEl === target;
2457
- o.classList.toggle('impeccable-spotlight', isMatch);
2458
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
2459
- if (isMatch) {
2460
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
2461
- o.style.display = '';
2462
- o.style.animation = 'none';
2463
- o.classList.add('impeccable-visible');
2464
- o._revealed = true;
2465
- positionOverlay(o);
2466
- }
2467
- }
2468
- showSpotlight(target);
2469
- }
2470
- } catch { /* invalid selector */ }
2471
- }
2472
- if (e.data.action === 'unhighlight') {
2473
- hideSpotlight();
2474
- for (const o of overlays) {
2475
- o.classList.remove('impeccable-spotlight');
2476
- o.classList.remove('impeccable-spotlight-dimmed');
2477
- }
2478
- }
2479
- });
2480
- window.postMessage({ source: 'impeccable-ready' }, '*');
2481
- } else {
2482
- if (document.readyState === 'loading') {
2483
- document.addEventListener('DOMContentLoaded', () => setTimeout(scan, 100));
2484
- } else {
2485
- setTimeout(scan, 100);
2486
- }
2487
- }
2488
-
2489
- window.impeccableScan = scan;
2490
- }
2491
-
2492
- // ─── Section 8: Node Engine ─────────────────────────────────────────────────
2493
-
2494
- // ─── Section 9: Exports ─────────────────────────────────────────────────────
2495
-
2496
- })();