Hide overlays for non-rendered elements using IntersectionObserver

Overlays are now created hidden and revealed by an IntersectionObserver
(rootMargin: 99999px), so they automatically show/hide when their target
becomes visible or invisible -- handles closed <details>, display:none,
hidden modals, overflow:hidden clipping, etc. without polling.

Adds overlay-positioning.html test fixture with 9 scenario groups
covering transforms, closed details, sticky, overflow, position offsets,
flex/grid, containing-block creators, and combinations.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Paul Bakaus
2026-03-27 23:12:24 -07:00
co-authored by Claude Opus 4.6
parent 3f86b72c88
commit 9ffa802c89
4 changed files with 693 additions and 0 deletions
@@ -1262,6 +1262,27 @@ if (IS_BROWSER) {
};
window.addEventListener('resize', onResize);
// Track target element visibility via IntersectionObserver.
// Uses a huge rootMargin so all *rendered* elements count as intersecting,
// while display:none / closed <details> / hidden modals etc. do not.
// This is event-driven -- no polling needed.
const visibilityObserver = new IntersectionObserver((entries) => {
for (const entry of entries) {
const overlay = entry.target._impeccableOverlay;
if (!overlay) continue;
if (entry.isIntersecting) {
overlay.style.display = '';
const rect = entry.target.getBoundingClientRect();
overlay.style.top = `${rect.top + scrollY - 2}px`;
overlay.style.left = `${rect.left + scrollX - 2}px`;
overlay.style.width = `${rect.width + 4}px`;
overlay.style.height = `${rect.height + 4}px`;
} else {
overlay.style.display = 'none';
}
}
}, { rootMargin: '99999px' });
const highlight = function(el, findings) {
const rect = el.getBoundingClientRect();
const outline = document.createElement('div');
@@ -1299,6 +1320,11 @@ if (IS_BROWSER) {
});
outline.appendChild(tooltip);
// Start hidden; the IntersectionObserver will show it once the target is rendered
outline.style.display = 'none';
el._impeccableOverlay = outline;
visibilityObserver.observe(el);
document.body.appendChild(outline);
overlays.push(outline);
};
@@ -1356,6 +1382,7 @@ if (IS_BROWSER) {
const scan = function() {
for (const o of overlays) o.remove();
overlays.length = 0;
visibilityObserver.disconnect();
const allFindings = [];
for (const el of document.querySelectorAll('*')) {
@@ -1260,6 +1260,27 @@ if (IS_BROWSER) {
};
window.addEventListener('resize', onResize);
// Track target element visibility via IntersectionObserver.
// Uses a huge rootMargin so all *rendered* elements count as intersecting,
// while display:none / closed <details> / hidden modals etc. do not.
// This is event-driven -- no polling needed.
const visibilityObserver = new IntersectionObserver((entries) => {
for (const entry of entries) {
const overlay = entry.target._impeccableOverlay;
if (!overlay) continue;
if (entry.isIntersecting) {
overlay.style.display = '';
const rect = entry.target.getBoundingClientRect();
overlay.style.top = `${rect.top + scrollY - 2}px`;
overlay.style.left = `${rect.left + scrollX - 2}px`;
overlay.style.width = `${rect.width + 4}px`;
overlay.style.height = `${rect.height + 4}px`;
} else {
overlay.style.display = 'none';
}
}
}, { rootMargin: '99999px' });
const highlight = function(el, findings) {
const rect = el.getBoundingClientRect();
const outline = document.createElement('div');
@@ -1297,6 +1318,11 @@ if (IS_BROWSER) {
});
outline.appendChild(tooltip);
// Start hidden; the IntersectionObserver will show it once the target is rendered
outline.style.display = 'none';
el._impeccableOverlay = outline;
visibilityObserver.observe(el);
document.body.appendChild(outline);
overlays.push(outline);
};
@@ -1354,6 +1380,7 @@ if (IS_BROWSER) {
const scan = function() {
for (const o of overlays) o.remove();
overlays.length = 0;
visibilityObserver.disconnect();
const allFindings = [];
for (const el of document.querySelectorAll('*')) {
+115
View File
@@ -149,3 +149,118 @@ describeIf('browser script parity with CLI', () => {
// Browser script doesn't have isFullPage check, so we just verify borders work
}, 15000);
});
describeIf('overlay positioning accuracy', () => {
let browser, page;
const TOLERANCE = 6; // px tolerance for position comparison (2px border offset + rounding)
beforeAll(async () => {
// Reuse same server setup — these tests run in the same suite
serverProcess = spawn('node', ['-e', `
const http = require('http');
const fs = require('fs');
const path = require('path');
const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript' };
http.createServer((req, res) => {
let filePath;
if (req.url.startsWith('/fixtures/')) {
filePath = path.join(${JSON.stringify(path.join(import.meta.dir))}, req.url);
} else if (req.url.startsWith('/js/')) {
const basename = req.url.split('/').pop();
filePath = path.join(${JSON.stringify(path.join(import.meta.dir, '..', 'public'))}, req.url);
if (!fs.existsSync(filePath)) {
filePath = path.join(${JSON.stringify(path.join(import.meta.dir, '..', '.claude', 'skills', 'critique', 'scripts'))}, basename);
}
} else {
res.writeHead(404); res.end(); return;
}
try {
const content = fs.readFileSync(filePath);
const ext = path.extname(filePath);
res.writeHead(200, { 'Content-Type': types[ext] || 'text/plain' });
res.end(content);
} catch { res.writeHead(404); res.end(); }
}).listen(${PORT + 1});
`], { stdio: 'ignore' });
await new Promise(r => setTimeout(r, 500));
browser = await puppeteer.default.launch({ headless: true });
page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 });
await page.goto(`http://localhost:${PORT + 1}/fixtures/antipatterns/overlay-positioning.html`, {
waitUntil: 'networkidle0',
timeout: 10000,
});
await new Promise(r => setTimeout(r, 300));
await page.evaluate(() => {
if (window.impeccableScan) window.impeccableScan();
});
await new Promise(r => setTimeout(r, 200));
});
afterAll(async () => {
if (browser) await browser.close();
if (serverProcess) serverProcess.kill();
});
async function getOverlayPositions() {
return page.evaluate(() => {
const overlays = document.querySelectorAll('.impeccable-overlay:not(.impeccable-banner)');
return Array.from(overlays).map(o => {
const t = o._targetEl;
if (!t) return null;
const tRect = t.getBoundingClientRect();
const oRect = o.getBoundingClientRect();
const label = o.querySelector('.impeccable-label')?.textContent || '';
return {
label,
target: { top: tRect.top, left: tRect.left, width: tRect.width, height: tRect.height },
overlay: { top: oRect.top, left: oRect.left, width: oRect.width, height: oRect.height },
overlayHidden: o.style.display === 'none',
targetVisible: tRect.width > 0 && tRect.height > 0,
inClosedDetails: !!t.closest('details:not([open])'),
};
}).filter(Boolean);
});
}
test('visible overlays are positioned within tolerance of their targets', async () => {
const positions = await getOverlayPositions();
const visible = positions.filter(p => !p.overlayHidden);
expect(visible.length).toBeGreaterThan(0);
for (const p of visible) {
const topDiff = Math.abs(p.overlay.top - p.target.top);
const leftDiff = Math.abs(p.overlay.left - p.target.left);
const widthDiff = Math.abs(p.overlay.width - p.target.width);
const heightDiff = Math.abs(p.overlay.height - p.target.height);
expect(topDiff).toBeLessThanOrEqual(TOLERANCE);
expect(leftDiff).toBeLessThanOrEqual(TOLERANCE);
expect(widthDiff).toBeLessThanOrEqual(TOLERANCE);
expect(heightDiff).toBeLessThanOrEqual(TOLERANCE);
}
}, 20000);
test('overlays for non-rendered elements are hidden', async () => {
const positions = await getOverlayPositions();
// Elements inside closed <details> should have hidden overlays
const closedDetailsOverlays = positions.filter(p => p.inClosedDetails);
expect(closedDetailsOverlays.length).toBeGreaterThan(0);
for (const p of closedDetailsOverlays) {
expect(p.overlayHidden).toBe(true);
}
}, 20000);
test('overlays inside transform ancestors are accurately positioned', async () => {
const positions = await getOverlayPositions();
const visible = positions.filter(p => !p.overlayHidden);
for (const p of visible) {
const topDiff = Math.abs(p.overlay.top - p.target.top);
const leftDiff = Math.abs(p.overlay.left - p.target.left);
expect(topDiff).toBeLessThanOrEqual(TOLERANCE);
expect(leftDiff).toBeLessThanOrEqual(TOLERANCE);
}
}, 20000);
});
+524
View File
@@ -0,0 +1,524 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Overlay Positioning Edge Cases</title>
<style>
body {
font-family: system-ui, sans-serif;
background: #f9fafb;
padding: 2rem;
max-width: 900px;
margin: 0 auto;
}
h1 { font-size: 2rem; margin-bottom: 0.5rem; }
h2 { font-size: 1.125rem; margin: 2.5rem 0 0.75rem; color: #6b7280; border-bottom: 1px solid #e5e7eb; padding-bottom: 0.5rem; }
.scenario { margin-bottom: 2rem; padding: 1rem; border: 1px dashed #d1d5db; border-radius: 8px; }
.scenario-label { font-size: 0.75rem; color: #6b7280; margin-bottom: 0.5rem; text-transform: uppercase; letter-spacing: 0.05em; }
/* ============================================
1. TRANSFORM ANCESTOR
position:absolute overlays on body use document coords,
but getBoundingClientRect is viewport-relative.
Transforms on ancestors create new stacking contexts.
============================================ */
.transform-container {
transform: translateY(0);
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
.transform-rotate {
transform: rotate(0deg);
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
.transform-scale {
transform: scale(1);
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
.transform-nested-outer {
transform: translateX(0);
padding: 1rem;
background: #e5e7eb;
border-radius: 8px;
}
.transform-nested-inner {
transform: translateY(0);
padding: 1rem;
background: #d1d5db;
border-radius: 8px;
}
/* ============================================
2. CLOSED <details>
Elements inside collapsed details may report
a bounding rect but aren't visually present.
============================================ */
details { margin-bottom: 1rem; }
summary { cursor: pointer; font-weight: 600; }
/* ============================================
3. STICKY / FIXED POSITIONING
Sticky elements change their containing block
behavior during scroll.
============================================ */
.sticky-container {
height: 200px;
overflow-y: auto;
border: 1px solid #d1d5db;
border-radius: 8px;
}
.sticky-header {
position: sticky;
top: 0;
background: #1f2937;
color: white;
padding: 0.5rem 1rem;
z-index: 10;
}
.sticky-content {
padding: 1rem;
}
/* ============================================
4. OVERFLOW HIDDEN
Elements that extend beyond an overflow:hidden
parent are visually clipped but still in the DOM.
============================================ */
.overflow-hidden-container {
overflow: hidden;
height: 60px;
border: 1px solid #d1d5db;
border-radius: 8px;
padding: 0.5rem 1rem;
}
/* ============================================
5. ABSOLUTE / RELATIVE POSITIONING
Elements that are offset from their normal flow
position via top/left.
============================================ */
.relative-offset {
position: relative;
top: 20px;
left: 40px;
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
.absolute-container {
position: relative;
height: 120px;
background: #f3f4f6;
border-radius: 8px;
}
.absolute-child {
position: absolute;
bottom: 10px;
right: 10px;
}
/* ============================================
6. FLEXBOX / GRID CENTERING
Elements centered via flex/grid may have
unexpected positions vs. document flow.
============================================ */
.flex-center {
display: flex;
justify-content: center;
align-items: center;
height: 120px;
background: #f3f4f6;
border-radius: 8px;
}
.grid-center {
display: grid;
place-items: center;
height: 120px;
background: #f3f4f6;
border-radius: 8px;
}
/* ============================================
7. WILL-CHANGE / CONTAIN / FILTER
These CSS properties create new containing
blocks, similar to transforms.
============================================ */
.will-change-container {
will-change: transform;
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
.contain-container {
contain: layout;
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
.filter-container {
filter: brightness(1);
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
.backdrop-filter-container {
backdrop-filter: blur(0px);
padding: 1rem;
background: #f3f4f6;
border-radius: 8px;
}
/* ============================================
8. MARGIN COLLAPSE / NEGATIVE MARGINS
Elements with collapsed or negative margins
can shift from expected position.
============================================ */
.negative-margin-container {
padding: 2rem;
background: #f3f4f6;
border-radius: 8px;
}
.negative-margin-child {
margin-top: -1rem;
margin-left: -1rem;
}
/* ============================================
Anti-pattern triggers (tiny-text, cramped, ai-color)
used across scenarios.
============================================ */
.tiny { font-size: 10px; color: #374151; line-height: 1.4; }
.cramped-box { border: 1px solid #d1d5db; padding: 3px; font-size: 14px; border-radius: 4px; }
.ai-btn { background: linear-gradient(135deg, #8b5cf6, #6366f1); color: white; padding: 8px 16px; border: none; border-radius: 6px; font-size: 14px; cursor: pointer; }
.side-tab-card { border-left: 4px solid #8b5cf6; padding: 1rem; background: white; border-radius: 0 8px 8px 0; }
</style>
</head>
<body>
<h1>Overlay Positioning Edge Cases</h1>
<p>Each scenario places a detectable anti-pattern inside a layout context that can cause overlay misalignment.</p>
<!-- ═══════════════════════════════════════════
1. TRANSFORM ANCESTORS
═══════════════════════════════════════════ -->
<h2>1. Transform Ancestors</h2>
<div class="scenario">
<div class="scenario-label">1a. translateY(0) container</div>
<div class="transform-container">
<span class="tiny">This tiny text is inside a transform: translateY(0) container. The overlay should frame this text precisely.</span>
</div>
</div>
<div class="scenario">
<div class="scenario-label">1b. rotate(0deg) container</div>
<div class="transform-rotate">
<span class="tiny">Tiny text inside a transform: rotate(0deg) container.</span>
</div>
</div>
<div class="scenario">
<div class="scenario-label">1c. scale(1) container</div>
<div class="transform-scale">
<div class="cramped-box">Cramped text inside a transform: scale(1) container.</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">1d. Nested transforms</div>
<div class="transform-nested-outer">
<div class="transform-nested-inner">
<span class="tiny">Tiny text nested inside two levels of transformed parents.</span>
</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">1e. Transform + absolute child</div>
<div class="transform-container" style="position: relative; height: 100px;">
<div style="position: absolute; bottom: 8px; right: 8px;">
<span class="tiny">Absolutely positioned tiny text inside transformed parent.</span>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
2. CLOSED <details>
═══════════════════════════════════════════ -->
<h2>2. Closed Details</h2>
<div class="scenario">
<div class="scenario-label">2a. Closed details with anti-pattern inside</div>
<details>
<summary>Click to expand (closed by default)</summary>
<span class="tiny">This tiny text is hidden inside a closed details element. No overlay should appear for it.</span>
<div class="cramped-box">Cramped text also hidden inside closed details.</div>
</details>
</div>
<div class="scenario">
<div class="scenario-label">2b. Open details with anti-pattern inside</div>
<details open>
<summary>This details is open</summary>
<span class="tiny">This tiny text IS visible because details is open. Overlay should frame it correctly.</span>
</details>
</div>
<div class="scenario">
<div class="scenario-label">2c. Nested details (outer open, inner closed)</div>
<details open>
<summary>Outer details (open)</summary>
<p>Some visible content.</p>
<details>
<summary>Inner details (closed)</summary>
<span class="tiny">Hidden tiny text inside nested closed details.</span>
</details>
</details>
</div>
<div class="scenario">
<div class="scenario-label">2d. Transform inside closed details</div>
<details>
<summary>Closed with transform inside</summary>
<div class="transform-container">
<span class="tiny">Tiny text inside transform inside closed details. Double trouble.</span>
</div>
</details>
</div>
<!-- ═══════════════════════════════════════════
3. STICKY / FIXED
═══════════════════════════════════════════ -->
<h2>3. Sticky and Fixed Positioning</h2>
<div class="scenario">
<div class="scenario-label">3a. Sticky header inside scrollable container</div>
<div class="sticky-container">
<div class="sticky-header">
<span class="tiny">Tiny text in a sticky header.</span>
</div>
<div class="sticky-content">
<p>Scroll this container to test sticky behavior.</p>
<p>More content to enable scrolling.</p>
<p>Even more content here.</p>
<div class="cramped-box">Cramped text below the sticky header.</div>
<p>Additional content.</p>
<p>More filler text.</p>
</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">3b. Fixed-like element (within containing block)</div>
<div style="position: relative; height: 80px; background: #f3f4f6; border-radius: 8px;">
<div style="position: fixed; /* won't actually be fixed due to test context */ bottom: 0; left: 0; right: 0; background: #1f2937; color: white; padding: 0.5rem;">
<span class="tiny">Tiny text in a would-be fixed footer.</span>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
4. OVERFLOW HIDDEN
═══════════════════════════════════════════ -->
<h2>4. Overflow Hidden</h2>
<div class="scenario">
<div class="scenario-label">4a. Content clipped by overflow:hidden</div>
<div class="overflow-hidden-container">
<p>This paragraph is visible.</p>
<span class="tiny">This tiny text is below the overflow cutoff, clipped but still in DOM.</span>
<p>This content is also clipped away.</p>
</div>
</div>
<div class="scenario">
<div class="scenario-label">4b. overflow:hidden + transform ancestor</div>
<div class="transform-container">
<div class="overflow-hidden-container">
<p>Visible inside transform + overflow.</p>
<span class="tiny">Clipped tiny text inside a transformed overflow:hidden container.</span>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
5. ABSOLUTE / RELATIVE OFFSETS
═══════════════════════════════════════════ -->
<h2>5. Position Offsets</h2>
<div class="scenario">
<div class="scenario-label">5a. Relative position with top/left offset</div>
<div class="relative-offset">
<span class="tiny">This tiny text is shifted via position:relative + top/left offset.</span>
</div>
<div style="height: 30px;"></div><!-- spacer for the offset -->
</div>
<div class="scenario">
<div class="scenario-label">5b. Absolute child in relative parent</div>
<div class="absolute-container">
<p>Normal flow content at top.</p>
<div class="absolute-child">
<span class="tiny">Absolutely positioned tiny text at bottom-right.</span>
</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">5c. Negative top offset</div>
<div style="padding-top: 2rem;">
<div style="position: relative; top: -1rem;">
<span class="tiny">Tiny text pulled upward via negative top offset.</span>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
6. FLEX / GRID CENTERING
═══════════════════════════════════════════ -->
<h2>6. Flex and Grid Centering</h2>
<div class="scenario">
<div class="scenario-label">6a. Flex-centered anti-pattern</div>
<div class="flex-center">
<span class="tiny">Centered tiny text inside a flex container.</span>
</div>
</div>
<div class="scenario">
<div class="scenario-label">6b. Grid-centered anti-pattern</div>
<div class="grid-center">
<div class="cramped-box">Cramped text inside a grid-centered container.</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">6c. Flex with transform</div>
<div class="flex-center transform-container">
<button class="ai-btn">AI Gradient Button in Flex + Transform</button>
</div>
</div>
<!-- ═══════════════════════════════════════════
7. WILL-CHANGE / CONTAIN / FILTER
═══════════════════════════════════════════ -->
<h2>7. Containing Block Creators</h2>
<div class="scenario">
<div class="scenario-label">7a. will-change: transform</div>
<div class="will-change-container">
<span class="tiny">Tiny text inside a will-change: transform container.</span>
</div>
</div>
<div class="scenario">
<div class="scenario-label">7b. contain: layout</div>
<div class="contain-container">
<span class="tiny">Tiny text inside a contain: layout container.</span>
</div>
</div>
<div class="scenario">
<div class="scenario-label">7c. filter: brightness(1)</div>
<div class="filter-container">
<span class="tiny">Tiny text inside a filter container (creates containing block).</span>
</div>
</div>
<div class="scenario">
<div class="scenario-label">7d. backdrop-filter</div>
<div class="backdrop-filter-container">
<span class="tiny">Tiny text inside a backdrop-filter container.</span>
</div>
</div>
<!-- ═══════════════════════════════════════════
8. NEGATIVE MARGINS
═══════════════════════════════════════════ -->
<h2>8. Margin Collapse and Negative Margins</h2>
<div class="scenario">
<div class="scenario-label">8a. Negative margin shifting element position</div>
<div class="negative-margin-container">
<div class="negative-margin-child">
<span class="tiny">Tiny text pulled out of its parent via negative margins.</span>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
9. COMBINATION SCENARIOS
═══════════════════════════════════════════ -->
<h2>9. Combined Edge Cases</h2>
<div class="scenario">
<div class="scenario-label">9a. Transform + sticky + overflow</div>
<div class="transform-container">
<div class="sticky-container">
<div class="sticky-header">
<span class="tiny">Tiny text in sticky header inside transform inside scrollable overflow.</span>
</div>
<div class="sticky-content">
<p>Scroll content line 1.</p>
<p>Scroll content line 2.</p>
<p>Scroll content line 3.</p>
<div class="cramped-box">Cramped box scrolled below sticky.</div>
<p>Scroll content line 4.</p>
<p>Scroll content line 5.</p>
</div>
</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">9b. Closed details + transform + flex</div>
<details>
<summary>Closed combo scenario</summary>
<div class="flex-center transform-container">
<span class="tiny">Triple-nested: closed details > flex > transform > tiny text.</span>
</div>
</details>
</div>
<div class="scenario">
<div class="scenario-label">9c. Grid + absolute + transform</div>
<div class="grid-center" style="position: relative; height: 150px;">
<div class="transform-container" style="position: absolute; top: 10px; left: 10px; right: 10px;">
<span class="tiny">Absolute inside grid inside transform: overlays must track all three contexts.</span>
</div>
<div style="position: absolute; bottom: 10px; right: 10px;">
<div class="cramped-box">Absolute cramped box at bottom-right of grid.</div>
</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">9d. Overflow hidden + absolute breakout</div>
<div style="position: relative; overflow: hidden; height: 80px; background: #f3f4f6; border-radius: 8px; padding: 1rem;">
<p>Visible content.</p>
<div style="position: absolute; bottom: -20px; left: 0; right: 0;">
<span class="tiny">Absolute-positioned tiny text that breaks out below overflow:hidden.</span>
</div>
</div>
</div>
<div class="scenario">
<div class="scenario-label">9e. Side-tab card inside transform + relative offset</div>
<div class="transform-container">
<div style="position: relative; left: 50px;">
<div class="side-tab-card">
This card has a side-tab border accent and is offset inside a transform container.
</div>
</div>
</div>
</div>
<script src="/js/detect-antipatterns-browser.js"></script>
</body>
</html>