Skip to content

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

TypeScript

fix(Drawer): stop the panel repainting into the page after close() (#5549)

freddymeta9ebd45fb3264
diff --git a/.github/scripts/modal-close-visibility.js b/.github/scripts/modal-close-visibility.js
index b0e3ce4b05..41718b8c59 100644
--- a/.github/scripts/modal-close-visibility.js
+++ b/.github/scripts/modal-close-visibility.js
@@ -3,21 +3,23 @@
/**
- * @description Asserts a modal <dialog> is still rendered when close() runs
+ * @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 any close() ran at display: none
+ * @output One line per target; exit 1 if a close/render invariant fails
*
- * A modal <dialog> that is `display: none` while still `:modal` blocks every
- * pointer event on the document, and browsers are not required to release that
- * block when close() finally runs — Safari 26.1 did not, leaving a page that
- * looked normal and answered nothing (#4290). The drawer must therefore still
- * be rendered at the moment it is told to close.
+ * Two opposite ordering bugs live at this boundary:
*
- * That ordering only exists in a browser: it is produced by a `display`
- * transition with `allow-discrete`, which jsdom neither runs nor exposes, so
- * the unit suite passes whether or not the invariant holds. Chromium is enough
- * to observe it — the ordering is the bug, and the Safari version it was
- * reported against is not needed to see it go wrong.
+ * 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().
+ *
+ * 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.
*/
const { chromium } = require('playwright');
@@ -40,6 +42,15 @@ const TARGETS = [
story: 'core-mobilenav--default',
openButton: 'Open Navigation',
},
+ {
+ component: 'Drawer',
+ 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.
+ transformAncestor: true,
+ mustBeHiddenAfterClose: true,
+ },
];
const CONTENT_TYPES = {
@@ -86,10 +97,25 @@ function createServer(dir, listenPort) {
// Records the computed `display` of every dialog at the instant it is closed.
function recordCloseDisplay() {
window.__closeDisplays = [];
+ window.__postCloseFrames = [];
const close = HTMLDialogElement.prototype.close;
HTMLDialogElement.prototype.close = function (...args) {
- window.__closeDisplays.push(getComputedStyle(this).display);
- return close.apply(this, 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.
+ requestAnimationFrame(() => {
+ const rect = dialog.getBoundingClientRect();
+ window.__postCloseFrames.push({
+ display: getComputedStyle(dialog).display,
+ open: dialog.open,
+ x: Math.round(rect.x),
+ width: Math.round(rect.width),
+ });
+ });
+ return result;
};
}
@@ -100,6 +126,16 @@ async function probe(page, target) {
{ waitUntil: 'networkidle', timeout: 15000 }
);
+ if (target.transformAncestor) {
+ await page.evaluate(() => {
+ const root = document.querySelector('#storybook-root');
+ if (!(root instanceof HTMLElement)) {
+ throw new Error('Storybook root not found');
+ }
+ root.style.transform = 'translateZ(0)';
+ });
+ }
+
await page.getByRole('button', { name: target.openButton }).click();
await page.waitForFunction(
() => document.querySelector('dialog')?.matches(':modal') === true,
@@ -111,8 +147,16 @@ async function probe(page, target) {
await page.waitForFunction(() => window.__closeDisplays.length > 0, null, {
timeout: 5000,
});
+ if (target.mustBeHiddenAfterClose) {
+ await page.waitForFunction(() => window.__postCloseFrames.length > 0, null, {
+ timeout: 5000,
+ });
+ }
- return page.evaluate(() => window.__closeDisplays);
+ return page.evaluate(() => ({
+ closeDisplays: window.__closeDisplays,
+ postCloseFrames: window.__postCloseFrames,
+ }));
}
async function run() {
@@ -134,16 +178,28 @@ async function run() {
for (const target of TARGETS) {
const page = await context.newPage();
try {
- const displays = await probe(page, target);
- const hidden = displays.filter((d) => d === 'none');
- if (hidden.length > 0) {
+ const { closeDisplays, postCloseFrames } = await probe(page, target);
+ const hiddenAtClose = closeDisplays.filter((d) => d === 'none');
+ const paintedAfterClose = target.mustBeHiddenAfterClose
+ ? postCloseFrames.filter((frame) => frame.display !== 'none')
+ : [];
+
+ if (hiddenAtClose.length > 0) {
+ failures++;
+ console.error(
+ `✗ ${target.component}: close() ran at display: none (${closeDisplays.join(', ')})`
+ );
+ } else if (paintedAfterClose.length > 0) {
failures++;
console.error(
- `✗ ${target.component}: close() ran at display: none (${displays.join(', ')})`
+ `✗ ${target.component}: painted after close() outside the top layer — ${JSON.stringify(paintedAfterClose)}`
);
} else {
+ const postClose = target.mustBeHiddenAfterClose
+ ? '; hidden before the next paint'
+ : '';
console.log(
- `✓ ${target.component}: close() ran at display: ${displays.join(', ')}`
+ `✓ ${target.component}: close() ran at display: ${closeDisplays.join(', ')}${postClose}`
);
}
} catch (e) {
@@ -160,11 +216,11 @@ async function run() {
if (failures > 0) {
console.error(
- `\nFailing: ${failures} modal(s) closed while not rendered — see #4290.`
+ `\nFailing: ${failures} native-dialog close/render ordering check(s) — see #4290 and #5549.`
);
return 1;
}
- console.log('\nAll modals were still rendered when close() ran.');
+ console.log('\nAll native-dialog close/render ordering checks passed.');
return 0;
}
@@ -173,6 +229,6 @@ run()
process.exitCode = code;
})
.catch((e) => {
- console.error('Modal close visibility guard failed:', e);
+ console.error('Native-dialog close visibility guard failed:', e);
process.exit(1);
});
diff --git a/packages/lab/src/Drawer/Drawer.test.tsx b/packages/lab/src/Drawer/Drawer.test.tsx
index 6dfb9d4046..d2d289670b 100644
--- a/packages/lab/src/Drawer/Drawer.test.tsx
+++ b/packages/lab/src/Drawer/Drawer.test.tsx
@@ -255,6 +255,10 @@ describe('Drawer', () => {
fireEvent.click(screen.getByRole('button', {name: 'Close inspector'}));
// Still open while the slide-out transition plays
expect(dialog).toHaveAttribute('open');
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ expect(dialog).toHaveAttribute('open');
act(() => {
vi.advanceTimersByTime(300);
});
@@ -264,6 +268,43 @@ describe('Drawer', () => {
}
});
+ it('closes as soon as the slide-out transition ends', () => {
+ vi.useFakeTimers();
+ try {
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open inspector'}));
+ const dialog = screen.getByRole('dialog', {hidden: true});
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close inspector'}));
+ expect(dialog).toHaveAttribute('open');
+
+ // The transition is authoritative — no need to wait out the backstop.
+ act(() => {
+ fireEvent.transitionEnd(dialog, {propertyName: 'transform'});
+ });
+ expect(dialog).not.toHaveAttribute('open');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps sliding while a transitionend for another property arrives', () => {
+ vi.useFakeTimers();
+ try {
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open inspector'}));
+ const dialog = screen.getByRole('dialog', {hidden: true});
+
+ fireEvent.click(screen.getByRole('button', {name: 'Close inspector'}));
+ act(() => {
+ fireEvent.transitionEnd(dialog, {propertyName: 'opacity'});
+ });
+ expect(dialog).toHaveAttribute('open');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('restores focus to the trigger element on close', () => {
vi.useFakeTimers();
try {
@@ -576,10 +617,43 @@ describe('Drawer', () => {
});
});
+ describe('exit anchoring', () => {
+ it('slides out to the side it opened from, even if the prop flips', () => {
+ // The common consumer shape: `side` is derived from the same state that
+ // drives isOpen, so it reverts to the default the moment the drawer
+ // closes. The panel must still leave by the edge it came in from.
+ function Harness() {
+ const [side, setSide] = useState<'start' | 'end' | null>(null);
+ return (
+ <>
+ <button type="button" onClick={() => setSide('start')}>
+ Open from start
+ </button>
+ <Drawer
+ isOpen={side != null}
+ onOpenChange={isOpen => !isOpen && setSide(null)}
+ label="Filters"
+ side={side ?? 'end'}>
+ Content
+ </Drawer>
+ </>
+ );
+ }
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open from start'}));
+ const dialog = screen.getByRole('dialog', {hidden: true});
+ expect(dialog).toHaveAttribute('data-side', 'start');
+
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ // Mid-exit: the live prop is now 'end', the anchor must still be 'start'.
+ expect(dialog).toHaveAttribute('data-side', 'start');
+ });
+ });
+
describe('container padding isolation', () => {
it('resets container padding custom properties on the root dialog element', () => {
render(
- <Drawer isOpen onClose={() => {}} label="Details">
+ <Drawer isOpen onOpenChange={() => {}} label="Details">
Content
</Drawer>,
);
diff --git a/packages/lab/src/Drawer/Drawer.tsx b/packages/lab/src/Drawer/Drawer.tsx
index c189953264..b78b6eb759 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, Icon/IconButton, useScrollLock, BaseProps, mergeProps/mergeRefs, themeProps
+ * @input Uses React, StyleX, theme tokens, Icon/IconButton, useScrollLock/useDrawerDialogPresence, BaseProps, mergeProps/mergeRefs, themeProps
* @output Exports Drawer component and DrawerProps
* @position Lab implementation; consumed by index.ts, tested by Drawer.test.tsx, demonstrated in Storybook
*
@@ -26,10 +26,11 @@
* - `show()` when `hasScrim={false}` — non-modal overlay; the page behind
* stays interactive (e.g. master-detail inspectors).
*
- * Entry animation uses `@starting-style` + `transition-behavior:
- * allow-discrete` (see CLAUDE.md dialog-entry pattern); exit slides out
- * before a delayed `dialog.close()` releases the top layer and restores
- * focus to the element that opened the drawer.
+ * 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.
*
* Sibling drawers coordinate through a module-level LIFO registry: Escape
* closes only the top (last-opened) drawer, and non-modal drawers stack
@@ -70,6 +71,7 @@ import {
themeProps,
} from '@astryxdesign/core/utils';
import {overlayPaddingReset} from '@astryxdesign/core/Layout';
+import {useDrawerDialogPresence} from './useDrawerDialogPresence';
// =============================================================================
// LIFO stacking registry (internal)
@@ -149,22 +151,30 @@ const styles = stylex.create({
insetBlockStart: 0,
insetBlockEnd: 0,
height: '100dvh',
- // Closed state. `display` participates in the transition with
- // allow-discrete so it flips to none only after the slide-out finishes
- // (@starting-style covers the none -> flex entry).
+ // Closed state. `display` is owned by React (see `rendered`), not by a
+ // discrete `display` transition, so only `transform` animates here.
display: 'none',
- transitionProperty: 'transform, display',
+ transitionProperty: 'transform',
transitionDuration: durationVars['--duration-medium'],
transitionTimingFunction: easeVars['--ease-standard'],
- transitionBehavior: 'allow-discrete',
'@media (prefers-reduced-motion: reduce)': {
transitionDuration: '0.01s',
},
},
- // Open state applied via isOpen prop, not :where([open]) — attribute
+ // 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.
+ //
+ // Applied via the isOpen/exit state, not :where([open]) — attribute
// selectors have zero specificity and can lose to default styles
// depending on CSS source order (same rationale as Dialog/MobileNav).
- open: {
+ rendered: {
display: 'flex',
},
// start/end transforms flip under RTL so the panel always slides in from
@@ -406,9 +416,6 @@ export function Drawer({
...props
}: DrawerProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
- const closeTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
- // Element focused when the drawer opened — restored on close.
- const triggerElementRef = useRef<HTMLElement | null>(null);
// Registry identity + latest onOpenChange (stable across re-renders so the
// registration effect doesn't churn on every onOpenChange identity change).
const drawerId = useId();
@@ -418,78 +425,22 @@ export function Drawer({
}, [onOpenChange]);
// z-index assigned by the registry on open (non-modal stacking only).
const [stackZ, setStackZ] = useState(NON_MODAL_BASE_Z);
+ // Whether the panel paints: true while open and for the whole slide-out.
+ const [isRendered, setIsRendered] = useState(isOpen);
+
+ // Adjusted during render, not in an effect: the panel has to be rendered in
+ // the same commit that targets the open transform, or @starting-style has
+ // nothing to animate from.
+ if (isOpen && !isRendered) {
+ setIsRendered(true);
+ }
- // Open/close the native dialog. close() is delayed so the slide-out
- // transition can play; focus restore happens after close() because a
- // modal dialog makes the rest of the document inert (focus() on the
- // trigger would silently fail while the dialog is still open).
- useEffect(() => {
- const dialog = dialogRef.current;
- if (!dialog) {
- return;
- }
-
- if (closeTimeoutRef.current) {
- clearTimeout(closeTimeoutRef.current);
- closeTimeoutRef.current = null;
- }
-
- if (isOpen) {
- if (!dialog.open) {
- triggerElementRef.current =
- document.activeElement as HTMLElement | null;
- if (hasScrim) {
- dialog.showModal();
- } else {
- dialog.show();
- }
- // React's autoFocus calls .focus() during commit, before the dialog
- // is shown, so it silently fails — honor data-autofocus instead
- // (same contract as Dialog).
- const autofocusTarget =
- dialog.querySelector<HTMLElement>('[data-autofocus]');
- if (autofocusTarget) {
- autofocusTarget.focus();
- }
- }
- } else if (dialog.open) {
- const duration = window.matchMedia('(prefers-reduced-motion: reduce)')
- .matches
- ? 10
- : 250;
- closeTimeoutRef.current = setTimeout(() => {
- dialog.close();
- // Return focus to the element that opened the drawer.
- triggerElementRef.current?.focus();
- triggerElementRef.current = null;
- }, duration);
- }
-
- return () => {
- if (closeTimeoutRef.current) {
- clearTimeout(closeTimeoutRef.current);
- closeTimeoutRef.current = null;
- }
- };
- }, [isOpen, hasScrim]);
-
- // Close the native dialog on unmount if it's still open. When the drawer
- // is mounted inside an <Activity> that flips to mode="hidden", React runs
- // effect cleanups (with a stale isOpen) instead of re-running the effect
- // with isOpen=false — leaving the <dialog> `open` would skip showModal()
- // on the next open and the drawer could never be re-opened (see
- // MobileNavReopen.test.tsx for the original repro). This must be a
- // separate unmount-only effect: putting it in the open/close effect above
- // would close the dialog on every isOpen flip and cut off the delayed
- // slide-out close.
- useEffect(() => {
- const dialog = dialogRef.current;
- return () => {
- if (dialog?.open) {
- dialog.close();
- }
- };
- }, []);
+ useDrawerDialogPresence({
+ dialogRef,
+ isOpen,
+ isModal: hasScrim,
+ setIsRendered,
+ });
// LIFO registry membership: register on open, unregister on close or
// unmount. The returned z-index stacks non-modal siblings in open order.
@@ -551,8 +502,21 @@ export function Drawer({
? MOBILE_WIDTH_FULL
: `min(${widthValue}, calc(100dvw - ${MOBILE_PAGE_REVEAL}px))`;
- const sideStyle = side === 'start' ? styles.start : styles.end;
- const sideOpenStyle = side === 'start' ? styles.startOpen : styles.endOpen;
+ // The side the panel is ANCHORED to, which is the side it must slide back
+ // out to. Latched at open, because a consumer commonly derives `side` from
+ // the same state that drives `isOpen` (`side={selected?.side ?? 'end'}`):
+ // that state clears on close, so the live prop flips mid-exit and the panel
+ // teleports to the other edge and slides out the wrong way. Children stay
+ // mounted for the exit for the same reason; so does the anchor.
+ const exitSideRef = useRef(side);
+ if (isOpen) {
+ exitSideRef.current = side;
+ }
+ const anchoredSide = isOpen ? side : exitSideRef.current;
+
+ const sideStyle = anchoredSide === 'start' ? styles.start : styles.end;
+ const sideOpenStyle =
+ anchoredSide === 'start' ? styles.startOpen : styles.endOpen;
// Filter out native `open` to prevent InvalidStateError when passed
const {open: _open, ...safeProps} = props as Record<string, unknown>;
@@ -561,13 +525,13 @@ export function Drawer({
<dialog
ref={mergeRefs(ref, dialogRef)}
{...mergeProps(
- themeProps('drawer', {side}),
+ themeProps('drawer', {side: anchoredSide}),
stylex.props(
styles.dialog,
overlayPaddingReset.reset,
sideStyle,
dynamicStyles.inlineSize(widthValue, mobileWidth),
- isOpen && styles.open,
+ isRendered && styles.rendered,
isOpen && sideOpenStyle,
hasScrim ? styles.scrim : dynamicStyles.stackZ(stackZ),
hasScrim && isOpen && styles.scrimOpen,
diff --git a/packages/lab/src/Drawer/useDrawerDialogPresence.ts b/packages/lab/src/Drawer/useDrawerDialogPresence.ts
new file mode 100644
index 0000000000..5c7c3d5556
--- /dev/null
+++ b/packages/lab/src/Drawer/useDrawerDialogPresence.ts
@@ -0,0 +1,222 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @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
+ * @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.
+ *
+ * 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.
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/Drawer/Drawer.test.tsx
+ * - /.github/scripts/modal-close-visibility.js
+ */
+
+import {
+ useEffect,
+ useRef,
+ type Dispatch,
+ type RefObject,
+ type SetStateAction,
+} from 'react';
+import {flushSync} from 'react-dom';
+
+/** Slack past the computed transition before the backstop gives up waiting. */
+const EXIT_BACKSTOP_BUFFER_MS = 50;
+
+/**
+ * Hold used when the transition duration cannot be read — an unresolved
+ * `var()` outside a real browser. Picking a fixed number would otherwise make
+ * an assumption about the consumer's theme.
+ */
+const EXIT_FALLBACK_MS = 250;
+
+type UseDrawerDialogPresenceOptions = {
+ dialogRef: RefObject<HTMLDialogElement | null>;
+ isOpen: boolean;
+ isModal: boolean;
+ setIsRendered: Dispatch<SetStateAction<boolean>>;
+};
+
+/**
+ * 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.
+ */
+export function useDrawerDialogPresence({
+ dialogRef,
+ isOpen,
+ isModal,
+ setIsRendered,
+}: UseDrawerDialogPresenceOptions): void {
+ // Element focused when the drawer opened — restored on close.
+ const triggerElementRef = useRef<HTMLElement | null>(null);
+
+ useEffect(() => {
+ const dialog = dialogRef.current;
+ if (!dialog) {
+ return;
+ }
+
+ if (isOpen) {
+ if (!dialog.open) {
+ 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
+ // contract as Dialog).
+ dialog.querySelector<HTMLElement>('[data-autofocus]')?.focus();
+ }
+ return;
+ }
+
+ if (!dialog.open) {
+ return;
+ }
+
+ return waitForDrawerExit(dialog, () => {
+ dialog.close();
+ // 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
+ // task, so the browser never gets to paint between them.
+ 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.
+ triggerElementRef.current?.focus();
+ triggerElementRef.current = null;
+ });
+ }, [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.
+ // 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();
+ }
+ };
+ }, [dialogRef]);
+}
+
+/**
+ * Wait for the panel's transform transition, with a computed-duration
+ * backstop. Mirrors BottomSheetPanel.waitForTransition: the native event is
+ * authoritative, and the timeout only prevents a lost event from stranding an
+ * open dialog.
+ */
+function waitForDrawerExit(
+ element: HTMLDialogElement,
+ complete: () => void,
+): () => void {
+ let done = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ const finish = () => {
+ if (done) {
+ return;
+ }
+ done = true;
+ if (timer != null) {
+ clearTimeout(timer);
+ }
+ element.removeEventListener('transitionend', handleTransitionEnd);
+ element.removeEventListener('transitioncancel', handleTransitionEnd);
+ complete();
+ };
+
+ const handleTransitionEnd = (event: TransitionEvent) => {
+ if (event.target === element && event.propertyName === 'transform') {
+ finish();
+ }
+ };
+
+ element.addEventListener('transitionend', handleTransitionEnd);
+ element.addEventListener('transitioncancel', handleTransitionEnd);
+
+ const transitionMs = readTransformTransitionMs(element);
+ timer = setTimeout(
+ finish,
+ (transitionMs ?? EXIT_FALLBACK_MS) + EXIT_BACKSTOP_BUFFER_MS,
+ );
+
+ return () => {
+ done = true;
+ if (timer != null) {
+ clearTimeout(timer);
+ }
+ element.removeEventListener('transitionend', handleTransitionEnd);
+ element.removeEventListener('transitioncancel', handleTransitionEnd);
+ };
+}
+
+/** Read the transform transition's duration + delay from computed CSS. */
+function readTransformTransitionMs(element: HTMLElement): number | null {
+ const computed = window.getComputedStyle(element);
+ const properties = computed.transitionProperty
+ .split(',')
+ .map(value => value.trim());
+ const durations = parseTimes(computed.transitionDuration);
+ const delays = parseTimes(computed.transitionDelay);
+
+ if (
+ properties.length === 0 ||
+ durations.length === 0 ||
+ delays.length === 0 ||
+ durations.includes(null) ||
+ delays.includes(null)
+ ) {
+ return null;
+ }
+
+ return properties.reduce((longest, property, index) => {
+ if (property !== 'transform' && property !== 'all') {
+ return longest;
+ }
+ const duration = durations[index % durations.length];
+ const delay = delays[index % delays.length];
+ return Math.max(longest, (duration ?? 0) + (delay ?? 0));
+ }, 0);
+}
+
+function parseTimes(value: string): Array<number | null> {
+ return value.split(',').map(part => {
+ const trimmed = part.trim();
+ const time = Number.parseFloat(trimmed);
+ if (!Number.isFinite(time)) {
+ return null;
+ }
+ if (trimmed.endsWith('ms')) {
+ return time;
+ }
+ return trimmed.endsWith('s') ? time * 1000 : null;
+ });
+}