Skip to content

The design language that makes your AI harness better at design.

JavaScript

Fix: keep live chrome usable while a native modal dialog is open (#879)

Abdul Wahabe727d00e7c55
diff --git a/browser-bundle/40-overlay.js b/browser-bundle/40-overlay.js
index 7f912d489..8e49c462c 100644
--- a/browser-bundle/40-overlay.js
+++ b/browser-bundle/40-overlay.js
@@ -206,6 +206,29 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
overlay.style.height = `${rect.height + 4}px`;
}
+ // Where an outline lives and which coordinates it takes. A modal <dialog>
+ // paints over everything outside its subtree, so live mode parks a popover
+ // (#impeccable-live-top-layer) inside the topmost open one; an outline
+ // whose target is in that dialog mounts there, in viewport coordinates
+ // because the host is a fixed box. Live fires an event of the same name on
+ // every move of the host, and every outline is placed again. Without live
+ // mode the lookup misses.
+ function placeOverlay(overlay) {
+ const host = document.getElementById('impeccable-live-top-layer');
+ const mount = host && host.parentNode.contains(overlay._targetEl) ? host : document.body;
+ if (overlay.parentNode !== mount) mount.appendChild(overlay);
+ overlay._isFixed = mount === host || isInFixedContext(overlay._targetEl);
+ overlay.style.position = overlay._isFixed ? 'fixed' : 'absolute';
+ }
+
+ document.addEventListener('impeccable-live-top-layer', () => {
+ for (const o of overlays) {
+ if (!o._targetEl) continue;
+ placeOverlay(o);
+ positionOverlay(o);
+ }
+ });
+
function repositionOverlays() {
for (const o of overlays) {
if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
@@ -240,6 +263,7 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
if (!overlay) continue;
if (entry.isIntersecting) {
overlay.style.display = '';
+ placeOverlay(overlay);
positionOverlay(overlay);
if (!overlay._revealed) {
overlay._revealed = true;
@@ -292,19 +316,10 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
const outline = document.createElement('div');
outline.className = 'impeccable-overlay';
outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
+ Object.assign(outline.style, { zIndex: '99999', boxSizing: 'border-box' });
// Build per-finding label entries: ✦ prefix for slop
const entries = findings.map(f => {
@@ -432,7 +447,8 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
el.removeEventListener('mouseleave', onMouseLeave);
};
- document.body.appendChild(outline);
+ placeOverlay(outline);
+ positionOverlay(outline);
overlays.push(outline);
};
diff --git a/crates/live/assets/detect-antipatterns-browser.js b/crates/live/assets/detect-antipatterns-browser.js
index 303e708f2..c6a00c64b 100644
--- a/crates/live/assets/detect-antipatterns-browser.js
+++ b/crates/live/assets/detect-antipatterns-browser.js
@@ -3034,6 +3034,29 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
overlay.style.height = `${rect.height + 4}px`;
}
+ // Where an outline lives and which coordinates it takes. A modal <dialog>
+ // paints over everything outside its subtree, so live mode parks a popover
+ // (#impeccable-live-top-layer) inside the topmost open one; an outline
+ // whose target is in that dialog mounts there, in viewport coordinates
+ // because the host is a fixed box. Live fires an event of the same name on
+ // every move of the host, and every outline is placed again. Without live
+ // mode the lookup misses.
+ function placeOverlay(overlay) {
+ const host = document.getElementById('impeccable-live-top-layer');
+ const mount = host && host.parentNode.contains(overlay._targetEl) ? host : document.body;
+ if (overlay.parentNode !== mount) mount.appendChild(overlay);
+ overlay._isFixed = mount === host || isInFixedContext(overlay._targetEl);
+ overlay.style.position = overlay._isFixed ? 'fixed' : 'absolute';
+ }
+
+ document.addEventListener('impeccable-live-top-layer', () => {
+ for (const o of overlays) {
+ if (!o._targetEl) continue;
+ placeOverlay(o);
+ positionOverlay(o);
+ }
+ });
+
function repositionOverlays() {
for (const o of overlays) {
if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
@@ -3068,6 +3091,7 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
if (!overlay) continue;
if (entry.isIntersecting) {
overlay.style.display = '';
+ placeOverlay(overlay);
positionOverlay(overlay);
if (!overlay._revealed) {
overlay._revealed = true;
@@ -3120,19 +3144,10 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
const outline = document.createElement('div');
outline.className = 'impeccable-overlay';
outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
+ Object.assign(outline.style, { zIndex: '99999', boxSizing: 'border-box' });
// Build per-finding label entries: ✦ prefix for slop
const entries = findings.map(f => {
@@ -3260,7 +3275,8 @@ function createImpeccableOverlay({ extensionMode = false, antipatterns = [] } =
el.removeEventListener('mouseleave', onMouseLeave);
};
- document.body.appendChild(outline);
+ placeOverlay(outline);
+ positionOverlay(outline);
overlays.push(outline);
};
diff --git a/scripts/test-suites.mjs b/scripts/test-suites.mjs
index 7fca290d7..d6ee7c012 100644
--- a/scripts/test-suites.mjs
+++ b/scripts/test-suites.mjs
@@ -223,13 +223,14 @@ export const SUITES = {
/^ENGINE_VERSION$/,
/^tests\/framework-fixtures/,
/^tests\/live-e2e(\.test\.mjs|\/)/,
+ /^browser-bundle\/40-overlay\.js$/,
],
commands: [
{
runner: 'node',
timeoutMs: 600000,
forceExit: true,
- files: ['tests/live-e2e.test.mjs'],
+ files: ['tests/live-e2e.test.mjs', 'tests/live-top-layer.test.mjs'],
},
],
},
diff --git a/skill/scripts/live-browser-dom.js b/skill/scripts/live-browser-dom.js
index e85c95c43..c8fb8f96a 100644
--- a/skill/scripts/live-browser-dom.js
+++ b/skill/scripts/live-browser-dom.js
@@ -100,8 +100,88 @@
return doc.body;
}
+ // A modal <dialog> (showModal) paints in the top layer and makes every
+ // node outside its subtree inert, so chrome on <body> can be neither seen
+ // nor clicked while one is open, and no z-index reaches it (issue #879).
+ // While a modal is open the chrome parks inside the topmost one, in one
+ // popover: inside the dialog it is not inert, and a popover shown after
+ // the dialog paints above it. One popover for all of it, because
+ // top-layer entries stack by show order, which would drop the z-index
+ // order between the roots. The detect overlay (browser-bundle/
+ // 40-overlay.js) mounts its outlines here too: it finds the host by this
+ // id and places its outlines again on the event of the same name, fired
+ // on every move.
+ const topLayerHost = doc.createElement('div');
+ topLayerHost.id = prefix + '-top-layer';
+ // Same box as the SvelteKit shadow host: 0x0, fixed, chrome overflows it.
+ // `all: initial` also clears the popover UA box.
+ for (const [name, value] of Object.entries({
+ all: 'initial', position: 'fixed', top: '0', left: '0', width: '0', height: '0', overflow: 'visible',
+ })) topLayerHost.style.setProperty(name, value, 'important');
+ const pageRoots = new WeakSet(); // chrome nodes mounted on the page itself
+ const openModals = []; // in the order they opened; last is topmost
+
+ function syncTopLayerHost(records = []) {
+ for (const { type, target, oldValue } of records) {
+ if (type !== 'attributes' || oldValue !== null || !target.matches('dialog:modal')) continue;
+ // Opened, or closed and reopened in one task (the observer sees only
+ // the end state): either way it is back on top of the top layer, so
+ // a host shown inside it earlier has to be shown again. A write to an
+ // `open` that was already set (oldValue not null) moved nothing.
+ const i = openModals.indexOf(target);
+ if (i !== -1) openModals.splice(i, 1);
+ openModals.push(target);
+ if (topLayerHost.parentNode === target) topLayerHost.remove();
+ }
+ // A closed dialog, or one removed from the document while open, stops matching :modal.
+ for (let i = openModals.length - 1; i >= 0; i--) {
+ if (!openModals[i].matches('dialog:modal')) openModals.splice(i, 1);
+ }
+ const modal = openModals[openModals.length - 1] || null;
+ if (topLayerHost.parentNode === modal) return;
+ if (modal) {
+ modal.appendChild(topLayerHost);
+ for (const el of [...doc.body.children]) if (pageRoots.has(el)) topLayerHost.appendChild(el);
+ topLayerHost.showPopover();
+ } else {
+ doc.body.append(...topLayerHost.childNodes);
+ topLayerHost.remove();
+ }
+ doc.dispatchEvent(new Event(topLayerHost.id));
+ }
+
+ // Returns the function that stops watching and puts the chrome back.
+ function watchModalDialogs() {
+ if (typeof topLayerHost.showPopover !== 'function') return () => {};
+ topLayerHost.popover = 'manual';
+ // Parked in the page's dialog, chrome clicks would bubble into its own
+ // handlers, such as a click-outside-the-box close. Live listens in capture.
+ topLayerHost.addEventListener('click', (e) => e.stopPropagation());
+ openModals.push(...doc.querySelectorAll('dialog:modal'));
+ const observer = new MutationObserver(syncTopLayerHost);
+ observer.observe(doc, { subtree: true, childList: true, attributes: true, attributeOldValue: true, attributeFilter: ['open'] });
+ syncTopLayerHost();
+ return () => {
+ observer.disconnect();
+ openModals.length = 0;
+ syncTopLayerHost();
+ };
+ }
+
+ // Mount a chrome node on the page itself: <body>, or the top-layer host
+ // while the chrome is parked in a modal.
+ function uiAppendToPage(el) {
+ pageRoots.add(el);
+ (topLayerHost.parentNode ? topLayerHost : doc.body).appendChild(el);
+ return el;
+ }
+
function uiAppend(el) {
- liveUiRoot().appendChild(el);
+ const uiRoot = liveUiRoot();
+ if (uiRoot === doc.body) return uiAppendToPage(el);
+ // An adapter shadow root: its host is the node that sits on the page.
+ if (uiRoot.host) pageRoots.add(uiRoot.host);
+ uiRoot.appendChild(el);
return el;
}
@@ -153,6 +233,9 @@
cssId,
liveUiRoot,
uiAppend,
+ uiAppendToPage,
+ topLayerHost,
+ watchModalDialogs,
uiAppendStyle,
uiGetById,
activeElementDeep,
diff --git a/skill/scripts/live-browser.js b/skill/scripts/live-browser.js
index 2b149cbd9..99d013da2 100644
--- a/skill/scripts/live-browser.js
+++ b/skill/scripts/live-browser.js
@@ -265,6 +265,7 @@
let editBadgeEl = null;
let editBadgeProxyRoot = null;
let editBadgeProxyByTarget = new Map();
+ let stopModalWatch = null;
//
// Helpers
@@ -291,6 +292,9 @@
cssId,
liveUiRoot,
uiAppend,
+ uiAppendToPage,
+ topLayerHost,
+ watchModalDialogs,
uiAppendStyle,
uiGetById,
activeElementDeep,
@@ -967,11 +971,14 @@
}
}
- function sanitizedContextOuterHTML(el, maxLength) {
- if (!el || !el.cloneNode) return '';
+ // The element as the agent reads it, text and markup alike. The chrome
+ // parks inside an open modal <dialog> (live-browser-dom.js), so a picked
+ // dialog contains it; the clone must not.
+ function sanitizedContextClone(el) {
const clone = el.cloneNode(true);
+ if (el.contains(topLayerHost)) clone.querySelector('#' + topLayerHost.id).remove();
stripManualEditRuntimeState(clone);
- return clone.outerHTML ? clone.outerHTML.slice(0, maxLength) : '';
+ return clone;
}
function extractContext(el) {
@@ -1001,12 +1008,13 @@
: (anchorClasses.length ? el.tagName.toLowerCase() + '.' + anchorClasses.join('.') : null);
let anchorMatches = null;
if (anchor) { try { anchorMatches = document.querySelectorAll(anchor).length; } catch { anchorMatches = null; } }
+ const clone = sanitizedContextClone(el);
return {
tagName: el.tagName.toLowerCase(), id: el.id || null,
classes: [...el.classList],
anchor, anchorMatches,
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: sanitizedContextOuterHTML(el, 10000),
+ textContent: (clone.textContent || '').slice(0, 500),
+ outerHTML: (clone.outerHTML || '').slice(0, 10000),
computedStyles: {
'font-family': cs.fontFamily, 'font-size': cs.fontSize,
'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
@@ -3710,6 +3718,7 @@
function copyEditLeafContext(el, originalText, newText) {
if (!el) return null;
+ const clone = sanitizedContextClone(el);
return {
ref: documentRefForElement(el),
tagName: el.tagName ? el.tagName.toLowerCase() : null,
@@ -3717,8 +3726,8 @@
classes: el.classList ? [...el.classList].filter((cls) => cls.indexOf('impeccable-') !== 0) : [],
originalText,
newText,
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: sanitizedContextOuterHTML(el, 3000) || null,
+ textContent: (clone.textContent || '').slice(0, 500),
+ outerHTML: (clone.outerHTML || '').slice(0, 3000) || null,
};
}
@@ -3744,13 +3753,14 @@
function copyEditContainerContext(el) {
if (!el) return null;
+ const clone = sanitizedContextClone(el);
return {
ref: documentRefForElement(el),
tagName: el.tagName ? el.tagName.toLowerCase() : null,
id: el.id || null,
classes: el.classList ? [...el.classList].filter((cls) => cls.indexOf('impeccable-') !== 0) : [],
- textContent: (el.textContent || '').slice(0, 1000),
- outerHTML: sanitizedContextOuterHTML(el, 10000) || null,
+ textContent: (clone.textContent || '').slice(0, 1000),
+ outerHTML: (clone.outerHTML || '').slice(0, 10000) || null,
};
}
@@ -4540,7 +4550,7 @@
for (const [name, value] of Object.entries(styles)) {
setImportantStyle(editBadgeProxyRoot, name.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase()), value);
}
- document.body.appendChild(editBadgeProxyRoot);
+ uiAppendToPage(editBadgeProxyRoot);
}
function styleEditBadgeProxy(proxy, target) {
@@ -8032,8 +8042,8 @@
let depth = 0;
while (node && depth < 12) {
// 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
+ if (node.tagName === 'DIALOG' || (node.getAttribute && node.getAttribute('role') === 'dialog'
+ && node.getAttribute('aria-modal') === 'true')) {
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
return;
}
@@ -8645,6 +8655,7 @@
const opts = {
scale: Math.min(window.devicePixelRatio || 1, 2),
font: fontCssText ? { cssText: fontCssText } : undefined,
+ filter: (node) => node !== topLayerHost,
};
if (shouldUseAncestorCropShaderProxy(el)) {
try {
@@ -12249,6 +12260,7 @@ void main() {
pagePickSkipClick = false;
cleanup();
hideBar();
+ if (stopModalWatch) { stopModalWatch(); stopModalWatch = null; }
if (pendingDockResizeObserver) { pendingDockResizeObserver.disconnect(); pendingDockResizeObserver = null; }
window.removeEventListener('resize', positionPendingDock);
if (pendingIntroAnimation) { pendingIntroAnimation.cancel(); pendingIntroAnimation = null; }
@@ -13466,6 +13478,7 @@ void main() {
attachSteerFocusDebug();
attachSteerFocusGuard();
initDesignPanel();
+ stopModalWatch = watchModalDialogs();
fetchPendingCount();
document.addEventListener('mousemove', handleMouseMove, true);
document.addEventListener('click', handleClick, true);
diff --git a/tests/live-browser-source.test.mjs b/tests/live-browser-source.test.mjs
index ec3035cf0..9af6d5c97 100644
--- a/tests/live-browser-source.test.mjs
+++ b/tests/live-browser-source.test.mjs
@@ -311,17 +311,17 @@ describe('live-browser source contracts', () => {
);
assert.match(
SOURCE,
- /function sanitizedContextOuterHTML\(el, maxLength\)[\s\S]*?stripManualEditRuntimeState\(clone\);/,
+ /function sanitizedContextClone\(el\)[\s\S]*?stripManualEditRuntimeState\(clone\);/,
'manual copy edit prompt context should strip browser-only edit markers before staging HTML',
);
assert.match(
SOURCE,
- /outerHTML: sanitizedContextOuterHTML\(el, 10000\),/,
+ /function extractContext\(el\)[\s\S]*?const clone = sanitizedContextClone\(el\);[\s\S]*?outerHTML: \(clone\.outerHTML \|\| ''\)\.slice\(0, 10000\),/,
'staged element context should not include live edit runtime attributes',
);
assert.match(
SOURCE,
- /function copyEditLeafContext\(el, originalText, newText\)[\s\S]*?outerHTML: sanitizedContextOuterHTML\(el, 3000\) \|\| null,/,
+ /function copyEditLeafContext\(el, originalText, newText\)[\s\S]*?const clone = sanitizedContextClone\(el\);[\s\S]*?outerHTML: \(clone\.outerHTML \|\| ''\)\.slice\(0, 3000\) \|\| null,/,
'staged leaf context should not include live edit runtime attributes',
);
assert.match(
diff --git a/tests/live-top-layer.test.mjs b/tests/live-top-layer.test.mjs
new file mode 100644
index 000000000..af1f3d63c
--- /dev/null
+++ b/tests/live-top-layer.test.mjs
@@ -0,0 +1,198 @@
+/**
+ * Live chrome stays usable while a native modal <dialog> is open (issue #879).
+ *
+ * showModal() puts the dialog in the top layer and makes everything outside
+ * its subtree inert, so chrome on <body> neither shows nor takes clicks. Real
+ * pointer input only: a synthetic el.click() bypasses inertness and would pass
+ * on the broken code.
+ *
+ * Needs Playwright Chromium (npx playwright install chromium); no engine
+ * binary or dev server. Run with: node --test tests/live-top-layer.test.mjs
+ */
+
+import { describe, it, before, after, beforeEach, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const HOST = '#impeccable-live-top-layer';
+
+const PAGE = `
+ <button id="open" onclick="d.showModal()">Open</button>
+ <p id="outside">Outside</p>
+ <dialog id="d" style="transform: translateX(0); overflow: hidden">
+ <p id="inside">Inside</p>
+ <button id="close" onclick="d.close()">Close</button>
+ <dialog id="d2"><p>Nested</p></dialog>
+ </dialog>
+ <div style="height: 2000px"></div>`;
+
+let browser;
+let page;
+
+before(async () => {
+ let playwright;
+ try {
+ playwright = await import('playwright');
+ browser = await playwright.chromium.launch({ headless: true });
+ } catch (err) {
+ throw new Error(`Playwright Chromium is required (${err.message}). Run: npx playwright install chromium`);
+ }
+});
+
+after(async () => {
+ if (browser) await browser.close();
+});
+
+beforeEach(async () => {
+ page = await browser.newPage({ viewport: { width: 800, height: 600 } });
+ await page.setContent(PAGE);
+ await page.addScriptTag({ path: join(ROOT, 'skill/scripts/live-browser-dom.js') });
+ await page.evaluate(() => {
+ const h = window.__IMPECCABLE_LIVE_DOM__.createLiveBrowserDomHelpers({ prefix: 'impeccable-live', document });
+ const bar = document.createElement('div');
+ bar.id = 'impeccable-live-bar';
+ bar.style.cssText = 'position: fixed; left: 20px; bottom: 20px; width: 160px; height: 40px; z-index: 100005';
+ bar.onclick = () => { window.clicks = (window.clicks || 0) + 1; };
+ h.uiAppend(bar);
+ window.live = h;
+ h.watchModalDialogs();
+ });
+});
+
+afterEach(async () => {
+ await page.close();
+});
+
+async function click(selector) {
+ const box = await page.locator(selector).boundingBox();
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+}
+
+const clicks = () => page.evaluate(() => window.clicks || 0);
+const parentOf = (selector) => page.evaluate((s) => document.querySelector(s).parentElement?.id || null, selector);
+
+describe('live chrome under a modal dialog', () => {
+ it('stays clickable while a modal is open and returns to body on close', async () => {
+ await click('#impeccable-live-bar');
+ assert.equal(await clicks(), 1);
+
+ await click('#open');
+ await click('#impeccable-live-bar');
+ assert.equal(await clicks(), 2);
+ assert.equal(await page.evaluate(() => {
+ const r = document.getElementById('impeccable-live-bar').getBoundingClientRect();
+ return document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2).id;
+ }), 'impeccable-live-bar');
+ assert.equal(await parentOf('#impeccable-live-bar'), 'impeccable-live-top-layer');
+ assert.equal(await parentOf(HOST), 'd');
+
+ // Chrome mounted while the modal is open lands in the same host.
+ await page.evaluate(() => {
+ const el = document.createElement('div');
+ el.id = 'impeccable-live-late';
+ window.live.uiAppend(el);
+ });
+ assert.equal(await parentOf('#impeccable-live-late'), 'impeccable-live-top-layer');
+
+ await click('#close');
+ assert.equal(await page.evaluate(() => document.querySelector('#impeccable-live-top-layer')), null);
+ assert.equal(await page.evaluate(() => document.getElementById('impeccable-live-bar').parentNode === document.body), true);
+ assert.equal(await page.evaluate(() => document.getElementById('impeccable-live-late').parentNode === document.body), true);
+ await click('#impeccable-live-bar');
+ assert.equal(await clicks(), 3);
+ });
+
+ it('follows the topmost of nested modals', async () => {
+ await page.evaluate(() => d.showModal());
+ await page.evaluate(() => d2.showModal());
+ assert.equal(await parentOf(HOST), 'd2');
+ await click('#impeccable-live-bar');
+ assert.equal(await clicks(), 1);
+
+ // Rewriting `open` on the lower modal does not raise it.
+ await page.evaluate(() => d.setAttribute('open', ''));
+ assert.equal(await parentOf(HOST), 'd2');
+ await click('#impeccable-live-bar');
+ assert.equal(await clicks(), 2);
+
+ await page.evaluate(() => d2.close());
+ assert.equal(await parentOf(HOST), 'd');
+ });
+
+ it('stays above a modal closed and reopened in one task', async () => {
+ await page.evaluate(() => d.showModal());
+ await page.evaluate(() => { d.close(); d.showModal(); });
+ await click('#impeccable-live-bar');
+ assert.equal(await clicks(), 1);
+ });
+
+ it('keeps chrome clicks out of the dialog handlers', async () => {
+ // A common light-dismiss: close when a click lands outside the dialog box.
+ await page.evaluate(() => d.addEventListener('click', (e) => {
+ const r = d.getBoundingClientRect();
+ if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) d.close();
+ }));
+ await page.evaluate(() => d.showModal());
+ await click('#impeccable-live-bar');
+ assert.equal(await clicks(), 1);
+ assert.equal(await page.evaluate(() => d.open), true);
+ });
+
+ it('puts the chrome back when an open modal is removed from the document', async () => {
+ await page.evaluate(() => d.showModal());
+ assert.equal(await parentOf(HOST), 'd');
+
+ await page.evaluate(() => d.remove());
+ assert.equal(await page.evaluate(() => document.getElementById('impeccable-live-bar').parentNode === document.body), true);
+ assert.equal(await page.evaluate(() => document.querySelector('#impeccable-live-top-layer')), null);
+ });
+
+ it('mounts detect outlines for targets inside the modal in the host', async () => {
+ await page.addScriptTag({ path: join(ROOT, 'browser-bundle/40-overlay.js') });
+ await page.evaluate(() => {
+ window.overlay = createImpeccableOverlay({ extensionMode: true, antipatterns: [{ id: 'x', name: 'X', category: 'slop' }] });
+ for (const id of ['inside', 'outside']) {
+ window.overlay.highlight(document.getElementById(id), [{ type: 'x', detail: id }]);
+ }
+ });
+ const outlineParent = (id) => page.evaluate((target) => {
+ const o = window.overlay.overlays.find((el) => el._targetEl.id === target);
+ return o.parentNode === document.body ? 'body' : o.parentNode.id;
+ }, id);
+ assert.equal(await outlineParent('inside'), 'body');
+
+ // The outline made while the dialog was closed moves in once it opens,
+ // and still lines up with its target on a scrolled page.
+ await page.evaluate(() => { scrollTo(0, 300); d.showModal(); });
+ await page.waitForFunction(
+ () => window.overlay.overlays.some((o) => o.parentNode.id === 'impeccable-live-top-layer' && o.style.display !== 'none'),
+ null,
+ { timeout: 5000 },
+ );
+ assert.equal(await outlineParent('inside'), 'impeccable-live-top-layer');
+ assert.equal(await outlineParent('outside'), 'body');
+ const [outline, target] = await page.evaluate(() => {
+ const o = window.overlay.overlays.find((el) => el._targetEl.id === 'inside').getBoundingClientRect();
+ const t = document.getElementById('inside').getBoundingClientRect();
+ return [[o.top + 2, o.left + 2], [t.top, t.left]];
+ });
+ assert.deepEqual(outline.map(Math.round), target.map(Math.round));
+
+ // One made while it is open mounts there directly.
+ const direct = await page.evaluate(() => {
+ window.overlay.highlight(document.getElementById('inside'), [{ type: 'x', detail: 'again' }]);
+ return window.overlay.overlays.at(-1).parentNode.id;
+ });
+ assert.equal(direct, 'impeccable-live-top-layer');
+
+ // A modal opened above takes the host, but an outline for the dialog
+ // underneath stays under that modal, and returns when it closes.
+ await page.evaluate(() => d2.showModal());
+ assert.equal(await parentOf(HOST), 'd2');
+ assert.equal(await outlineParent('inside'), 'body');
+ await page.evaluate(() => d2.close());
+ assert.equal(await outlineParent('inside'), 'impeccable-live-top-layer');
+ });
+});