Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(lab): harden Drawer layer lifecycle (#6073)

Xinzi Zhou189056a433c1
diff --git a/.github/scripts/modal-close-visibility.js b/.github/scripts/modal-close-visibility.js
index 41718b8c59..2b24bd2fe9 100644
--- a/.github/scripts/modal-close-visibility.js
+++ b/.github/scripts/modal-close-visibility.js
@@ -1,40 +1,57 @@
#!/usr/bin/env node
// Copyright (c) Meta Platforms, Inc. and affiliates.
-
/**
- * @description Asserts native-dialog close/render ordering in a real browser
- * @input --storybook-dir <path> [--port <n>]
- * @output One line per target; exit 1 if a close/render invariant fails
+ * @description Asserts native-dialog host exit/render/dismissal ordering in a real browser (MobileNav, Drawer)
+ * @input --storybook-dir <path> [--port <n>] [--browser chromium|webkit]
+ * @output One line per target; exit 1 if a native-host invariant fails
*
- * Two opposite ordering bugs live at this boundary:
+ * Five ordering contracts live at this boundary:
*
* 1. A modal <dialog> that is `display: none` while still `:modal` blocks every
* pointer event on the document, and Safari 26.1 did not release that block
* when close() finally ran (#4290). It must still be rendered when close()
* starts.
- * 2. A fixed panel that stays rendered after close() leaves the top layer can
- * paint back inside a transformed ancestor for one frame (#5549). It must be
- * hidden before the next paint after close().
+ * 2. A fixed panel that stays rendered after its native host leaves the top
+ * layer can paint back inside a transformed ancestor for one frame (#5549).
+ * It must be hidden before the next paint.
+ * 3. The non-modal Popover host must preserve `<dialog>`'s observable `close`
+ * event so ref/onClose consumers keep their focus-restoration contract, and
+ * must dispatch it after the drawer's own focus restore: native close events
+ * are task-queued, so a consumer close listener that retargets focus
+ * (master-detail row switching) always had the last word.
+ * 4. A closing top drawer stays on the shared dismissal stack until its visual
+ * exit completes, so a second Escape cannot dismiss the drawer below it.
+ * 5. After a completed exit, focus rests on the element focused at open — or on
+ * the element a consumer close listener chose instead (contract 3).
*
- * Neither ordering exists in jsdom: it runs no CSS transition and has no top
- * layer. Chromium is enough to observe both invariants; the browser-specific
- * failure that first exposed each one is not needed to see the ordering fail.
+ * None of these orderings exists in jsdom: it runs no CSS transition and has no
+ * top layer. Runs in Chromium by default; `--browser webkit` runs the same
+ * probes in Playwright WebKit because `docs/architecture/layer-runtime.md`
+ * requires Chromium and WebKit evidence for native Popover/dialog/focus
+ * changes. (Playwright WebKit is the WebKit engine, not Safari itself — see
+ * spec:AST-027 for that distinction.)
*/
-const { chromium } = require('playwright');
+const playwright = require('playwright');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const args = process.argv.slice(2);
-const getArg = (name) => {
+const getArg = name => {
const idx = args.indexOf(`--${name}`);
return idx !== -1 ? args[idx + 1] : null;
};
const storybookDir = getArg('storybook-dir') || 'apps/storybook/dist';
const port = Number(getArg('port') || 6009);
+const browserName = getArg('browser') || 'chromium';
+
+if (browserName !== 'chromium' && browserName !== 'webkit') {
+ console.error(`Unsupported --browser "${browserName}" (chromium|webkit)`);
+ process.exit(1);
+}
const TARGETS = [
{
@@ -43,13 +60,40 @@ const TARGETS = [
openButton: 'Open Navigation',
},
{
- component: 'Drawer',
+ component: 'Drawer (modal)',
story: 'lab-drawer--showcase',
openButton: 'Open inspector',
- // Reproduces the real failure condition: after close() releases the top
- // layer, this becomes the containing block for the fixed panel.
+ // Reproduces the real failure condition: after the native host releases the
+ // top layer, this becomes the containing block for the fixed panel.
+ transformAncestor: true,
+ mustBeHiddenAfterClose: true,
+ finalFocus: 'Open inspector',
+ },
+ {
+ component: 'Drawer (non-modal)',
+ story: 'lab-drawer--row-inspector',
+ openButton: 'web-01 / us-east-1',
+ host: 'popover',
transformAncestor: true,
mustBeHiddenAfterClose: true,
+ mustDispatchClose: true,
+ // Exercises contract 3's ordering: the drawer restores web-01 (its
+ // trigger), then this listener must win with the latest selected row.
+ closeListenerFocus: 'web-02 / us-east-1',
+ finalFocus: 'web-02 / us-east-1',
+ },
+ {
+ component: 'Drawer (stacked exit)',
+ story: 'lab-drawer--stacked-drawers',
+ openButton: 'Open order',
+ nestedButton: 'Open line item',
+ outerLabel: 'Order details',
+ innerLabel: 'Line item details',
+ host: 'popover',
+ stackedExit: true,
+ mustBeHiddenAfterClose: true,
+ mustDispatchClose: true,
+ finalFocus: 'Open order',
},
];
@@ -63,7 +107,7 @@ const CONTENT_TYPES = {
};
function createServer(dir, listenPort) {
- return new Promise((resolve) => {
+ return new Promise(resolve => {
const server = http.createServer((req, res) => {
const filePath = path
.join(dir, req.url === '/' ? 'index.html' : req.url)
@@ -83,8 +127,7 @@ function createServer(dir, listenPort) {
return;
}
res.writeHead(200, {
- 'Content-Type':
- CONTENT_TYPES[path.extname(resolved)] || 'text/plain',
+ 'Content-Type': CONTENT_TYPES[path.extname(resolved)] || 'text/plain',
});
res.end(data);
});
@@ -94,36 +137,65 @@ function createServer(dir, listenPort) {
});
}
-// Records the computed `display` of every dialog at the instant it is closed.
-function recordCloseDisplay() {
+// Records the rendered state at the instant either native host is released.
+function recordHostExitDisplay() {
window.__closeDisplays = [];
window.__postCloseFrames = [];
- const close = HTMLDialogElement.prototype.close;
- HTMLDialogElement.prototype.close = function (...args) {
- const dialog = this;
- window.__closeDisplays.push(getComputedStyle(dialog).display);
- const result = close.apply(dialog, args);
- // Sample immediately before the next paint. Drawer must have committed its
- // hide by this point; otherwise the non-top-layer panel can paint against a
- // transformed ancestor for one frame.
+ window.__dialogCloseEvents = 0;
+
+ const sampleAfterExit = dialog => {
requestAnimationFrame(() => {
const rect = dialog.getBoundingClientRect();
window.__postCloseFrames.push({
display: getComputedStyle(dialog).display,
open: dialog.open,
+ popoverOpen: dialog.matches(':popover-open'),
x: Math.round(rect.x),
width: Math.round(rect.width),
});
});
+ };
+ const recordExit = (dialog, exit, args) => {
+ window.__closeDisplays.push(getComputedStyle(dialog).display);
+ const result = exit.apply(dialog, args);
+ // Sample immediately before the next paint. A `mustBeHiddenAfterClose`
+ // target must have committed its hide by this point; otherwise the
+ // non-top-layer panel can paint against a transformed ancestor for one frame.
+ sampleAfterExit(dialog);
return result;
};
+
+ const close = HTMLDialogElement.prototype.close;
+ HTMLDialogElement.prototype.close = function (...args) {
+ return recordExit(this, close, args);
+ };
+
+ const hidePopover = HTMLElement.prototype.hidePopover;
+ if (typeof hidePopover === 'function') {
+ HTMLElement.prototype.hidePopover = function (...args) {
+ if (this instanceof HTMLDialogElement) {
+ return recordExit(this, hidePopover, args);
+ }
+ return hidePopover.apply(this, args);
+ };
+ }
+
+ document.addEventListener(
+ 'close',
+ event => {
+ if (event.target instanceof HTMLDialogElement) {
+ window.__dialogCloseEvents += 1;
+ }
+ },
+ true,
+ );
}
async function probe(page, target) {
- await page.addInitScript(recordCloseDisplay);
+ await page.addInitScript(recordHostExitDisplay);
await page.goto(
`http://localhost:${port}/iframe.html?id=${target.story}&viewMode=story`,
- { waitUntil: 'networkidle', timeout: 15000 }
+ {waitUntil: 'networkidle', timeout: 15000},
);
if (target.transformAncestor) {
@@ -136,27 +208,154 @@ async function probe(page, target) {
});
}
- await page.getByRole('button', { name: target.openButton }).click();
+ const hostSelector =
+ target.host === 'popover' ? 'dialog:popover-open' : 'dialog:modal';
+ const openHostCount = target.stackedExit ? 2 : 1;
+ await page.getByRole('button', {name: target.openButton}).click();
+ if (target.nestedButton) {
+ await page.getByRole('button', {name: target.nestedButton}).click();
+ }
await page.waitForFunction(
- () => document.querySelector('dialog')?.matches(':modal') === true,
- null,
- { timeout: 5000 }
+ ({selector, count}) => document.querySelectorAll(selector).length === count,
+ {selector: hostSelector, count: openHostCount},
+ {timeout: 5000},
);
- await page.keyboard.press('Escape');
- await page.waitForFunction(() => window.__closeDisplays.length > 0, null, {
- timeout: 5000,
- });
+ // Let every open host finish its @starting-style entry before we drive the
+ // close. If Escape lands while a drawer is still sliding in, the exit cancels
+ // the entry transition and the presence hook treats that `transitioncancel`
+ // as exit completion — so the host leaves the top layer at once, with no
+ // slide-out. On a slow CI runner the whole exit is gone before the probe can
+ // observe the close event, the focus handoff, or the stacked-ownership
+ // window, and the wait below times out (a flake that never reproduces on a
+ // fast dev machine). Waiting for the resting transform makes the following
+ // exit a clean, observable transition. No-op for hosts that do not transform
+ // the dialog element itself (MobileNav animates a child; its transform stays
+ // `none`).
+ await page.waitForFunction(
+ selector => {
+ const dialogs = [...document.querySelectorAll(selector)];
+ return (
+ dialogs.length > 0 &&
+ dialogs.every(dialog => {
+ const transform = getComputedStyle(dialog).transform;
+ return (
+ transform === 'none' || transform === 'matrix(1, 0, 0, 1, 0, 0)'
+ );
+ })
+ );
+ },
+ hostSelector,
+ {timeout: 5000},
+ );
+
+ if (target.closeListenerFocus) {
+ await page.evaluate(
+ ({selector, focusLabel}) => {
+ const dialog = document.querySelector(selector);
+ const retarget = [...document.querySelectorAll('button')].find(
+ button => (button.textContent || '').trim() === focusLabel,
+ );
+ if (!(dialog instanceof HTMLElement) || !retarget) {
+ throw new Error('close-listener focus fixture not found');
+ }
+ dialog.addEventListener('close', () => retarget.focus(), {once: true});
+ },
+ {selector: hostSelector, focusLabel: target.closeListenerFocus},
+ );
+ }
+
+ let stackedExitOwned = true;
+ if (target.stackedExit) {
+ const outer = page.getByRole('dialog', {name: target.outerLabel});
+ const inner = page.getByRole('dialog', {name: target.innerLabel});
+ const innerOpenClass = await inner.getAttribute('class');
+
+ await page.keyboard.press('Escape');
+ // Wait until React has committed the inner drawer's exit state while its
+ // native host is still open. The second Escape then exercises the actual
+ // slide-out window rather than racing the first state update.
+ await page.waitForFunction(
+ ({label, openClass}) => {
+ const dialog = [...document.querySelectorAll('dialog')].find(
+ candidate => candidate.getAttribute('aria-label') === label,
+ );
+ return (
+ dialog?.matches(':popover-open') === true &&
+ dialog.className !== openClass
+ );
+ },
+ {label: target.innerLabel, openClass: innerOpenClass},
+ {timeout: 5000},
+ );
+
+ const outerOpenClass = await outer.getAttribute('class');
+ await page.keyboard.press('Escape');
+ await page.evaluate(
+ () => new Promise(resolve => requestAnimationFrame(() => resolve(true))),
+ );
+ // A lower drawer that incorrectly handled the second Escape loses its open
+ // transform class immediately, independent of how long a busy runner delays
+ // the transition timer. This avoids a wall-clock-based flaky assertion.
+ stackedExitOwned = (await outer.getAttribute('class')) === outerOpenClass;
+
+ await page.waitForFunction(
+ ({label, selector}) => {
+ const dialog = [...document.querySelectorAll('dialog')].find(
+ candidate => candidate.getAttribute('aria-label') === label,
+ );
+ return dialog != null && !dialog.matches(selector);
+ },
+ {label: target.innerLabel, selector: hostSelector},
+ {timeout: 5000},
+ );
+ if (stackedExitOwned) {
+ await page.keyboard.press('Escape');
+ }
+ } else {
+ await page.keyboard.press('Escape');
+ }
+
+ const expectedExits = target.stackedExit ? 2 : 1;
+ await page.waitForFunction(
+ count => window.__closeDisplays.length >= count,
+ expectedExits,
+ {timeout: 5000},
+ );
+ await page.waitForFunction(
+ selector => document.querySelectorAll(selector).length === 0,
+ hostSelector,
+ {timeout: 5000},
+ );
if (target.mustBeHiddenAfterClose) {
- await page.waitForFunction(() => window.__postCloseFrames.length > 0, null, {
- timeout: 5000,
- });
+ await page.waitForFunction(
+ count => window.__postCloseFrames.length >= count,
+ expectedExits,
+ {timeout: 5000},
+ );
}
- return page.evaluate(() => ({
- closeDisplays: window.__closeDisplays,
- postCloseFrames: window.__postCloseFrames,
- }));
+ return page.evaluate(
+ ({expectedExits, stackedExitOwned}) => {
+ const active = document.activeElement;
+ return {
+ closeDisplays: window.__closeDisplays,
+ postCloseFrames: window.__postCloseFrames,
+ closeEvents: window.__dialogCloseEvents,
+ expectedExits,
+ stackedExitOwned,
+ finalFocus:
+ active instanceof HTMLElement
+ ? (
+ active.getAttribute('aria-label') ||
+ active.textContent ||
+ active.tagName
+ ).trim()
+ : 'none',
+ };
+ },
+ {expectedExits, stackedExitOwned},
+ );
}
async function run() {
@@ -167,44 +366,76 @@ async function run() {
}
const server = await createServer(dir, port);
- const browser = await chromium.launch();
+ const browser = await playwright[browserName].launch();
let failures = 0;
try {
const context = await browser.newContext({
- viewport: { width: 430, height: 860 },
+ viewport: {width: 430, height: 860},
});
for (const target of TARGETS) {
const page = await context.newPage();
+ const name = `${target.component} [${browserName}]`;
try {
- const { closeDisplays, postCloseFrames } = await probe(page, target);
- const hiddenAtClose = closeDisplays.filter((d) => d === 'none');
- const paintedAfterClose = target.mustBeHiddenAfterClose
- ? postCloseFrames.filter((frame) => frame.display !== 'none')
+ const {
+ closeDisplays,
+ postCloseFrames,
+ closeEvents,
+ expectedExits,
+ stackedExitOwned,
+ finalFocus,
+ } = await probe(page, target);
+ const hiddenAtExit = closeDisplays.filter(d => d === 'none');
+ const paintedAfterExit = target.mustBeHiddenAfterClose
+ ? postCloseFrames.filter(frame => frame.display !== 'none')
: [];
+ const missingCloseEvent =
+ target.mustDispatchClose && closeEvents < expectedExits;
+ const wrongFinalFocus =
+ target.finalFocus != null && finalFocus !== target.finalFocus;
- if (hiddenAtClose.length > 0) {
+ if (!stackedExitOwned) {
failures++;
console.error(
- `✗ ${target.component}: close() ran at display: none (${closeDisplays.join(', ')})`
+ `✗ ${name}: a second Escape reached the lower drawer during the top drawer's exit`,
);
- } else if (paintedAfterClose.length > 0) {
+ } else if (hiddenAtExit.length > 0) {
failures++;
console.error(
- `✗ ${target.component}: painted after close() outside the top layer — ${JSON.stringify(paintedAfterClose)}`
+ `✗ ${name}: native host exited at display: none (${closeDisplays.join(', ')})`,
+ );
+ } else if (paintedAfterExit.length > 0) {
+ failures++;
+ console.error(
+ `✗ ${name}: painted after native host exit — ${JSON.stringify(paintedAfterExit)}`,
+ );
+ } else if (missingCloseEvent) {
+ failures++;
+ console.error(
+ `✗ ${name}: emitted ${closeEvents}/${expectedExits} dialog close event(s)`,
+ );
+ } else if (wrongFinalFocus) {
+ failures++;
+ console.error(
+ `✗ ${name}: focus rests on "${finalFocus}" after exit, expected "${target.finalFocus}"`,
);
} else {
const postClose = target.mustBeHiddenAfterClose
? '; hidden before the next paint'
: '';
+ const closeEvent = target.mustDispatchClose
+ ? `; ${closeEvents} close event(s)`
+ : '';
+ const focus =
+ target.finalFocus != null ? `; focus on "${finalFocus}"` : '';
console.log(
- `✓ ${target.component}: close() ran at display: ${closeDisplays.join(', ')}${postClose}`
+ `✓ ${name}: native host exited at display: ${closeDisplays.join(', ')}${postClose}${closeEvent}${focus}`,
);
}
} catch (e) {
failures++;
- console.error(`✗ ${target.component}: probe failed — ${e.message}`);
+ console.error(`✗ ${name}: probe failed — ${e.message}`);
} finally {
await page.close();
}
@@ -216,19 +447,21 @@ async function run() {
if (failures > 0) {
console.error(
- `\nFailing: ${failures} native-dialog close/render ordering check(s) — see #4290 and #5549.`
+ `\nFailing: ${failures} native-dialog host ordering check(s) in ${browserName} — see #4290 and #5549.`,
);
return 1;
}
- console.log('\nAll native-dialog close/render ordering checks passed.');
+ console.log(
+ `\nAll native-dialog host ordering checks passed in ${browserName}.`,
+ );
return 0;
}
run()
- .then((code) => {
+ .then(code => {
process.exitCode = code;
})
- .catch((e) => {
- console.error('Native-dialog close visibility guard failed:', e);
+ .catch(e => {
+ console.error('Native-dialog host guard failed:', e);
process.exit(1);
});
diff --git a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx
index 39376db429..26ac2bb80c 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx
@@ -658,7 +658,7 @@ export default function ComponentScoresPage() {
// Switching rows keeps the non-modal drawer open. Reset its reading
// position and move focus to the new heading so the changed audit is
- // announced and Escape continues to reach the drawer's key handler.
+ // announced and Escape continues to reach the shared dismissal owner.
useEffect(() => {
if (!isAuditPanelOpen || !selectedRowId) {
return;
diff --git a/apps/sandbox/src/app/(sandbox)/pages/motion-lab/__generated__/motionAudit.ts b/apps/sandbox/src/app/(sandbox)/pages/motion-lab/__generated__/motionAudit.ts
index afd0b970f5..db4a34a82b 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/motion-lab/__generated__/motionAudit.ts
+++ b/apps/sandbox/src/app/(sandbox)/pages/motion-lab/__generated__/motionAudit.ts
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// @generated by scripts/generate-motion-audit.mjs — do not edit by hand.
-// Measured against packages/core + packages/lab at [email protected].
+// Measured against packages/core + packages/lab at [email protected].
// Regenerate: pnpm -F @astryxdesign/sandbox generate:motion-audit
//
// The Motion Lab shows these numbers instead of the ones written in the project
@@ -27,19 +27,19 @@ export type SiteRef = {
readonly decl?: string;
};
-export const CORE_VERSION = '0.5.0';
+export const CORE_VERSION = '0.5.2';
export const AUDIT_COUNTS = {
componentDirs: 121,
coreComponentDirs: 104,
labComponentDirs: 17,
hardcodedInLab: 10,
- filesScanned: 701,
- animatingComponents: 55,
- staticComponents: 65,
- animatedFiles: 88,
+ filesScanned: 721,
+ animatingComponents: 56,
+ staticComponents: 64,
+ animatedFiles: 89,
filesWithReducedMotion: 48,
- filesWithoutReducedMotion: 40,
+ filesWithoutReducedMotion: 41,
hardcodedTotal: 58,
hardcodedDuration: 34,
hardcodedEasing: 24,
@@ -50,7 +50,7 @@ export const AUDIT_COUNTS = {
transitionAll: 0,
infiniteLoops: 9,
setTimeoutLiterals: 1,
- getComputedStyleReads: 34,
+ getComputedStyleReads: 35,
} as const;
export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
@@ -98,7 +98,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/BottomSheet/BottomSheet.tsx',
package: 'core',
component: 'BottomSheet',
- line: 94,
+ line: 95,
kind: 'duration',
prop: 'transitionDuration',
value: '0.01s',
@@ -108,7 +108,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/BottomSheet/BottomSheet.tsx',
package: 'core',
component: 'BottomSheet',
- line: 109,
+ line: 110,
kind: 'easing',
prop: 'transitionTimingFunction',
value: 'linear',
@@ -158,7 +158,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/Button/Button.tsx',
package: 'core',
component: 'Button',
- line: 380,
+ line: 383,
kind: 'duration',
prop: 'animationDuration',
value: '1ms',
@@ -258,7 +258,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'lab/CircularProgress/CircularProgress.tsx',
package: 'lab',
component: 'CircularProgress',
- line: 188,
+ line: 190,
kind: 'easing',
prop: 'animationTimingFunction',
value: 'linear',
@@ -268,7 +268,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'lab/CircularProgress/CircularProgress.tsx',
package: 'lab',
component: 'CircularProgress',
- line: 210,
+ line: 212,
kind: 'easing',
prop: 'animationTimingFunction',
value: 'ease-in-out',
@@ -398,7 +398,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/DateInput/Wheel.tsx',
package: 'core',
component: 'DateInput',
- line: 171,
+ line: 172,
kind: 'easing',
prop: 'animationTimingFunction',
value: 'linear',
@@ -408,7 +408,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'lab/Drawer/Drawer.tsx',
package: 'lab',
component: 'Drawer',
- line: 161,
+ line: 121,
kind: 'duration',
prop: 'transitionDuration',
value: '0.01s',
@@ -418,7 +418,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'lab/Drawer/Drawer.tsx',
package: 'lab',
component: 'Drawer',
- line: 234,
+ line: 194,
kind: 'duration',
prop: 'transitionDuration',
value: '0.01s',
@@ -478,7 +478,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/Spinner/Spinner.tsx',
package: 'core',
component: 'Spinner',
- line: 265,
+ line: 294,
kind: 'easing',
prop: 'animationTimingFunction',
value: 'linear',
@@ -508,7 +508,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/Stepper/Step.tsx',
package: 'core',
component: 'Stepper',
- line: 388,
+ line: 433,
kind: 'easing',
prop: 'transitionTimingFunction',
value: 'linear',
@@ -518,7 +518,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/Table/plugins/columnResize/useTableColumnResize.tsx',
package: 'core',
component: 'Table',
- line: 248,
+ line: 245,
kind: 'duration',
prop: 'transition',
value: '150ms',
@@ -528,7 +528,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/Table/plugins/columnResize/useTableColumnResize.tsx',
package: 'core',
component: 'Table',
- line: 248,
+ line: 245,
kind: 'duration',
prop: 'transition',
value: '150ms',
@@ -538,7 +538,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/Table/plugins/columnResize/useTableColumnResize.tsx',
package: 'core',
component: 'Table',
- line: 248,
+ line: 245,
kind: 'easing',
prop: 'transition',
value: 'ease',
@@ -548,7 +548,7 @@ export const HARDCODED_SITES: ReadonlyArray<HardcodedSite> = [
file: 'core/Table/plugins/columnResize/useTableColumnResize.tsx',
package: 'core',
component: 'Table',
- line: 248,
+ line: 245,
kind: 'easing',
prop: 'transition',
value: 'ease',
@@ -665,7 +665,7 @@ export const DURATION_WITHOUT_CURVE: ReadonlyArray<SiteRef> = [
file: 'core/DateInput/MonthScroller.tsx',
package: 'core',
component: 'DateInput',
- line: 165,
+ line: 166,
decl: "transitionDuration: durationVars['--duration-fast']",
},
{
@@ -679,7 +679,7 @@ export const DURATION_WITHOUT_CURVE: ReadonlyArray<SiteRef> = [
file: 'core/DateInput/Wheel.tsx',
package: 'core',
component: 'DateInput',
- line: 110,
+ line: 111,
decl: "transitionDuration: durationVars['--duration-fast']",
},
{
@@ -700,7 +700,7 @@ export const DURATION_WITHOUT_CURVE: ReadonlyArray<SiteRef> = [
file: 'core/Stepper/Step.tsx',
package: 'core',
component: 'Stepper',
- line: 405,
+ line: 450,
decl: 'transitionDuration:',
},
{
@@ -728,7 +728,7 @@ export const DURATION_WITHOUT_CURVE: ReadonlyArray<SiteRef> = [
file: 'lab/Drawer/Drawer.tsx',
package: 'lab',
component: 'Drawer',
- line: 232,
+ line: 192,
decl: "transitionDuration: '0.01s'",
},
];
@@ -738,7 +738,7 @@ export const TRANSFORM_TRANSITIONS: ReadonlyArray<SiteRef> = [
file: 'core/Banner/Banner.tsx',
package: 'core',
component: 'Banner',
- line: 340,
+ line: 345,
decl: "transitionProperty: 'transform'",
},
{
@@ -780,7 +780,7 @@ export const TRANSFORM_TRANSITIONS: ReadonlyArray<SiteRef> = [
file: 'core/Collapsible/Collapsible.tsx',
package: 'core',
component: 'Collapsible',
- line: 107,
+ line: 117,
decl: "transitionProperty: 'transform'",
},
{
@@ -822,14 +822,14 @@ export const TRANSFORM_TRANSITIONS: ReadonlyArray<SiteRef> = [
file: 'core/MultiSelector/MultiSelector.tsx',
package: 'core',
component: 'MultiSelector',
- line: 187,
+ line: 189,
decl: "transitionProperty: 'transform'",
},
{
file: 'core/MultiSelector/MultiSelector.tsx',
package: 'core',
component: 'MultiSelector',
- line: 208,
+ line: 210,
decl: "transitionProperty: 'background-image, background-color, color, opacity, transform'",
},
{
@@ -843,21 +843,21 @@ export const TRANSFORM_TRANSITIONS: ReadonlyArray<SiteRef> = [
file: 'core/Resizable/ResizeHandle.tsx',
package: 'core',
component: 'Resizable',
- line: 194,
+ line: 219,
decl: "transitionProperty: 'opacity, background-color, transform'",
},
{
file: 'core/Selector/Selector.tsx',
package: 'core',
component: 'Selector',
- line: 209,
+ line: 212,
decl: "transitionProperty: 'transform'",
},
{
file: 'core/Selector/Selector.tsx',
package: 'core',
component: 'Selector',
- line: 230,
+ line: 233,
decl: "transitionProperty: 'background-image, background-color, color, opacity, transform'",
},
{
@@ -878,14 +878,14 @@ export const TRANSFORM_TRANSITIONS: ReadonlyArray<SiteRef> = [
file: 'core/Stepper/Step.tsx',
package: 'core',
component: 'Stepper',
- line: 367,
+ line: 412,
decl: "transitionProperty: 'transform'",
},
{
file: 'core/Switch/Switch.tsx',
package: 'core',
component: 'Switch',
- line: 288,
+ line: 275,
decl: "transitionProperty: 'transform, width, height'",
},
{
@@ -920,7 +920,7 @@ export const TRANSFORM_TRANSITIONS: ReadonlyArray<SiteRef> = [
file: 'core/Toast/Toast.tsx',
package: 'core',
component: 'Toast',
- line: 57,
+ line: 83,
decl: "transitionProperty: 'opacity, transform'",
},
{
@@ -969,7 +969,7 @@ export const TRANSFORM_TRANSITIONS: ReadonlyArray<SiteRef> = [
file: 'lab/Drawer/Drawer.tsx',
package: 'lab',
component: 'Drawer',
- line: 157,
+ line: 117,
decl: "transitionProperty: 'transform'",
},
];
@@ -999,7 +999,7 @@ export const INFINITE_LOOPS: ReadonlyArray<SiteRef> = [
file: 'core/Spinner/Spinner.tsx',
package: 'core',
component: 'Spinner',
- line: 263,
+ line: 292,
},
{
file: 'core/StatusDot/StatusDot.tsx',
@@ -1023,13 +1023,13 @@ export const INFINITE_LOOPS: ReadonlyArray<SiteRef> = [
file: 'lab/CircularProgress/CircularProgress.tsx',
package: 'lab',
component: 'CircularProgress',
- line: 189,
+ line: 191,
},
{
file: 'lab/CircularProgress/CircularProgress.tsx',
package: 'lab',
component: 'CircularProgress',
- line: 211,
+ line: 213,
},
];
@@ -1181,6 +1181,11 @@ export const NO_REDUCED_MOTION: ReadonlyArray<{
package: 'core',
component: 'TreeList',
},
+ {
+ file: 'core/Typeahead/busyIndicatorLane.tsx',
+ package: 'core',
+ component: 'Typeahead',
+ },
{
file: 'core/hooks/useKeyboardHint.tsx',
package: 'core',
@@ -1297,6 +1302,7 @@ export const ANIMATING_COMPONENTS: ReadonlyArray<string> = [
'TopNav',
'Tour',
'TreeList',
+ 'Typeahead',
];
export const STATIC_COMPONENTS: ReadonlyArray<string> = [
@@ -1362,7 +1368,6 @@ export const STATIC_COMPONENTS: ReadonlyArray<string> = [
'Toolbar',
'Tooltip',
'TransferList',
- 'Typeahead',
'VisuallyHidden',
'VStack',
];
diff --git a/apps/sandbox/src/app/(sandbox)/pages/motion-lab/bugs/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/motion-lab/bugs/page.tsx
index 137c8f8326..28be4654e8 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/motion-lab/bugs/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/motion-lab/bugs/page.tsx
@@ -564,24 +564,22 @@ export default function MotionBugsPage() {
<DemoCard
title="The drawer exit, cut short"
question="Slide 410ms, unmount at 250ms. Drag either slider: at what point does an exit stop being an exit?"
- badges={<Badge variant="error" label="Confirmed in lab" />}>
+ badges={<Badge variant="success" label="Resolved in Lab" />}>
<DemoBody>
<Text type="supporting">
- <strong>The brief is right, to the millisecond.</strong>{' '}
- <code>lab/Drawer/Drawer.tsx:459</code> hardcodes a <code>250</code>
- ms close timer, while <code>:157</code> and <code>:219</code> set
- the panel and scrim transitions to <code>--duration-medium</code> —
- 410ms. The dialog is closed at 61% of its own travel, so the last
- 160ms of the slide never renders.
+ <strong>This was the lab failure.</strong> The former implementation
+ hardcoded a <code>250</code>ms close timer while the panel and scrim
+ transitions used <code>--duration-medium</code> (410ms by default).
+ The dialog closed at 61% of its own travel, so the last 160ms of the
+ slide never rendered.
</Text>
<Text type="supporting" color="secondary">
- The reduced-motion branch beside it is the tell: the same expression
- picks <code>10</code>ms when the user asks for less motion, which
- means someone thought carefully about the timer and still had to
- restate the duration by hand. Nothing in either package derives a
- timer from its transition; MobileNav is the only component that even
- tries, and it does it by reading <code>getComputedStyle</code>. That
- is the argument for the JS token mirror in one file.
+ Lab Drawer now waits for the actual transform transition and uses a
+ computed-duration backstop in{' '}
+ <code>lab/Drawer/useDrawerDialogPresence.ts</code>. Theme motion can
+ no longer desynchronize the visual exit from native-host release;
+ the sliders below preserve the original failure as an interactive
+ explanation of why the fix matters.
</Text>
</DemoBody>
<DemoBody>
diff --git a/apps/storybook/stories/Drawer.stories.tsx b/apps/storybook/stories/Drawer.stories.tsx
index 2020a72e56..2ca2c12c65 100644
--- a/apps/storybook/stories/Drawer.stories.tsx
+++ b/apps/storybook/stories/Drawer.stories.tsx
@@ -99,8 +99,8 @@ export const Showcase: Story = {
export const RowInspector: Story = {
render: () => {
- const [selectedId, setSelectedId] = useState<string | null>(null);
- const selected = HOSTS.find(host => host.id === selectedId);
+ const [selected, setSelected] = useState(HOSTS[0]);
+ const [isOpen, setIsOpen] = useState(false);
return (
<>
<VStack gap={1}>
@@ -109,40 +109,94 @@ export const RowInspector: Story = {
key={host.id}
variant="ghost"
label={`${host.id} / ${host.region}`}
- onClick={() => setSelectedId(host.id)}
+ onClick={() => {
+ setSelected(host);
+ setIsOpen(true);
+ }}
/>
))}
</VStack>
<Drawer
- isOpen={selected != null}
- onOpenChange={isOpen => !isOpen && setSelectedId(null)}
- label={selected ? `Host details: ${selected.id}` : 'Host details'}
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label={`Host details: ${selected.id}`}
hasScrim={false}
width={360}>
- {selected != null && (
- <Section padding={4}>
- <VStack gap={4}>
- <VStack gap={1}>
- <Heading level={3}>{selected.id}</Heading>
- <Text type="supporting" color="secondary">
- {selected.region}
- </Text>
- </VStack>
- <Divider />
- <VStack gap={2}>
- <Text type="label">Status</Text>
- <Text type="body">{selected.status}</Text>
- <Text type="label">CPU</Text>
- <Text type="body">{selected.cpu}</Text>
- </VStack>
- <Button
- label="Close inspector"
- variant="secondary"
- onClick={() => setSelectedId(null)}
- />
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>{selected.id}</Heading>
+ <Text type="supporting" color="secondary">
+ {selected.region}
+ </Text>
</VStack>
- </Section>
- )}
+ <Divider />
+ <VStack gap={2}>
+ <Text type="label">Status</Text>
+ <Text type="body">{selected.status}</Text>
+ <Text type="label">CPU</Text>
+ <Text type="body">{selected.cpu}</Text>
+ </VStack>
+ <Button
+ label="Close inspector"
+ variant="secondary"
+ onClick={() => setIsOpen(false)}
+ />
+ </VStack>
+ </Section>
+ </Drawer>
+ </>
+ );
+ },
+};
+
+/**
+ * Sibling drawers share one top-layer stack. A closing inner drawer continues
+ * to own Escape until its slide-out finishes, then the outer drawer becomes
+ * the topmost dismissible surface.
+ */
+export const StackedDrawers: Story = {
+ render: () => {
+ const [orderOpen, setOrderOpen] = useState(false);
+ const [lineItemOpen, setLineItemOpen] = useState(false);
+ return (
+ <>
+ <Button label="Open order" onClick={() => setOrderOpen(true)} />
+ <Drawer
+ isOpen={orderOpen}
+ onOpenChange={setOrderOpen}
+ label="Order details"
+ hasScrim={false}>
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Order #4821</Heading>
+ <Text type="body">Three line items, ready to ship.</Text>
+ <Button
+ label="Open line item"
+ data-autofocus
+ onClick={() => setLineItemOpen(true)}
+ />
+ </VStack>
+ </Section>
+ </Drawer>
+ <Drawer
+ isOpen={lineItemOpen}
+ onOpenChange={setLineItemOpen}
+ label="Line item details"
+ hasScrim={false}
+ width={320}>
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Compute instance</Heading>
+ <Text type="body">Quantity 6 · us-east-1</Text>
+ <Button
+ label="Close line item"
+ variant="secondary"
+ data-autofocus
+ onClick={() => setLineItemOpen(false)}
+ />
+ </VStack>
+ </Section>
</Drawer>
</>
);
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 50e3910cf1..9f197a29f6 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -14,6 +14,7 @@ applies_to:
packages/core/src/Layer/,
packages/core/src/Popover/,
packages/core/src/Dialog/,
+ packages/lab/src/Drawer/,
packages/core/src/DropdownMenu/,
packages/core/src/Tooltip/,
packages/core/src/HoverCard/,
@@ -161,16 +162,16 @@ can perform its own action without closing the layer.
`family:overlay-dismissal` owns the shipped Escape/platform-close membership
contract. The current shared stack registers present layers with `close` or
`block` behavior and orders them by logical depth, DOM containment, then stable
-registration sequence. `useFocusTrap` adapts an active trap with `onEscape` into
+active-cycle registration sequence. `useFocusTrap` adapts an active trap with `onEscape` into
that stack.
-Tooltip, HoverCard, Dialog, Popover, DropdownMenu, Lightbox, MobileNav, and
-BottomSheetSwitcher all register with the shared stack. Tooltip and HoverCard
-report current DOM presence; Popover and DropdownMenu register through
-`useFocusTrap`; Dialog, Lightbox, MobileNav, and BottomSheetSwitcher additionally
-ask `shouldDismissOnCloseRequest()` before acting on native platform close
-requests. Other family members still use local Escape handling as listed in
-`family:overlay-dismissal`.
+Tooltip, HoverCard, Dialog, Lab Drawer, Popover, DropdownMenu, Lightbox,
+MobileNav, and BottomSheetSwitcher all register with the shared stack. Tooltip
+and HoverCard report current DOM presence; Popover and DropdownMenu register
+through `useFocusTrap`; Dialog, Lightbox, MobileNav, BottomSheetSwitcher, and
+Lab Drawer additionally ask `shouldDismissOnCloseRequest()` before acting on
+native platform close requests. Other family members still use local Escape
+handling as listed in `family:overlay-dismissal`.
Outside interaction is not coordinated by the shared stack. Current paths are
independent:
@@ -350,6 +351,8 @@ be updated only as that work ships.
menu-cascade parent-close chain.
- Dialog families own native modal/backdrop presentation and their local channel
policies.
+- Lab Drawer owns modal `showModal()` and non-modal `showPopover()` hosting while
+ the shared dismissal stack owns Escape and platform close routing.
- `LayerProvider`, `ToastContext`, `useToast`, and `ToastViewport` own current
notification state, dispatch, and viewport rendering.
- CommandPalette owns command search and selection; Dialog owns its native modal
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index deff79eded..ccbb97a7f7 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -15,6 +15,7 @@ verified_by:
packages/core/src/Layer/useLayerDismissal.test.tsx,
packages/core/src/Layer/layerDismissalInvariants.test.tsx,
packages/core/src/Layer/layerDismissalFamilies.test.tsx,
+ packages/lab/src/Drawer/Drawer.test.tsx,
packages/core/src/hooks/useFocusTrap.test.tsx,
packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
]
@@ -157,9 +158,9 @@ this record's current membership snapshot must be updated with it.
- **FR4 — Available nesting signals outrank host placement.** When a member
provides `LayerDepthProvider`, React-tree depth orders its descendant layers
ahead of the member even when both mount in the same commit. DOM containment
- may resolve equal-depth nesting; stable registration order resolves unrelated
- surfaces. A member without the provider does not guarantee this ordering for
- descendant content that is no longer DOM-contained.
+ may resolve equal-depth nesting; stable active-cycle registration order resolves
+ unrelated surfaces. A member without the provider does not guarantee this
+ ordering for descendant content that is no longer DOM-contained.
- **FR5 — Content may claim Escape first.** The shared listener runs in the
bubble phase and stands down when content has already handled the event.
- **FR6 — Text composition is not layer dismissal.** Escape used to cancel an
@@ -193,19 +194,19 @@ this record's current membership snapshot must be updated with it.
| Lightbox or MobileNav above a required Dialog | Top member handles the request | Required Dialog uses `block` only when it is topmost |
| Required Dialog alone | Request is consumed without closing | Dialog purpose selects `block` behavior |
| Self-owned input popup | Popup participates while present | Input owns selection, focus, open state, positioning, and outside dismissal |
-| Two unrelated registered surfaces | Later stable registration is topmost | Neither surface is treated as nested |
+| Two unrelated registered surfaces | Later active-cycle registration is topmost | Neither surface is treated as nested |
| Platform close request sent to a lower Dialog | Lower Dialog stays open | The platform targets a host; the shared check decides whether it may close |
## Adoption and exceptions
| Components or surface | Adoption | Current deviation or limitation |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Dialog, AlertDialog, Popover, DropdownMenu root, MoreMenu, Lightbox, MobileNav | shared owner | none |
+| Dialog, AlertDialog, Popover, DropdownMenu root, MoreMenu, Lightbox, MobileNav, Lab Drawer | shared owner | none |
| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers |
| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth |
| BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Adaptive BottomSheet paths inherit BottomSheet's adoption gap; Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
| BottomSheetSwitcher | shared owner | none |
-| BottomSheet, CommandPalette, ContextMenu, DropdownMenuSubMenu, PowerSearchEditPopover, Lab Drawer | local only | Must migrate from component-specific listeners or registries to the shared owner |
+| BottomSheet, CommandPalette, ContextMenu, DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
The rows marked partial or local are current adoption gaps against FR1. They are
not approved exceptions. Migration must preserve each component's existing focus,
diff --git a/docs/specs/AST-027/spec.md b/docs/specs/AST-027/spec.md
index 7fba17720c..c8ad700f9a 100644
--- a/docs/specs/AST-027/spec.md
+++ b/docs/specs/AST-027/spec.md
@@ -194,14 +194,14 @@ production declarations across 40 files and these current gaps:
| CLI-emitted page templates | Dashboard alert rail and Settings dialog use local `1`; Table filter uses reorder `2`; Kanban renders a fixed drag clone at `1000` | **Generated leaks.** New consumer apps inherit implicit local boundaries and, for Kanban, a page-level floating band | Add explicit surface isolation to local template relationships; route the Kanban drag clone through a visual-only Layer/top-layer host |
| Popover, Lightbox, and modal panel internals | Small values order arrows, controls, handles, panels, and tints inside native Popover or dialog hosts | **Correct cross-page mechanism; local ownership still requires proof.** The browser host, not the number, places the surface above page content | Preserve top-layer hosting and add or identify an explicit isolation owner for each internal relationship |
| ToastViewport | The viewport enters `popover="manual"` but also carries `z-index: 500` | **Redundant page-band value plus the AST-003 hosting gap.** Native promotion, not `500`, owns page-content order; current Toast can still sit behind a later modal | Complete AST-003's global host first or in the same change, then remove `500` and keep any internal ordering beneath an isolated viewport surface |
-| BottomSheet, BottomSheetSwitcher, and Lab Drawer non-modal paths | Non-modal `dialog.show()` paths use static or dynamic values beginning at `1000` | **Confirmed global leaks.** A page band cannot provide dialog-layer semantics | Route non-modal hosting through Layer/native top-layer infrastructure; keep panel, handle, tint, action, and stack ordering locally isolated inside the host |
+| BottomSheet and BottomSheetSwitcher non-modal paths | Non-modal `dialog.show()` paths use static or dynamic values beginning at `1000` | **Confirmed global leaks.** A page band cannot provide dialog-layer semantics | Route non-modal hosting through Layer/native top-layer infrastructure; keep panel, handle, tint, action, and stack ordering locally isolated inside the host |
Current source already routes Tooltip, HoverCard, Popover, DropdownMenu and its
-submenus, ContextMenu, CommandPalette, modal Dialog, Lightbox, MobileNav, Tour,
-Date-input layers, and RadialTooltip through Layer, native Popover, or
-`showModal()`. Their cross-page mechanism is directionally conforming. The
-confirmed exceptions are ChartTooltip and the non-modal BottomSheet,
-BottomSheetSwitcher, and Drawer paths. Toast is promoted but still has the
+submenus, ContextMenu, CommandPalette, modal Dialog, Lab Drawer, Lightbox,
+MobileNav, Tour, Date-input layers, and RadialTooltip through Layer, native
+Popover, or `showModal()`. Their cross-page mechanism is directionally
+conforming. The confirmed exceptions are ChartTooltip and the non-modal
+BottomSheet and BottomSheetSwitcher paths. Toast is promoted but still has the
global-host limitation already owned by AST-003.
This table is an impact inventory, not an implementation approval. Each row still
diff --git a/package.json b/package.json
index 99cac23818..f754d75d0f 100644
--- a/package.json
+++ b/package.json
@@ -41,6 +41,7 @@
"lab:readiness": "node internal/lab-readiness/audit.mjs",
"lab:readiness:check": "node internal/lab-readiness/audit.mjs --check",
"guard:modal-close": "node .github/scripts/modal-close-visibility.js",
+ "guard:modal-close:webkit": "node .github/scripts/modal-close-visibility.js --browser webkit",
"guard:theme-vars": "node .github/scripts/theme-var-reachability.js",
"guard:theme-layers": "node .github/scripts/theme-layer-cascade.js",
"guard:disabled-hover": "node .github/scripts/disabled-hover-audit.js",
diff --git a/packages/core/src/Layer/layerStack.ts b/packages/core/src/Layer/layerStack.ts
index 5f998f73bf..b85e470748 100644
--- a/packages/core/src/Layer/layerStack.ts
+++ b/packages/core/src/Layer/layerStack.ts
@@ -134,11 +134,13 @@ export interface LayerStackEntry {
}
const entries: LayerStackEntry[] = [];
-// Registration order per layer identity. A layer re-registers whenever its
-// depth or behavior changes — a Dialog whose `purpose` flips while open, a focus trap
-// that moves — and StrictMode remounts every effect once more on top of that.
-// Counting registrations instead would hand the layer a fresh, higher seq each
-// time and promote it above the layers opened over it.
+// Registration order per layer identity. `useLayerDismissal` keeps one token
+// through effect re-registration while an active layer changes depth or behavior
+// — a Dialog whose `purpose` flips while open, a focus trap that moves — and
+// through StrictMode's setup/cleanup replay. Counting those registrations would
+// hand the layer a fresh, higher seq and promote it above layers opened over it.
+// A genuine inactive -> active cycle receives a new token in the hook, matching
+// the browser top layer's show order.
let seqByToken = new WeakMap<object, number>();
let nextSeq = 0;
let isListening = false;
@@ -165,11 +167,11 @@ function seqFor(token: object): number {
* `LayerDepthProvider`, which a bare `useFocusTrap` cannot do — it renders
* nothing. For those, containment recovers the nesting the tree did not
* report.
- * 3. **Registration order.** For unrelated layers, the one that registered
- * later is on top, matching how the browser's own top layer stacks. A layer
- * keeps its first place for as long as its identity lives, so one that
- * closes and reopens does not move to the top — see the known edge in the
- * pull request.
+ * 3. **Registration order.** For unrelated layers, the one whose current active
+ * cycle registered later is on top, matching how the browser's own top layer
+ * stacks. Effect re-registration within that active cycle keeps its place so
+ * depth or behavior changes cannot jump the queue; a close/reopen cycle gets
+ * a fresh identity from `useLayerDismissal` and moves to the top.
*
* Modality is deliberately NOT a key. Ranking modals above everything sounds
* right and is not: a hover tip shown inside a modal renders on top of it, so
diff --git a/packages/core/src/Layer/useLayerDismissal.test.tsx b/packages/core/src/Layer/useLayerDismissal.test.tsx
index 8ca73ed75a..219d967fa1 100644
--- a/packages/core/src/Layer/useLayerDismissal.test.tsx
+++ b/packages/core/src/Layer/useLayerDismissal.test.tsx
@@ -242,6 +242,34 @@ describe('useLayerDismissal', () => {
expect(older).not.toHaveBeenCalled();
});
+ it('moves a reopened unrelated layer above siblings that stayed open', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const {rerender} = render(
+ <>
+ <Layer onDismiss={first} />
+ <Layer onDismiss={second} />
+ </>,
+ );
+
+ rerender(
+ <>
+ <Layer onDismiss={first} isActive={false} />
+ <Layer onDismiss={second} />
+ </>,
+ );
+ rerender(
+ <>
+ <Layer onDismiss={first} />
+ <Layer onDismiss={second} />
+ </>,
+ );
+
+ pressEscape();
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).not.toHaveBeenCalled();
+ });
+
it('keeps ordering under StrictMode, which mounts every effect twice', () => {
const first = vi.fn();
const second = vi.fn();
diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.ts
index 626c0a3f87..2dc2b8fa1e 100644
--- a/packages/core/src/Layer/useLayerDismissal.ts
+++ b/packages/core/src/Layer/useLayerDismissal.ts
@@ -97,15 +97,15 @@ export interface UseLayerDismissalReturn {
* The layer does NOT attach a key listener — the stack owns one listener and
* routes each Escape press to the top-most REGISTERED layer, so one press
* dismisses exactly one of them. Dialog (and what is built on it), Popover and
- * the menus built on it, Tooltip, HoverCard, Lightbox, MobileNav and
- * BottomSheetSwitcher register today.
+ * the menus built on it, Tooltip, HoverCard, Lightbox, MobileNav,
+ * BottomSheetSwitcher and lab's `Drawer` register today.
*
- * `BottomSheet`, `CommandPalette`, `ContextMenu`, `DropdownMenuSubMenu`,
- * `PowerSearchEditPopover` and lab's `Drawer` still run their own Escape
- * listener. They stay safe next to the stack only because each claims the press
- * at element level, and the stack stands down on an already-`defaultPrevented`
- * press — but a registered layer opened INSIDE one of them does not get the
- * press: the host takes it and closes instead. Migrating them is the fix.
+ * `BottomSheet`, `CommandPalette`, `ContextMenu`, `DropdownMenuSubMenu`, and
+ * `PowerSearchEditPopover` still run their own Escape listeners. They stay safe
+ * next to the stack only because each claims the press at element level, and the
+ * stack stands down on an already-`defaultPrevented` press — but a registered
+ * layer opened inside one of them does not get the press. Migrating them is the
+ * fix.
*
* Wrap the layer's own content in `LayerDepthProvider` so anything opened from
* inside it registers as nested.
@@ -132,8 +132,12 @@ export function useLayerDismissal(
const depth = useLayerDepth();
- // Identity for this layer's stack entry, stable across re-registration.
+ // Identity remains stable while one active layer re-registers because its
+ // depth or behavior changed. A later inactive -> active cycle gets a fresh
+ // identity below so its registration order matches a newly shown top-layer
+ // host rather than the component's original mount order.
const tokenRef = useRef<object>({});
+ const wasRegisteredRef = useRef(false);
// The stack calls these during an event, outside React's render, so they must
// reach the latest closures rather than the ones captured at registration.
@@ -150,8 +154,13 @@ export function useLayerDismissal(
useEffect(() => {
if (!isRegistered) {
+ wasRegisteredRef.current = false;
return;
}
+ if (!wasRegisteredRef.current) {
+ tokenRef.current = {};
+ wasRegisteredRef.current = true;
+ }
return registerLayer({
token: tokenRef.current,
depth,
diff --git a/packages/lab/src/Drawer/Drawer.doc.mjs b/packages/lab/src/Drawer/Drawer.doc.mjs
index f01610273c..769558faf6 100644
--- a/packages/lab/src/Drawer/Drawer.doc.mjs
+++ b/packages/lab/src/Drawer/Drawer.doc.mjs
@@ -77,7 +77,7 @@ export const docs = {
name: 'hasScrim',
type: 'boolean',
description:
- 'Modal scrim behind the drawer. true uses showModal() (top layer, focus trap, scroll lock; clicking the scrim closes; modal only); false uses show() for a non-modal overlay that does NOT trap focus and keeps the page behind interactive.',
+ 'Modal scrim behind the drawer. true uses showModal() (top layer, focus trap, scroll lock; clicking the scrim closes; modal only); false uses the manual Popover API for a non-modal top-layer overlay that does NOT trap focus and keeps the page behind interactive.',
default: 'true',
},
{
diff --git a/packages/lab/src/Drawer/Drawer.spec.md b/packages/lab/src/Drawer/Drawer.spec.md
index 0d8e2d122a..9f7f77d9d9 100644
--- a/packages/lab/src/Drawer/Drawer.spec.md
+++ b/packages/lab/src/Drawer/Drawer.spec.md
@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/lab/src/Drawer/Drawer.test.tsx,
+ packages/core/src/Layer/useLayerDismissal.test.tsx,
+ packages/core/src/Layer/layerDismissalFamilies.test.tsx,
.github/scripts/modal-close-visibility.js,
apps/storybook/rtl-audit/rtl-audit.mjs,
scripts/check-knowledge.mjs,
@@ -35,15 +37,15 @@ system_specs: [spec:AST-027/DEC-3]
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Current Lab surface | No public-API delta. At this commit, the experimental `@astryxdesign/lab` root exports `Drawer` and `DrawerProps`; `DrawerProps` extends `BaseProps<HTMLDialogElement>`, separately declares `ref`, and requires `isOpen`, `onOpenChange`, `label`, and `children`. This records current reachability, not a stable compatibility promise. |
-| Behavior | Drawer-owned visibility is controlled by the caller for a viewport-relative, full-height logical-side overlay. Native mode is selected from `hasScrim` at open; changing it while open is unsupported, although the current implementation updates scrim styling, `aria-modal`, modal-root clicks, and body lock live. Drawer-local registration gates Escape for same-presentation siblings and assigns non-modal z-index; modal paint is browser-owned, while mixed-presentation and nested stacking are unspecified. Exit renders current children. |
-| End-user impact | None from this documentation-only record; current modal/non-modal semantics, focus return, dismissal, motion, sizing, and sibling ordering remain unchanged. |
-| Builder impact | None; there is no migration or new caller choice. State and content remain caller-owned; Drawer renders the caller's current children during exit. Sibling composition remains current consumer guidance. |
-| Compatibility/readiness | Additive documentation with no runtime or default change; Drawer remains experimental in Lab, this record remains `draft`, and its candidate statements require approval. FR13–FR14 record named family/top-layer conformance gaps. |
-| Review checks | Reject regional, docked, or block-axis models; claims that modality and scrim are currently independent; or claims that the local registry and non-modal `show()` path satisfy shared dismissal/top-layer rules, guarantee mixed-presentation or nested ordering, or establish stable API/theming compatibility. |
-| Record context | `component:Drawer` FR1–FR14 and AR1–AR6 are draft candidate statements. Linked records govern only within their own declared authority and scope. |
+| Area | Contract |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Current Lab surface | No public-API delta. At this commit, the experimental `@astryxdesign/lab` root exports `Drawer` and `DrawerProps`; `DrawerProps` extends `BaseProps<HTMLDialogElement>`, separately declares `ref`, and requires `isOpen`, `onOpenChange`, `label`, and `children`. This records current reachability, not a stable compatibility promise. |
+| Behavior | Drawer-owned visibility is controlled by the caller for a viewport-relative, full-height logical-side overlay. `hasScrim` at native open selects `showModal()` or a manual Popover API host; changing it while open is unsupported. The shared layer dismissal stack gates Escape and platform close for the full rendered lifetime, the browser top layer owns paint order in both presentations, exit renders current children, and completed close returns focus to the element focused at open. |
+| End-user impact | Behavioral hardening only: Escape and platform close now resolve through the shared topmost/IME decision across overlay families, non-modal drawers paint in the browser top layer instead of a page-level z-index band, one dismissal request affects one surface even during exit or reopen, and focus returns to the opening element after completed close. Props, motion, sizing, and modal semantics are otherwise unchanged. |
+| Builder impact | None; there is no migration or new caller choice. State and content remain caller-owned; Drawer renders the caller's current children during exit. Sibling composition remains current consumer guidance, and a consumer `onKeyDown` that prevents default still cancels Escape dismissal. |
+| Compatibility/readiness | Behavioral hardening inside Lab with no public prop, default, or theming-target change; Drawer remains experimental in Lab, this record remains `draft`, and its candidate statements require approval. FR13–FR14 record shared-family and top-layer conformance replacing the previously recorded gaps. |
+| Review checks | Reject regional, docked, or block-axis models; claims that modality and scrim are currently independent; reintroduction of a Drawer-local Escape registry or page-level z-index band; claims that mixed-presentation or nested stacking is guaranteed beyond the shared stack's contract; or claims of stable API/theming compatibility. |
+| Record context | `component:Drawer` FR1–FR14 and AR1–AR6 are draft candidate statements. Linked records govern only within their own declared authority and scope. |
This table summarizes the draft body below; it does not change this record's declared authority.
@@ -54,16 +56,17 @@ floats over the current page without reflowing it. It supports modal inspection
with a scrim and non-modal master-detail inspection that leaves the page behind
available.
-This draft records the viewport-only Lab component that exists on current `main`.
-It introduces no runtime, styling, theming, or public-API change. In particular,
-it does not revive a regional, pane-scoped, or container-targeted Drawer model.
+This draft records the viewport-only Lab component after its current
+layer-lifecycle hardening. It introduces no new public prop or scope concept. In
+particular, it does not revive a regional, pane-scoped, or container-targeted
+Drawer model.
## Compatibility and migration
- Released default preserved: `not yet released`; Drawer remains in
`@astryxdesign/lab`.
-- Compatibility class: additive maintainer documentation only; runtime, DOM,
- styling, targets, props, and consumer docs remain unchanged.
+- Compatibility class: behavioral hardening inside Lab; public props, defaults,
+ root element, styling inputs, and controlled ownership remain unchanged.
- Controlled/uncontrolled behavior: unchanged for Drawer-owned paths; callers
provide `isOpen`, while direct native mutation through the public dialog ref is
outside that guarantee.
@@ -78,13 +81,13 @@ Consumer migration instructions belong in consumer docs and release notes.
- The viewport-relative side-panel surface, logical edge, inline-size budget, and
entry/exit motion.
- The current presentation input: its value at native open selects `showModal()`
- or `show()`. Changing it while open is unsupported; current live effects are
- recorded as implementation facts rather than durable transition policy.
+ or the manual Popover API host. Changing it while open is unsupported.
- Drawer-local focus entry/return, built-in close affordance, uncanceled
backdrop-click handling, and retention of its host through controlled exit
while rendering current caller-owned children.
-- The local registration order used for same-presentation sibling Escape
- eligibility and non-modal z-index assignment. Modal paint order is browser-owned.
+- Registering the layer with the shared dismissal stack for its rendered
+ lifetime. Escape and platform-close routing belong to the shared owner; paint
+ order in both presentations belongs to the browser top layer.
**Does not own / non-goals**
@@ -94,7 +97,7 @@ Consumer migration instructions belong in consumer docs and release notes.
- Regional or pane-scoped placement, a caller-supplied container, or independent
modality and scrim axes. Those are not current Drawer concepts.
- Cross-family Escape and platform-close ordering — owned by
- `family:overlay-dismissal`; current Drawer has a recorded local-adoption gap.
+ `family:overlay-dismissal`; Drawer participates through the shared owner.
- Button painting for the built-in close affordance — delegated to
`component:Button` through IconButton.
@@ -102,34 +105,34 @@ Consumer migration instructions belong in consumer docs and release notes.
Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
-| Concept | Closed values or states | Meaning | Availability by state | Default | Owner | Stability | Invalid-value behavior |
-| ------------------ | --------------------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------- | ------------------ | ------------------------- | ------------------------------------------------------ |
-| visibility | open, closed | whether caller-controlled Drawer presentation is requested | all presentations | caller-controlled | `component:Drawer` | experimental Lab contract | required controlled value |
-| logical edge | inline start, inline end | viewport edge from which the panel enters and exits | open and exiting | inline end | `component:Drawer` | experimental Lab contract | closed type rejects other values |
-| presentation | modal with scrim, non-modal without scrim | native open mode and associated initial semantics | chosen when the native dialog opens; live changes are unsupported | modal with scrim | `component:Drawer` | experimental Lab contract | one current boolean selects the initial mode |
-| inline-size budget | pixel number or valid CSS length | desktop inline size and reveal-mode mobile cap | desktop and mobile page-reveal mode | `400px` | `component:Drawer` | experimental Lab contract | invalid CSS lengths are unsupported |
-| mobile coverage | page reveal, full viewport | whether narrow viewports retain a visible page strip | viewports at or below the mobile boundary | 56px page reveal | `component:Drawer` | experimental Lab contract | closed boolean |
-| close affordance | built-in close button present, absent | whether Drawer supplies its top-trailing close action | modal and non-modal presentations | present | `component:Drawer` | experimental Lab contract | closed boolean |
-| sibling order | earlier opened, later opened, exiting, closed | same-presentation local Escape eligibility and non-modal z-index assignment | sibling Drawers using one presentation mode | later opened is last registry entry | `component:Drawer` | experimental Lab contract | mixed-presentation and nested stacking are unspecified |
+| Concept | Closed values or states | Meaning | Availability by state | Default | Owner | Stability | Invalid-value behavior |
+| ------------------ | --------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------- | ----------------------- | ------------------ | ------------------------- | ----------------------------------------------------- |
+| visibility | open, closed | whether caller-controlled Drawer presentation is requested | all presentations | caller-controlled | `component:Drawer` | experimental Lab contract | required controlled value |
+| logical edge | inline start, inline end | viewport edge from which the panel enters and exits | open and exiting | inline end | `component:Drawer` | experimental Lab contract | closed type rejects other values |
+| presentation | modal with scrim, non-modal without scrim | native host mode and associated document semantics | chosen when the native host opens; live changes are unsupported | modal with scrim | `component:Drawer` | experimental Lab contract | one current boolean selects the initial mode |
+| inline-size budget | pixel number or valid CSS length | desktop inline size and reveal-mode mobile cap | desktop and mobile page-reveal mode | `400px` | `component:Drawer` | experimental Lab contract | invalid CSS lengths are unsupported |
+| mobile coverage | page reveal, full viewport | whether narrow viewports retain a visible page strip | viewports at or below the mobile boundary | 56px page reveal | `component:Drawer` | experimental Lab contract | closed boolean |
+| close affordance | built-in close button present, absent | whether Drawer supplies its top-trailing close action | modal and non-modal presentations | present | `component:Drawer` | experimental Lab contract | closed boolean |
+| sibling order | earlier opened, later opened, exiting, closed | shared-stack Escape eligibility and browser top-layer paint order | sibling Drawers in either presentation | later opened is topmost | `component:Drawer` | experimental Lab contract | nested composition is outside the documented contract |
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
-| FR1 | Drawer MUST remain a viewport-relative, full-block-size overlay on the logical inline-start or inline-end edge and MUST NOT reserve layout space or reflow the page beneath it. | Current source, docs, stories, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The logical edge selected for an open Drawer MUST remain latched through its exit even when caller state changes the live edge prop during close. | Current exit-side test and implementation | Verified current behavior |
-| FR3 | The desktop inline-size budget MUST accept pixel numbers or CSS lengths and remain bounded by the viewport. At or below 640px, page-reveal mode MUST preserve 56px and use `width` as a cap; full-mobile mode MUST override `width` with `100dvw`. | Current docs, styles, and width tests | Verified current behavior |
-| FR4 | Visibility through Drawer-owned behavior MUST follow `isOpen`. Uncanceled Escape and modal-backdrop handling, and the built-in close action, request `false`; Drawer prevents its handled native `cancel` event from closing the dialog directly. During controlled exit, Drawer keeps its host and content region mounted while rendering the caller's current `children`. | Current prop contract and lifecycle tests | Verified for Drawer-owned paths; direct native mutation through the public ref is outside this guarantee |
-| FR5 | At open time, `hasScrim={true}` MUST select native `showModal()` with `aria-modal`, body scroll locking, and a visible backdrop; `hasScrim={false}` MUST select non-modal `show()` and leave the page behind interactive. Changing `hasScrim` while open is not a supported native-mode transition. The current implementation still updates scrim styling, `aria-modal`, modal-root click handling, and body locking live without switching the native mode. | Current source, docs, and initial-mode tests | Initial modes verified; live presentation changes unsupported |
-| FR6 | An uncanceled modal root/backdrop click (`target === currentTarget` while live `hasScrim` is true) MUST request close. Descendant clicks and dialog-root clicks while live `hasScrim` is false MUST NOT request close, and non-modal presentation MUST NOT install an invisible outside-pointer dismissal plane. | Current click tests | Verified current behavior |
-| FR7 | The built-in close affordance MUST appear by default in both presentations, carry an accessible name, and request close without taking open-state ownership. Callers may explicitly omit it. | Current docs and close-button tests | Verified current behavior |
-| FR8 | Opening MUST present the native dialog and attempt to focus the first rendered `[data-autofocus]` descendant, if any. After a completed controlled close, Drawer MUST attempt to restore focus to the element that was active before opening. | Current presence hook and focus tests | Verified for completed controlled close |
-| FR9 | Closing MUST retain the panel host, content region, edge, and native dialog while the exit remains visible and continue rendering the caller's current `children`. Once the visible exit completes, Drawer MUST release native dialog state and hide the panel before the next paint. | Current lifecycle tests and browser close-visibility guard | Observable outcome verified; mechanism private |
-| FR10 | Current Drawer-local coordination is registration-based. Among open sibling Drawers using the same presentation mode, the most recently registered handles a Drawer-local Escape event that reaches it; closing or unmounting unregisters it so the prior open Drawer becomes eligible. Non-modal siblings receive increasing local z-indexes, while modal paint order is browser-owned. Mixed-presentation visual ordering and nested stacking are unspecified. | Current source, docs, and non-modal stack tests | Recorded current behavior; local family adoption gap remains |
-| FR11 | At this commit, `DrawerProps` extends `BaseProps<HTMLDialogElement>` and separately declares `ref`. The root filters `open`, merges `xstyle`, `className`, and `style`, forwards remaining unclaimed props, composes consumer `onClick` and `onKeyDown`, and owns `aria-label`, `aria-modal`, and `onCancel`. A consumer `onKeyDown` that prevents default cancels Drawer-owned Escape handling. | Current source and focused keyboard tests | Recorded current Lab behavior; not a stable compatibility decision |
-| FR12 | At this commit, the painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. No separate Drawer target is currently emitted for content or scrim; future target qualification remains owned by `architecture:component-theming-surface`. | Current source, docs, and structural target metadata | Current reachability only; no target-admission decision |
-| FR13 | Drawer currently uses a component-local registry for open order, Escape eligibility, and non-modal z-index assignment. It does not control native modal top-layer order. That implementation is a deviation from `family:overlay-dismissal/FR1`, not an accepted family exception or a new component-local policy. | Current family adoption table | Known current adoption gap |
-| FR14 | Non-modal Drawer currently uses `dialog.show()` plus a page-level z-index band rather than a native top-layer host. That implementation is a named conformance gap against `spec:AST-027/DEC-3`, not part of the durable component contract. | Current source and `spec:AST-027` | Known current top-layer gap |
+| ID | Candidate invariant | Basis | Draft review state |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
+| FR1 | Drawer MUST remain a viewport-relative, full-block-size overlay on the logical inline-start or inline-end edge and MUST NOT reserve layout space or reflow the page beneath it. | Current source, docs, stories, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The logical edge selected for an open Drawer MUST remain latched through its exit even when caller state changes the live edge prop during close. | Current exit-side test and implementation | Verified current behavior |
+| FR3 | The desktop inline-size budget MUST accept pixel numbers or CSS lengths and remain bounded by the viewport. At or below 640px, page-reveal mode MUST preserve 56px and use `width` as a cap; full-mobile mode MUST override `width` with `100dvw`. | Current docs, styles, and width tests | Verified current behavior |
+| FR4 | Visibility through Drawer-owned behavior MUST follow `isOpen`. Uncanceled Escape routed by the shared stack, uncanceled modal-backdrop activation, and the built-in close action request `false`; Drawer prevents its handled native `cancel` event from closing the dialog directly. During controlled exit, Drawer keeps its host and content region mounted while rendering the caller's current `children`. | Current prop contract and lifecycle tests | Verified for Drawer-owned paths; direct native mutation through the public ref is outside this guarantee |
+| FR5 | At open time, `hasScrim={true}` MUST select native `showModal()` with `aria-modal`, a focus trap, body scroll locking, and a visible backdrop; `hasScrim={false}` MUST select a manual Popover API host that leaves the page behind interactive. Changing `hasScrim` while open is not a supported native-mode transition. | Current source, docs, and initial-mode tests | Initial modes verified; live presentation changes unsupported |
+| FR6 | An uncanceled modal root/backdrop click (`target === currentTarget` while live `hasScrim` is true) MUST request close. Descendant clicks and dialog-root clicks while live `hasScrim` is false MUST NOT request close, and non-modal presentation MUST NOT install an invisible outside-pointer dismissal plane. | Current click tests | Verified current behavior |
+| FR7 | The built-in close affordance MUST appear by default in both presentations, carry an accessible name, and request close without taking open-state ownership. Callers may explicitly omit it. | Current docs and close-button tests | Verified current behavior |
+| FR8 | Opening MUST present the native host, capture the element focused before opening, and attempt to focus the first rendered `[data-autofocus]` descendant, if any. After a completed controlled close releases the native host, Drawer MUST attempt to restore focus to the captured element. The non-modal host's synthetic `close` event MUST dispatch after that restore attempt — matching the task-queued native `dialog.close()` event — so a consumer close listener keeps the last word on final focus. | Current presence hook and focus tests | Verified for completed controlled close |
+| FR9 | Closing MUST retain the panel host, content region, edge, and native presentation while the exit remains visible and continue rendering the caller's current `children`. The transform transition is authoritative, a computed-duration backstop prevents a lost event from stranding the host, and native release and React hiding land together so no frame paints outside the top layer. | Current lifecycle tests and browser close-visibility guard | Observable outcome verified |
+| FR10 | Sibling Drawers MUST be composed as siblings. The last-opened present sibling owns the first Escape request through the shared stack; a closing sibling retains that ownership through its visible exit, and reopening registers a new active cycle so one request never closes two surfaces. Paint order in both presentations follows the browser top layer's chronological order. | Current docs, shared stack, and tests | Verified current behavior |
+| FR11 | At this commit, `DrawerProps` extends `BaseProps<HTMLDialogElement>` and separately declares `ref`. The root filters `open`, merges `xstyle`, `className`, and `style`, forwards remaining unclaimed props, composes consumer `onClick`, forwards consumer `onKeyDown` ahead of the shared document-level Escape owner, and owns `aria-label`, `aria-modal`, and `onCancel`. A consumer `onKeyDown` that prevents default cancels shared-stack Escape dismissal for the press. | Current source and focused keyboard tests | Recorded current Lab behavior; not a stable compatibility decision |
+| FR12 | At this commit, the painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. No separate Drawer target is currently emitted for content or scrim; future target qualification remains owned by `architecture:component-theming-surface`. | Current source, docs, and structural target metadata | Current reachability only; no target-admission decision |
+| FR13 | Drawer MUST join the shared dismissal stack for its full rendered lifetime, provide logical depth to descendant layers, route platform close through the same topmost/IME decision, and preserve consumer `preventDefault()` ownership. | Shared family contract and focused tests | Verified current conformance |
+| FR14 | Non-modal Drawer MUST use a manual Popover API host so cross-surface order comes from the browser top layer rather than a page-level z-index band. The reduced fallback may use `dialog.show()` only below the Popover API support floor. | Current source, browser guard, and `spec:AST-027` | Verified current conformance |
### Allowed variation
@@ -140,46 +143,50 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
- **AV2 — Inline size.** Consumers may choose the desktop budget within valid CSS
and viewport constraints. It remains the cap in mobile page-reveal mode, while
full-mobile mode uses `100dvw` instead.
-- **AV3 — Presentation.** The value at native open selects modal or non-modal
- dialog mode. Changing `hasScrim` while open is unsupported; current live scrim,
- ARIA, root-click, and body-lock updates are implementation effects rather than a
- supported native-mode transition.
+- **AV3 — Presentation.** The value at native open selects the modal dialog or
+ the non-modal popover host. Changing `hasScrim` while open is unsupported.
- **AV4 — Close control.** Callers may hide the built-in close button.
- **AV5 — Motion duration.** Themes may alter the transform transition duration;
close timing follows computed CSS and reduced-motion preferences.
### Representative states
-| State | Required invariant | Allowed variation |
-| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
-| Closed | no native dialog presentation or visible panel | caller content may remain mounted in React |
-| Modal inspector | opened with `hasScrim` true via `showModal()` with scrim, modal semantics, and body lock | edge, width, caller content, autofocus destination, and built-in close affordance |
-| Non-modal master-detail inspector | opened with `hasScrim` false via `show()`; no scrim, `aria-modal`, modal-root dismissal, or body lock; Escape requires an event reaching the dialog | edge, width, caller content, and built-in close affordance |
-| Narrow viewport with page reveal | panel does not exceed its `width` cap and preserves 56px of the page | requested width below the cap |
-| Narrow full-coverage viewport | panel uses `100dvw`, overriding the requested `width` | caller content |
-| Two non-modal sibling Drawers | later-opened open Drawer receives a higher page-level z-index and handles Escape dispatched within it | edge, width, and caller content |
-| Exiting Drawer | panel host, content region, logical edge, and native presentation remain while the exit is visible; current children render | caller-controlled child data and motion duration |
+| State | Required invariant | Allowed variation |
+| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
+| Closed | no native presentation or visible panel | caller content may remain mounted in React |
+| Modal inspector | opened with `hasScrim` true via `showModal()` with scrim, modal semantics, focus trap, and body lock | edge, width, caller content, autofocus destination, and built-in close affordance |
+| Non-modal master-detail inspector | opened with `hasScrim` false via the manual popover host; no scrim, `aria-modal`, or body lock; the page behind stays interactive | edge, width, caller content, and built-in close affordance |
+| Narrow viewport with page reveal | panel does not exceed its `width` cap and preserves 56px of the page | requested width below the cap |
+| Narrow full-coverage viewport | panel uses `100dvw`, overriding the requested `width` | caller content |
+| Two sibling Drawers | later-opened open Drawer paints above through the browser top layer and owns the first Escape request through the shared stack | edge, width, caller content, and either presentation composed as siblings |
+| Exiting Drawer | panel host, content region, logical edge, native presentation, and stack registration remain while the exit is visible; current children render | caller-controlled child data and motion duration |
### Transformation and precedence order
- **ORD1 — Open.** Resolve the current logical edge and width, retain the rendered
panel, capture the currently focused element, use current `hasScrim` to select
- the native dialog mode, then honor a rendered autofocus destination.
+ the native host, then honor a rendered autofocus destination.
- **ORD2 — Close.** During controlled close, Drawer keeps its panel and
- caller-provided content visible through the exit animation. After exit,
- presentation ends without an intermediate visible frame, and Drawer attempts to
- restore focus to the previously focused element when available.
-- **ORD3 — Sibling order.** For same-presentation sibling Drawers, registration
- order gates Drawer-local Escape handling; non-modal siblings also receive
- increasing z-indexes. Modal paint order is browser-owned. Mixed-presentation
- visual ordering and nested stacking are unspecified.
+ caller-provided content visible through the exit animation. Transition
+ completion or the computed-duration backstop releases the native host and hides
+ React output together, so presentation ends without an intermediate visible
+ frame; Drawer then attempts to restore focus to the previously focused element
+ when available. The non-modal host's synthetic `close` event dispatches only
+ after that restore attempt, so a consumer close listener that retargets focus
+ observes the same last-word ordering as the task-queued native event.
+- **ORD3 — Sibling order.** Sibling order comes from the shared dismissal stack
+ and the browser top layer: the last-opened present sibling is frontmost and
+ handles Escape first in both presentations. Descendant overlays remain governed
+ by their own component and family contracts rather than Drawer nesting.
### Performance and resources
-- **PR1 — Exit cleanup.** Any resources used to coordinate exit are released after
+- **PR1 — Exit-only resources.** Transition listeners and the backstop timer exist
+ only while close is waiting for the visible transform exit and are removed on
completion, interruption, or unmount.
-- **PR2 — Presentation cleanup.** Controlled closing or unmounting Drawer releases
- native presentation and any active body scroll lock.
+- **PR2 — Presentation cleanup.** Native presentation and any active body scroll
+ lock exist only for their active states and are released on controlled close,
+ unmount, or hidden Activity cleanup.
- **PR3 — Viewport-relative sizing.** Drawer derives sizing from `width`,
`isFullWidthOnMobile`, and the viewport; callers do not supply a regional
measurement target.
@@ -190,13 +197,12 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
content is not used as an implicit name. Current code does not reject an empty
or whitespace-only value.
- **AR2 — Modal truthfulness.** At open time, `hasScrim={true}` uses native modal
- dialog state and `aria-modal`; `hasScrim={false}` uses non-modal dialog state and
- omits `aria-modal`. Changing `hasScrim` while open is not a supported transition.
-- **AR3 — Keyboard dismissal.** For sibling Drawers using the same presentation
- mode, Escape requests close only for the last-opened still-open Drawer when a
- Drawer-local event reaches it; a consumer `onKeyDown` that prevents default
- cancels Drawer-owned keydown handling, and unrelated keys do not dismiss. Mixed
- presentation modes are not covered by this guarantee.
+ dialog state and `aria-modal`; `hasScrim={false}` uses the non-modal popover
+ host and omits `aria-modal`. Changing `hasScrim` while open is not a supported
+ transition.
+- **AR3 — Keyboard dismissal.** Escape requests close only for the topmost
+ registered layer through the shared stack; a consumer `onKeyDown` that prevents
+ default cancels that dismissal, and unrelated keys do not dismiss.
- **AR4 — Focus lifecycle.** Focus enters visible Drawer content through the
documented autofocus/native path and, after a completed controlled close, Drawer
attempts to restore focus to the element that was active when the Drawer opened.
@@ -226,8 +232,8 @@ does not decide future target qualification.
## Family and system relationships
- `family:overlay-dismissal` owns cross-component Escape and platform-close
- ordering. Drawer is a member but remains local-only on current `main`; FR13
- records that adoption gap without legitimizing a parallel policy.
+ ordering. Drawer participates through the shared owner for its rendered
+ lifetime and supplies logical depth to descendant layers.
- `architecture:layer-runtime` owns the distinction between native modal hosting,
non-modal dialog presentation, top-layer behavior, and shared layer plumbing.
- `architecture:public-component-api` owns stable API admission and compatibility.
@@ -239,21 +245,22 @@ does not decide future target qualification.
- `architecture:component-theming-surface` owns target qualification and future
anatomy mapping; this draft records the existing `drawer` target only.
- `spec:AST-027/DEC-3` requires equivalent floating interactions to use an
- applicable native top-layer host. Current non-modal Drawer does not yet conform;
- FR14 records that system-owned gap without adopting its implementation.
+ applicable native top-layer host. Modal `showModal()` and non-modal manual
+ Popover hosting satisfy that cross-surface route; the documented reduced
+ fallback remains below the Popover API support floor.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| --------------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
-| FR1–FR7 | `Drawer.test.tsx` render, initial-mode, click, sizing, side, and control suites | closed/open, both edges, initial modal/non-modal modes, mobile widths | Layout reflows; an initial mode gains the wrong semantics; uncanceled root-click or full-mobile sizing becomes nondeterministic. | `audit:Drawer/behavior` |
-| FR11 | Drawer source and focused keyboard composition/cancellation tests | filtered `open`, merged styling/ref, forwarded unclaimed props, owned ARIA/cancel, composed click/keydown | Current forwarding changes without review or built-in Escape ignores documented consumer cancellation. | `audit:Drawer/public-api` |
-| FR8, AR1–AR5 | `Drawer.test.tsx` label forwarding, autofocus, close, and focus-return suites | initial modal/non-modal modes, autofocus target, connected previously focused element | Focus moves before presentation, completed controlled close fails to restore focus, or label forwarding/dismissal naming breaks. | `audit:Drawer/accessibility` |
-| FR9, PR1–PR2 | close timing tests, browser close-visibility guard, and presence-hook source inspection | controlled close, transform end, unrelated transition, lost-event backstop | Native presentation ends before visible exit, the host is stranded, cleanup paths retain resources, or an intermediate frame paints outside native presentation. | `audit:Drawer/motion` |
-| FR10, FR13, AR3 | Drawer non-modal LIFO tests plus source and `family:overlay-dismissal` adoption table | two non-modal siblings, Drawer-local keydown, unmount, remaining sibling | One event closes two tested siblings, Drawer-local behavior is promised globally, or tested non-modal ordering is extended to mixed/nested cases. | `audit:Drawer/layers` |
-| FR14 | Drawer source plus `spec:AST-027` impact inventory and DEC-3 | non-modal `show()` host and page-level stack band | The current workaround is documented as conforming or mistaken for durable component policy. | `audit:Drawer/layers` |
-| FR12 | source, `Drawer.doc.mjs`, and current target discovery | start/end root Panel and inherited container context | Current root target/axis or padding reset changes, or the record claims an unreachable child target or decides future admission. | `audit:Drawer/theming` |
-| AR6 | side tests and source inspection plus Storybook ancestor-RTL audit | settled `end` placement under ancestor RTL; transform mirroring and reduced motion source-inspected | Audited settled placement or source-inspected ancestor mirroring/reduced-motion behavior changes without corresponding evidence. | `audit:Drawer/accessibility` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
+| FR1–FR7 | `Drawer.test.tsx` render, initial-mode, click, sizing, side, and control suites | closed/open, both edges, initial modal/non-modal modes, mobile widths | Layout reflows; an initial mode gains the wrong semantics; uncanceled root-click or full-mobile sizing becomes nondeterministic. | `audit:Drawer/behavior` |
+| FR11 | Drawer source and focused keyboard composition/cancellation tests | filtered `open`, merged styling/ref, forwarded unclaimed props, owned ARIA/cancel, composed click, forwarded keydown | Current forwarding changes without review or shared-stack Escape ignores documented consumer cancellation. | `audit:Drawer/public-api` |
+| FR8, AR1–AR5 | `Drawer.test.tsx` label forwarding, autofocus, close, and focus-return suites plus the browser guard's final-focus checks | initial modal/non-modal modes, autofocus target, connected previously focused element, close listener retargeting focus | Focus moves before presentation, completed controlled close fails to restore focus, the synthetic close overrides a consumer listener's focus target, or label forwarding/dismissal naming breaks. | `audit:Drawer/accessibility` |
+| FR9, PR1–PR2 | close timing tests, browser close-visibility guard, and presence-hook source inspection | controlled close, transform end, unrelated transition, lost-event backstop | Native presentation ends before visible exit, the host is stranded, cleanup paths retain resources, or an intermediate frame paints outside native presentation. | `audit:Drawer/motion` |
+| FR10, FR13, AR3 | Drawer shared-stack suites plus `useLayerDismissal` and family tests | siblings, closing top, reopen, unmount, nested descendant | One Escape closes two surfaces, a closing host drops ownership, or a reopened sibling keeps stale order. | `audit:Drawer/layers` |
+| FR14 | Drawer source plus `spec:AST-027` impact inventory and native-host browser guard | modal host, manual-popover host, reduced fallback | Non-modal presentation returns to a page-level band or loses native-host ordering. | `audit:Drawer/layers` |
+| FR12 | source, `Drawer.doc.mjs`, and current target discovery | start/end root Panel and inherited container context | Current root target/axis or padding reset changes, or the record claims an unreachable child target or decides future admission. | `audit:Drawer/theming` |
+| AR6 | side tests and source inspection plus Storybook ancestor-RTL audit | settled `end` placement under ancestor RTL; transform mirroring and reduced motion source-inspected | Audited settled placement or source-inspected ancestor mirroring/reduced-motion behavior changes without corresponding evidence. | `audit:Drawer/accessibility` |
## Decision log
@@ -269,6 +276,6 @@ current-state backfill.
## Content boundary
-This file does not duplicate consumer prop tables or examples, private registry
-and transition algorithms, current audit scores, implementation steps, or shared
-family/system rules. It links to their owners.
+This file does not duplicate consumer prop tables or examples, shared
+dismissal-stack internals, transition algorithms, current audit scores,
+implementation steps, or shared family/system rules. It links to their owners.
diff --git a/packages/lab/src/Drawer/Drawer.test.tsx b/packages/lab/src/Drawer/Drawer.test.tsx
index d2d289670b..6df04911e5 100644
--- a/packages/lab/src/Drawer/Drawer.test.tsx
+++ b/packages/lab/src/Drawer/Drawer.test.tsx
@@ -24,6 +24,12 @@ beforeEach(() => {
HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
this.setAttribute('open', '');
});
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('open');
+ });
HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
this.removeAttribute('open');
});
@@ -90,16 +96,102 @@ describe('Drawer', () => {
expect(screen.getByRole('dialog')).toHaveAttribute('aria-modal', 'true');
});
- it('opens with show() and no aria-modal when hasScrim is false', () => {
+ it('opens with showPopover() and no aria-modal when hasScrim is false', () => {
render(
<Drawer isOpen onOpenChange={() => {}} label="Details" hasScrim={false}>
Content
</Drawer>,
);
- expect(HTMLDialogElement.prototype.show).toHaveBeenCalled();
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();
expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog')).toHaveAttribute('popover', 'manual');
expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-modal');
});
+
+ it('leaves the manual popover and preserves close listeners after exit', () => {
+ const {rerender} = render(
+ <Drawer isOpen onOpenChange={() => {}} label="Details" hasScrim={false}>
+ Content
+ </Drawer>,
+ );
+ const dialog = screen.getByRole('dialog', {hidden: true});
+ const handleClose = vi.fn();
+ dialog.addEventListener('close', handleClose);
+
+ rerender(
+ <Drawer
+ isOpen={false}
+ onOpenChange={() => {}}
+ label="Details"
+ hasScrim={false}>
+ Content
+ </Drawer>,
+ );
+ act(() => {
+ fireEvent.transitionEnd(dialog, {propertyName: 'transform'});
+ });
+
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
+ expect(handleClose).toHaveBeenCalledTimes(1);
+ expect(dialog).not.toHaveAttribute('open');
+ });
+
+ it('dispatches the synthetic close after focus restore so a close listener owns final focus', () => {
+ // Master-detail row switching: the consumer's close listener retargets
+ // focus to the latest selected row. Native dialog.close() queues its
+ // close event as a task, so such a listener always ran after the
+ // drawer's own focus restore — the synthetic popover close must give
+ // the consumer the same last word.
+ function Fixture({isOpen}: {isOpen: boolean}) {
+ return (
+ <>
+ <button type="button">Open row</button>
+ <button type="button">Latest row</button>
+ <Drawer
+ isOpen={isOpen}
+ onOpenChange={() => {}}
+ label="Details"
+ hasScrim={false}>
+ Content
+ </Drawer>
+ </>
+ );
+ }
+ const {rerender} = render(<Fixture isOpen={false} />);
+ const openTrigger = screen.getByRole('button', {name: 'Open row'});
+ const latestRow = screen.getByRole('button', {name: 'Latest row'});
+ openTrigger.focus();
+ rerender(<Fixture isOpen />);
+
+ const dialog = screen.getByRole('dialog', {hidden: true});
+ const handleClose = vi.fn(() => latestRow.focus());
+ dialog.addEventListener('close', handleClose);
+
+ rerender(<Fixture isOpen={false} />);
+ act(() => {
+ fireEvent.transitionEnd(dialog, {propertyName: 'transform'});
+ });
+
+ expect(handleClose).toHaveBeenCalledTimes(1);
+ expect(latestRow).toHaveFocus();
+ });
+
+ it('dispatches exactly one close when an open non-modal drawer unmounts', () => {
+ const {unmount} = render(
+ <Drawer isOpen onOpenChange={() => {}} label="Details" hasScrim={false}>
+ Content
+ </Drawer>,
+ );
+ const dialog = screen.getByRole('dialog', {hidden: true});
+ const handleClose = vi.fn();
+ dialog.addEventListener('close', handleClose);
+
+ unmount();
+
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalledTimes(1);
+ expect(handleClose).toHaveBeenCalledTimes(1);
+ });
});
describe('Escape key', () => {
@@ -349,6 +441,20 @@ describe('Drawer', () => {
});
});
+ it('traps Tab focus inside a modal drawer', () => {
+ render(
+ <Drawer isOpen onOpenChange={() => {}} label="Details">
+ <button type="button">First action</button>
+ </Drawer>,
+ );
+ const closeButton = screen.getByRole('button', {name: 'Close'});
+ closeButton.focus();
+
+ fireEvent.keyDown(document, {key: 'Tab'});
+
+ expect(screen.getByRole('button', {name: 'First action'})).toHaveFocus();
+ });
+
it('focuses the element with data-autofocus on open', () => {
render(
<Drawer isOpen onOpenChange={() => {}} label="Details">
@@ -505,7 +611,7 @@ describe('Drawer', () => {
});
describe('LIFO stacking', () => {
- it('Escape only closes the last-opened drawer', () => {
+ it('Escape closes only the last-opened drawer, regardless of event target', () => {
const closeFirst = vi.fn();
const closeSecond = vi.fn();
render(
@@ -527,17 +633,11 @@ describe('Drawer', () => {
</>,
);
- // Escape inside the first (bottom-of-stack) drawer is ignored.
+ // The shared document-level owner routes Escape to the top layer even
+ // when the event starts inside a lower sibling.
fireEvent.keyDown(screen.getByRole('dialog', {name: 'First'}), {
key: 'Escape',
});
- expect(closeFirst).not.toHaveBeenCalled();
- expect(closeSecond).not.toHaveBeenCalled();
-
- // Escape inside the last-opened drawer closes it.
- fireEvent.keyDown(screen.getByRole('dialog', {name: 'Second'}), {
- key: 'Escape',
- });
expect(closeSecond).toHaveBeenCalledWith(false);
expect(closeFirst).not.toHaveBeenCalled();
});
@@ -565,24 +665,84 @@ describe('Drawer', () => {
);
}
- it('closes stacked drawers innermost-first', () => {
- vi.useFakeTimers();
- try {
- render(<StackHarness />);
- const outer = screen.getByRole('dialog', {name: 'Outer'});
- const inner = screen.getByRole('dialog', {name: 'Inner'});
+ it('keeps a closing top drawer on the stack until its exit completes', () => {
+ render(<StackHarness />);
+ const outer = screen.getByRole('dialog', {name: 'Outer'});
+ const inner = screen.getByRole('dialog', {name: 'Inner'});
- fireEvent.keyDown(inner, {key: 'Escape'});
- // Inner unregistered when isOpen flipped — outer is now the top.
- fireEvent.keyDown(outer, {key: 'Escape'});
- act(() => {
- vi.advanceTimersByTime(300);
- });
- expect(inner).not.toHaveAttribute('open');
- expect(outer).not.toHaveAttribute('open');
- } finally {
- vi.useRealTimers();
- }
+ fireEvent.keyDown(inner, {key: 'Escape'});
+ // The inner host is still top-layer present while it slides out. A second
+ // Escape must be consumed by that closing surface, not reach the outer.
+ fireEvent.keyDown(outer, {key: 'Escape'});
+ expect(outer).toHaveAttribute('open');
+ expect(inner).toHaveAttribute('open');
+
+ act(() => {
+ fireEvent.transitionEnd(inner, {propertyName: 'transform'});
+ });
+ expect(inner).not.toHaveAttribute('open');
+ expect(outer).toHaveAttribute('open');
+
+ fireEvent.keyDown(outer, {key: 'Escape'});
+ act(() => {
+ fireEvent.transitionEnd(outer, {propertyName: 'transform'});
+ });
+ expect(outer).not.toHaveAttribute('open');
+ });
+
+ function ReopenHarness() {
+ const [firstOpen, setFirstOpen] = useState(true);
+ const [secondOpen, setSecondOpen] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setFirstOpen(false)}>
+ Close first
+ </button>
+ <button type="button" onClick={() => setFirstOpen(true)}>
+ Reopen first
+ </button>
+ <Drawer
+ isOpen={firstOpen}
+ onOpenChange={setFirstOpen}
+ label="First"
+ hasScrim={false}>
+ First content
+ </Drawer>
+ <Drawer
+ isOpen={secondOpen}
+ onOpenChange={setSecondOpen}
+ label="Second"
+ hasScrim={false}>
+ Second content
+ </Drawer>
+ </>
+ );
+ }
+
+ it('moves a reopened sibling above a drawer that stayed open', () => {
+ render(<ReopenHarness />);
+ const first = screen.getByRole('dialog', {name: 'First'});
+ const second = screen.getByRole('dialog', {name: 'Second'});
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close first'}));
+ act(() => {
+ fireEvent.transitionEnd(first, {propertyName: 'transform'});
+ });
+ expect(first).not.toHaveAttribute('open');
+ expect(second).toHaveAttribute('open');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Reopen first'}));
+ expect(first).toHaveAttribute('open');
+
+ // Browser top-layer order now paints First above Second. The shared
+ // dismissal stack must use the same reopened-last ordering even when the
+ // key event starts in the lower sibling.
+ fireEvent.keyDown(second, {key: 'Escape'});
+ act(() => {
+ fireEvent.transitionEnd(first, {propertyName: 'transform'});
+ });
+ expect(first).not.toHaveAttribute('open');
+ expect(second).toHaveAttribute('open');
});
it('unregisters unmounted drawers so the remaining one becomes top', () => {
diff --git a/packages/lab/src/Drawer/Drawer.tsx b/packages/lab/src/Drawer/Drawer.tsx
index 2a29412f2e..720bb21960 100644
--- a/packages/lab/src/Drawer/Drawer.tsx
+++ b/packages/lab/src/Drawer/Drawer.tsx
@@ -4,7 +4,7 @@
/**
* @file Drawer.tsx
- * @input Uses React, StyleX, theme tokens and text defaults, Icon/IconButton, useScrollLock/useDrawerDialogPresence, BaseProps, mergeProps/mergeRefs, themeProps
+ * @input Uses React, StyleX, theme tokens and text defaults, Icon/IconButton, shared focus/dismissal/depth primitives, i18n, scroll locking/dialog presence, BaseProps, merged refs/props, themeProps
* @output Exports Drawer component and DrawerProps
* @position Lab implementation; consumed by index.ts, tested by Drawer.test.tsx, demonstrated in Storybook
*
@@ -23,18 +23,17 @@
* Uses the native `<dialog>` element (same precedent as Dialog/MobileNav):
* - `showModal()` when `hasScrim` (default) — top-layer rendering, focus
* trapping, `::backdrop`, no z-index management.
- * - `show()` when `hasScrim={false}` — non-modal overlay; the page behind
- * stays interactive (e.g. master-detail inspectors).
+ * - `showPopover()` when `hasScrim={false}` — non-modal top-layer overlay;
+ * the page behind stays interactive (e.g. master-detail inspectors).
*
- * Entry animation uses `@starting-style`; exit slides out before
- * `dialog.close()` releases the top layer and restores focus to the element
- * that opened the drawer. React owns `display` for both legs rather than a
- * discrete `display` transition, so the panel stops painting in the same
- * commit as `close()` — see the `rendered` style for why that matters.
+ * Entry animation uses `@starting-style`; exit slides out before the active
+ * modal-dialog or manual-popover host releases the top layer and focus returns
+ * to the element that opened the drawer. React owns `display` for both legs
+ * rather than a discrete `display` transition, so the panel stops painting in
+ * the same commit as the host closes — see the `rendered` style for why.
*
- * Sibling drawers coordinate through a module-level LIFO registry: Escape
- * closes only the top (last-opened) drawer, and non-modal drawers stack
- * last-opened-on-top via registry-assigned z-indexes.
+ * Sibling drawers use the shared layer dismissal stack for topmost-only Escape
+ * handling and the browser top layer's chronological paint order.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/lab/src/Drawer/Drawer.doc.mjs (props table, features, usage)
@@ -43,14 +42,7 @@
* - /apps/storybook/stories/Drawer.stories.tsx (examples and visual coverage)
*/
-import {
- useCallback,
- useEffect,
- useId,
- useRef,
- useState,
- type ReactNode,
-} from 'react';
+import {useCallback, useRef, useState, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
import {
@@ -65,56 +57,21 @@ import {
} from '@astryxdesign/core/theme/tokens.stylex';
import {Icon} from '@astryxdesign/core/Icon';
import {IconButton} from '@astryxdesign/core/IconButton';
-import {useScrollLock} from '@astryxdesign/core/hooks';
+import {
+ useFocusTrap,
+ useMergedRefs,
+ useScrollLock,
+} from '@astryxdesign/core/hooks';
+import {LayerDepthProvider, useLayerDismissal} from '@astryxdesign/core/Layer';
+import {useTranslator} from '@astryxdesign/core/i18n';
import {
composeEventHandlers,
mergeProps,
- mergeRefs,
themeProps,
} from '@astryxdesign/core/utils';
import {overlayPaddingReset} from '@astryxdesign/core/Layout';
import {useDrawerDialogPresence} from './useDrawerDialogPresence';
-// =============================================================================
-// LIFO stacking registry (internal)
-// =============================================================================
-
-// Module-level registry of currently open drawers, in open order (last entry
-// is the top of the stack). SSR-safe: only mutated inside effects. Escape
-// handling consults isTopDrawer() so sibling drawers close innermost-first,
-// and non-modal (show()) drawers get incrementing z-indexes so the
-// last-opened one paints on top; modal drawers rely on the native top
-// layer's chronological stacking instead.
-type DrawerRegistryEntry = {id: string; close: () => void};
-
-// Without the top layer (hasScrim={false} uses show(), not showModal())
-// the panel needs explicit stacking. No z-index token exists in the theme;
-// 1000 matches the app-level drawer convention.
-const NON_MODAL_BASE_Z = 1000;
-
-const openDrawerStack: DrawerRegistryEntry[] = [];
-let registrationCounter = 0;
-
-function registerDrawer(id: string, close: () => void): number {
- openDrawerStack.push({id, close});
- registrationCounter += 1;
- return NON_MODAL_BASE_Z + registrationCounter - 1;
-}
-
-function unregisterDrawer(id: string): void {
- const index = openDrawerStack.findIndex(entry => entry.id === id);
- if (index !== -1) {
- openDrawerStack.splice(index, 1);
- }
- if (openDrawerStack.length === 0) {
- registrationCounter = 0;
- }
-}
-
-function isTopDrawer(id: string): boolean {
- return openDrawerStack[openDrawerStack.length - 1]?.id === id;
-}
-
// =============================================================================
// Styles
// =============================================================================
@@ -181,14 +138,14 @@ const styles = stylex.create({
},
},
// Rendered while the drawer is open AND while it slides out. Applied from
- // React state, not from a discrete `display` transition: `close()` drops the
- // dialog out of the top layer, and any ancestor that establishes a
- // containing block for fixed positioning (transform, filter, container-type,
- // contain) then becomes the origin for the panel's `position: fixed`. A
- // panel still painting after `close()` therefore snaps back INTO the layout
- // and covers the page for the rest of the hold. Owning `display` lets the
- // hide land in the same commit as `close()`, so no frame is ever painted
- // outside the top layer.
+ // React state, not from a discrete `display` transition: leaving either
+ // native top-layer host drops the panel back into its ordinary containing
+ // context, and any ancestor that establishes a containing block for fixed
+ // positioning (transform, filter, container-type, contain) then becomes the
+ // origin for the panel's `position: fixed`. A panel still painting after host
+ // release therefore snaps back INTO the layout and covers the page for the
+ // rest of the hold. Owning `display` lets the hide land in the same commit, so
+ // no frame is ever painted outside the top layer.
//
// Applied via the isOpen/exit state, not :where([open]) — attribute
// selectors have zero specificity and can lose to default styles
@@ -301,9 +258,6 @@ const dynamicStyles = stylex.create({
},
maxWidth: '100dvw',
}),
- stackZ: (z: number) => ({
- zIndex: z,
- }),
});
// =============================================================================
@@ -363,8 +317,8 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {
* Whether to render a modal scrim behind the drawer.
* - `true` (default) — `showModal()`: top layer, focus trap, body scroll
* lock, click-outside-to-close.
- * - `false` — `show()`: non-modal overlay; the page behind stays
- * interactive. Escape still closes while focus is inside the drawer.
+ * - `false` — `showPopover()`: non-modal top-layer overlay; the page behind
+ * stays interactive. Escape still closes through the shared layer stack.
* @default true
*/
hasScrim?: boolean;
@@ -435,15 +389,11 @@ export function Drawer({
...props
}: DrawerProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
- // Registry identity + latest onOpenChange (stable across re-renders so the
- // registration effect doesn't churn on every onOpenChange identity change).
- const drawerId = useId();
- const onOpenChangeRef = useRef(onOpenChange);
- useEffect(() => {
- onOpenChangeRef.current = onOpenChange;
- }, [onOpenChange]);
- // z-index assigned by the registry on open (non-modal stacking only).
- const [stackZ, setStackZ] = useState(NON_MODAL_BASE_Z);
+ const {containerRef: focusTrapRef} = useFocusTrap<HTMLDialogElement>({
+ isActive: isOpen && hasScrim,
+ });
+ const mergedDialogRef = useMergedRefs(ref, dialogRef, focusTrapRef);
+ const t = useTranslator();
// Whether the panel paints: true while open and for the whole slide-out.
const [isRendered, setIsRendered] = useState(isOpen);
@@ -461,48 +411,36 @@ export function Drawer({
setIsRendered,
});
- // LIFO registry membership: register on open, unregister on close or
- // unmount. The returned z-index stacks non-modal siblings in open order.
- useEffect(() => {
- if (!isOpen) {
- return;
- }
- const z = registerDrawer(drawerId, () => onOpenChangeRef.current(false));
- setStackZ(z);
- return () => unregisterDrawer(drawerId);
- }, [isOpen, drawerId]);
+ const handleDismiss = useCallback(() => {
+ onOpenChange(false);
+ }, [onOpenChange]);
+
+ // The shared stack owns Escape delivery across every overlay family. The
+ // provider below gives layers opened from Drawer content a greater logical
+ // depth even when they render elsewhere in the DOM or browser top layer.
+ const {shouldDismissOnCloseRequest} = useLayerDismissal({
+ // The native host stays present through the slide-out. Keep this entry on
+ // the stack until the same commit that hides the host, so a second Escape
+ // cannot fall through to a lower layer during the exit animation.
+ isActive: isRendered,
+ onDismiss: handleDismiss,
+ getContainer: () => dialogRef.current,
+ });
// Lock body scroll while a modal drawer is open (iOS Safari workaround).
useScrollLock(isOpen && hasScrim);
- // Escape closes. The native `cancel` event only fires for showModal();
- // this React keydown handler covers the non-modal show() path too. Only the
- // top of the drawer stack closes, so stacked siblings peel off
- // innermost-first.
- const handleKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLDialogElement>) => {
- if (event.key === 'Escape') {
- event.preventDefault();
- if (isTopDrawer(drawerId)) {
- onOpenChange(false);
- }
- }
- },
- [onOpenChange, drawerId],
- );
-
- // Native cancel event (browser Escape handling) — prevent the browser
- // from closing the dialog directly and route through onOpenChange so the
- // caller's state stays the source of truth. Same top-of-stack rule as
- // the keydown path.
+ // A modal dialog's native cancel event is a platform close request (for
+ // example Android Back). Keep controlled state authoritative and apply the
+ // same top-most/IME rules as the shared Escape listener.
const handleCancel = useCallback(
(event: React.SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
- if (isTopDrawer(drawerId)) {
- onOpenChange(false);
+ if (shouldDismissOnCloseRequest()) {
+ handleDismiss();
}
},
- [onOpenChange, drawerId],
+ [handleDismiss, shouldDismissOnCloseRequest],
);
// Clicks on the ::backdrop target the <dialog> element itself; clicks on
@@ -542,7 +480,7 @@ export function Drawer({
return (
<dialog
- ref={mergeRefs(ref, dialogRef)}
+ ref={mergedDialogRef}
{...mergeProps(
themeProps('drawer', {side: anchoredSide}),
stylex.props(
@@ -552,7 +490,7 @@ export function Drawer({
dynamicStyles.inlineSize(widthValue, mobileWidth),
isRendered && styles.rendered,
isOpen && sideOpenStyle,
- hasScrim ? styles.scrim : dynamicStyles.stackZ(stackZ),
+ hasScrim && styles.scrim,
hasScrim && isOpen && styles.scrimOpen,
xstyle,
),
@@ -560,26 +498,29 @@ export function Drawer({
style,
)}
{...safeProps}
+ popover={hasScrim ? undefined : 'manual'}
aria-label={label}
aria-modal={hasScrim ? 'true' : undefined}
onClick={composeEventHandlers(onClickProp, handleClick)}
- onKeyDown={composeEventHandlers(onKeyDownProp, handleKeyDown)}
+ onKeyDown={onKeyDownProp}
onCancel={handleCancel}>
- {/* Scrollable content area — tabIndex so the dialog's focusing steps
- land on the panel body rather than the first button inside. */}
- <div tabIndex={-1} {...stylex.props(styles.content)}>
- {children}
- </div>
- {hasCloseButton && (
- <div {...stylex.props(styles.controls)}>
- <IconButton
- icon={<Icon icon="close" size="sm" color="inherit" />}
- label="Close"
- variant="ghost"
- onClick={() => onOpenChange(false)}
- />
+ <LayerDepthProvider>
+ {/* Scrollable content area — tabIndex so the dialog's focusing steps
+ land on the panel body rather than the first button inside. */}
+ <div tabIndex={-1} {...stylex.props(styles.content)}>
+ {children}
</div>
- )}
+ {hasCloseButton && (
+ <div {...stylex.props(styles.controls)}>
+ <IconButton
+ icon={<Icon icon="close" size="sm" color="inherit" />}
+ label={t('@astryx.dialog.close')}
+ variant="ghost"
+ onClick={handleDismiss}
+ />
+ </div>
+ )}
+ </LayerDepthProvider>
</dialog>
);
}
diff --git a/packages/lab/src/Drawer/useDrawerDialogPresence.ts b/packages/lab/src/Drawer/useDrawerDialogPresence.ts
index 5c7c3d5556..78be6d3627 100644
--- a/packages/lab/src/Drawer/useDrawerDialogPresence.ts
+++ b/packages/lab/src/Drawer/useDrawerDialogPresence.ts
@@ -5,18 +5,19 @@
/**
* @file useDrawerDialogPresence.ts
* @input Controlled open state, modal mode, dialog ref, and rendered-state setter
- * @output Coordinates native dialog presence, exit timing, focus restoration, and unmount cleanup
+ * @output Coordinates native top-layer presence, exit timing, focus restoration, and unmount cleanup
* @position Drawer-internal hook; consumed only by Drawer.tsx
*
* The drawer has two independent notions of presence:
* - React's rendered state keeps the panel visible for its CSS exit.
- * - The native <dialog> `open` state keeps it in the top layer.
+ * - Native `showModal()` or `showPopover()` state keeps it in the browser top
+ * layer.
*
* Their close ordering is a browser-visible invariant: the panel must finish
- * its exit, then `dialog.close()` and the React hide must happen in the same
- * task. If the hide lands a frame later, a transformed ancestor becomes the
- * containing block for the now-non-top-layer `position: fixed` panel and it
- * paints back inside the page for one frame.
+ * its exit, then leave the active native host and hide in the same task. If the
+ * hide lands a frame later, a transformed ancestor becomes the containing block
+ * for the now-non-top-layer `position: fixed` panel and it paints back inside
+ * the page for one frame.
*
* SYNC: When modified, update:
* - /packages/lab/src/Drawer/Drawer.test.tsx
@@ -49,15 +50,69 @@ type UseDrawerDialogPresenceOptions = {
setIsRendered: Dispatch<SetStateAction<boolean>>;
};
+function isPopoverOpen(dialog: HTMLDialogElement): boolean {
+ try {
+ return dialog.matches(':popover-open');
+ } catch {
+ // jsdom and pre-Popover browsers do not recognize :popover-open.
+ return false;
+ }
+}
+
+function isDrawerHostOpen(
+ dialog: HTMLDialogElement,
+ isModal: boolean,
+): boolean {
+ return isModal ? dialog.open : isPopoverOpen(dialog) || dialog.open;
+}
+
+function showDrawerHost(dialog: HTMLDialogElement, isModal: boolean): void {
+ if (isModal) {
+ dialog.showModal();
+ } else if (typeof dialog.showPopover === 'function') {
+ dialog.showPopover();
+ } else {
+ // Reduced fallback for browsers below the Popover API support floor.
+ dialog.show();
+ }
+}
+
+function dispatchDialogClose(dialog: HTMLDialogElement): void {
+ const EventConstructor = dialog.ownerDocument.defaultView?.Event ?? Event;
+ dialog.dispatchEvent(new EventConstructor('close'));
+}
+
+/**
+ * Leaves the active native host. Returns whether the caller owes a synthetic
+ * `close` dispatch: `dialog.close()` used to power the non-modal path, and
+ * consumers observe its native `close` event through refs/onClose. Popover
+ * dismissal has no equivalent event, so that public DOM contract is preserved
+ * explicitly — but by the caller, not here. Native `close` is queued as a
+ * task, so a consumer's listener always ran after this hook's own focus
+ * restore; the synthetic event must keep that ordering (and fire exactly once
+ * per exit, including the unmount path).
+ */
+function hideDrawerHost(dialog: HTMLDialogElement, isModal: boolean): boolean {
+ if (!isModal && typeof dialog.hidePopover === 'function') {
+ dialog.hidePopover();
+ return true;
+ }
+ if (dialog.open) {
+ dialog.close();
+ }
+ return false;
+}
+
/**
* Coordinates the native dialog and React-rendered presence for Drawer.
*
- * Opening captures the trigger, opens the native dialog, and honours the
- * component's `data-autofocus` contract. Closing waits for the actual
- * transform transition (with a computed-duration backstop), then closes the
- * native dialog and synchronously hides the panel before the browser can paint
- * it outside the top layer. Unmount cleanup closes a dialog left open by React
- * Activity or a removed subtree.
+ * Opening captures the trigger, enters the modal-dialog or manual-popover host,
+ * and honours the component's `data-autofocus` contract. Closing waits for the
+ * actual transform transition (with a computed-duration backstop), then leaves
+ * the native host and synchronously hides the panel before the browser can paint
+ * it outside the top layer, restores focus to the captured trigger, and only
+ * then dispatches the popover host's synthetic `close`. Unmount cleanup closes
+ * a host left open by React Activity or a removed subtree.
*/
export function useDrawerDialogPresence({
dialogRef,
@@ -75,28 +130,24 @@ export function useDrawerDialogPresence({
}
if (isOpen) {
- if (!dialog.open) {
+ if (!isDrawerHostOpen(dialog, isModal)) {
triggerElementRef.current =
document.activeElement as HTMLElement | null;
- if (isModal) {
- dialog.showModal();
- } else {
- dialog.show();
- }
- // React's autoFocus calls .focus() during commit, before the dialog is
- // shown, so it silently fails — honour data-autofocus instead (same
+ showDrawerHost(dialog, isModal);
+ // React's autoFocus calls .focus() during commit, before the native host
+ // is visible, so it silently fails — honour data-autofocus instead (same
// contract as Dialog).
dialog.querySelector<HTMLElement>('[data-autofocus]')?.focus();
}
return;
}
- if (!dialog.open) {
+ if (!isDrawerHostOpen(dialog, isModal)) {
return;
}
return waitForDrawerExit(dialog, () => {
- dialog.close();
+ const owesCloseEvent = hideDrawerHost(dialog, isModal);
// flushSync, not a plain setState: React's default scheduling can land
// the commit after the next paint, and that one frame is exactly the
// bug — the panel paints outside the top layer. Both happen in this
@@ -104,27 +155,37 @@ export function useDrawerDialogPresence({
flushSync(() => {
setIsRendered(false);
});
- // Return focus after close(): a modal dialog makes the rest of the
- // document inert, so focusing the trigger before close() silently fails.
+ // Return focus after leaving the native host: a modal dialog makes the
+ // rest of the document inert, so focusing earlier silently fails.
triggerElementRef.current?.focus();
triggerElementRef.current = null;
+ // The synthetic popover close fires after the focus restore above,
+ // mirroring the task-queued native event: a consumer close listener
+ // that retargets focus (master-detail row switching) gets the last word.
+ if (owesCloseEvent) {
+ dispatchDialogClose(dialog);
+ }
});
}, [dialogRef, isModal, isOpen, setIsRendered]);
- // Close the native dialog on unmount if it is still open. When the drawer is
- // mounted inside an <Activity> that flips to mode="hidden", React runs effect
- // cleanups (with stale isOpen) instead of re-running the effect with
- // isOpen=false. Leaving `open` set would skip showModal() on the next open.
+ // Leave the active native host on unmount. When the drawer is mounted inside
+ // an <Activity> that flips to mode="hidden", React runs effect cleanups (with
+ // stale isOpen) instead of re-running the effect with isOpen=false. Leaving
+ // the host active would strand the top-layer surface and skip the next open.
// This is deliberately separate from the open/close effect: putting it in
// that cleanup would cut off every delayed slide-out.
useEffect(() => {
const dialog = dialogRef.current;
return () => {
- if (dialog?.open) {
- dialog.close();
+ if (dialog && isDrawerHostOpen(dialog, isModal)) {
+ if (hideDrawerHost(dialog, isModal)) {
+ // No focus restore on this path — the drawer is being torn down, so
+ // the owed synthetic close fires immediately (still exactly once).
+ dispatchDialogClose(dialog);
+ }
}
};
- }, [dialogRef]);
+ }, [dialogRef, isModal]);
}
/**
@@ -207,7 +268,7 @@ function readTransformTransitionMs(element: HTMLElement): number | null {
}, 0);
}
-function parseTimes(value: string): Array<number | null> {
+function parseTimes(value: string): (number | null)[] {
return value.split(',').map(part => {
const trimmed = part.trim();
const time = Number.parseFloat(trimmed);