An open source design system that's fully customizable and agent ready
TypeScript
fix(Drawer): a non-modal drawer that unmounts while open returns focus to its opener (#9672)
Cindy Zhangb1a6f16c68dc
diff --git a/.changeset/drawer-unmount-returns-focus.md b/.changeset/drawer-unmount-returns-focus.mdnew file mode 100644index 0000000000..5f21611603--- /dev/null+++ b/.changeset/drawer-unmount-returns-focus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Drawer`: a non-modal drawer (`hasScrim={false}`) that unmounts while it is open, for example one rendered only while open (`{isEditing && <Drawer isOpen …>}`) or removed with the rest of a view, now returns focus to the control that opened it instead of dropping it to the page. A modal drawer already did.++@cixzhang @duytbpdiff --git a/apps/storybook/stories/Drawer.stories.tsx b/apps/storybook/stories/Drawer.stories.tsxindex 4ed93cdad0..cb590553c3 100644--- a/apps/storybook/stories/Drawer.stories.tsx+++ b/apps/storybook/stories/Drawer.stories.tsx@@ -527,6 +527,37 @@ export const Scrim: Story = {},};+/**+ * A drawer rendered only while open: Save removes it without a close. Focus+ * goes back to the button that opened it, as a close returns it.+ */+export const UnmountWhileOpen: Story = {+ render: () => {+ const [isEditing, setIsEditing] = useState(false);+ return (+ <>+ <Button label="Edit row" onClick={() => setIsEditing(true)} />+ {isEditing ? (+ <Drawer+ isOpen+ onOpenChange={setIsEditing}+ label="Edit row"+ hasScrim={false}>+ <Section padding={4}>+ <VStack gap={3}>+ <Text type="body">+ This drawer renders only while open. Save removes it.+ </Text>+ <Button label="Save" onClick={() => setIsEditing(false)} />+ </VStack>+ </Section>+ </Drawer>+ ) : null}+ </>+ );+ },+};+/*** `purpose` matches Dialog. `info` (default) closes on Escape and a scrim* click; `form` ignores the scrim click so a stray click cannot discard input;diff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.mdindex 6c98f898a3..79ba72f050 100644--- a/docs/specs/components/Drawer/Drawer.spec.md+++ b/docs/specs/components/Drawer/Drawer.spec.md@@ -160,28 +160,28 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.## Behavioral and layout contract-| ID | Invariant | Basis |-| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |-| 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 |-| 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 |-| 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 |-| FR4 | Visibility through Drawer-owned behavior MUST follow `isOpen`, from the render after hydration on (FR17). Uncanceled Escape routed by the shared stack and uncanceled modal-backdrop activation request `false` when `purpose` allows (FR15) and the press closes no layer open above the drawer (FR6), and a `DrawerHeader` close action requests `false` through the callback it is given; 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 |-| FR5 | At open time, `hasScrim={true}` MUST select native `showModal()` with `aria-modal`, a focus trap, page scroll locking, and a visible backdrop; under the lock, pull-to-refresh and the page's bounce stop, because a scroll lock under a modal holds the page (`spec:AST-094` FR19), as behind a UIKit modal presentation; `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 |-| FR6 | An uncanceled press on the modal backdrop that starts and ends there (`target === currentTarget` for the pointer-down, the pointer-up, and the click, while live `hasScrim` is true; `family:overlay-dismissal` FR10) MUST request close when `purpose` is `info`, unless the press light-dismisses a layer open above the drawer, which consumes it (`family:overlay-dismissal` FR11), and MUST NOT for `form` or `required`; a press that crosses the drawer's edge either way MUST NOT 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; `useBackdropPress.test.tsx` |-| FR7 | Drawer MUST NOT render a close control of its own. A visible close action is caller composition, normally `DrawerHeader` with `onOpenChange` (`component:DrawerHeader` FR3), which requests `false` through that callback without taking open-state ownership. | DEC-1; close-control suite |-| 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 |-| 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 |-| 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 |-| FR11 | `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, for a modal `required` drawer, `role="alertdialog"`. Implementation gap: a consumer `onCancel` is dropped (Current-state impact). A consumer `onKeyDown` that prevents default cancels shared-stack Escape dismissal for the press. | Current source and focused keyboard tests |-| FR12 | The painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. `DrawerHeader`'s targets are owned by `component:DrawerHeader` FR5. 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 |-| 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 |-| 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` |-| FR15 | `purpose` takes the same values and default as Dialog's prop. `info` (default) lets Escape, platform close, and a modal scrim click request close; `form` lets Escape and platform close request close and ignores scrim clicks; `required` lets none request close, registers with the shared stack as `block` so the request does not reach a lower layer, and exposes a modal drawer as `role="alertdialog"`. Without a scrim, `form` and `info` behave the same. | DEC-1; purpose suite; `family:overlay-dismissal` Escape behavior |-| FR16 | The Content area pads caller content by the drawer's container inset, `--spacing-4` by default as in Dialog, and publishes the applied inset to descendants as a container publisher would; `architecture:container-padding` does not yet admit Drawer as one (Current-state impact). Its block-end edge applies the container inset plus the home-indicator safe area while publishing the inset alone, so a bleed child subtracts only the inset and the safe area survives below it. The root dialog keeps the container-padding reset (FR12). | `architecture:container-padding`; container padding suite |-| FR17 | A Drawer open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Drawer) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 |-| FR18 | While a modal Drawer (`hasScrim`) is open it supplies its `<dialog>` as the passive global outlet, so app-global surfaces such as toasts render inside it, paint above it, and stay operable and reachable by keyboard; it stops supplying when it starts to close, so they return to their place and are not carried out with the exit. Moving them keeps toast entries, timers, and focus handoff (`spec:AST-003` FR18, FR19). A non-modal Drawer supplies no outlet (`architecture:layer-runtime`). | `spec:AST-003` FR18 |-| FR19 | When a non-modal Drawer (`hasScrim={false}`) enters the top layer through `showPopover()`, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the drawer; the drawer supplies no outlet, and its close moves and re-enters nothing (`architecture:layer-runtime`). | `architecture:layer-runtime` |-| FR20 | Drawer's scrim is the theme's `--color-overlay` dim with no blur, on every pointer; under forced colors the drawer keeps a visible edge. | Owner decision, 2026-10-25: the overlay stays theme-controlled and unblurred on every pointer. |+| ID | Invariant | Basis |+| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |+| 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 |+| 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 |+| 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 |+| FR4 | Visibility through Drawer-owned behavior MUST follow `isOpen`, from the render after hydration on (FR17). Uncanceled Escape routed by the shared stack and uncanceled modal-backdrop activation request `false` when `purpose` allows (FR15) and the press closes no layer open above the drawer (FR6), and a `DrawerHeader` close action requests `false` through the callback it is given; 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 |+| FR5 | At open time, `hasScrim={true}` MUST select native `showModal()` with `aria-modal`, a focus trap, page scroll locking, and a visible backdrop; under the lock, pull-to-refresh and the page's bounce stop, because a scroll lock under a modal holds the page (`spec:AST-094` FR19), as behind a UIKit modal presentation; `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 |+| FR6 | An uncanceled press on the modal backdrop that starts and ends there (`target === currentTarget` for the pointer-down, the pointer-up, and the click, while live `hasScrim` is true; `family:overlay-dismissal` FR10) MUST request close when `purpose` is `info`, unless the press light-dismisses a layer open above the drawer, which consumes it (`family:overlay-dismissal` FR11), and MUST NOT for `form` or `required`; a press that crosses the drawer's edge either way MUST NOT 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; `useBackdropPress.test.tsx` |+| FR7 | Drawer MUST NOT render a close control of its own. A visible close action is caller composition, normally `DrawerHeader` with `onOpenChange` (`component:DrawerHeader` FR3), which requests `false` through that callback without taking open-state ownership. | DEC-1; close-control suite |+| 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. When an open Drawer unmounts, it MUST return focus to the captured element if focus would otherwise be lost (left on the page body or on a node that left the document); a development-only simulated unmount is not a removal. | Current presence hook and focus tests |+| 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 |+| 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 |+| FR11 | `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, for a modal `required` drawer, `role="alertdialog"`. Implementation gap: a consumer `onCancel` is dropped (Current-state impact). A consumer `onKeyDown` that prevents default cancels shared-stack Escape dismissal for the press. | Current source and focused keyboard tests |+| FR12 | The painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. `DrawerHeader`'s targets are owned by `component:DrawerHeader` FR5. 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 |+| 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 |+| 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` |+| FR15 | `purpose` takes the same values and default as Dialog's prop. `info` (default) lets Escape, platform close, and a modal scrim click request close; `form` lets Escape and platform close request close and ignores scrim clicks; `required` lets none request close, registers with the shared stack as `block` so the request does not reach a lower layer, and exposes a modal drawer as `role="alertdialog"`. Without a scrim, `form` and `info` behave the same. | DEC-1; purpose suite; `family:overlay-dismissal` Escape behavior |+| FR16 | The Content area pads caller content by the drawer's container inset, `--spacing-4` by default as in Dialog, and publishes the applied inset to descendants as a container publisher would; `architecture:container-padding` does not yet admit Drawer as one (Current-state impact). Its block-end edge applies the container inset plus the home-indicator safe area while publishing the inset alone, so a bleed child subtracts only the inset and the safe area survives below it. The root dialog keeps the container-padding reset (FR12). | `architecture:container-padding`; container padding suite |+| FR17 | A Drawer open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Drawer) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 |+| FR18 | While a modal Drawer (`hasScrim`) is open it supplies its `<dialog>` as the passive global outlet, so app-global surfaces such as toasts render inside it, paint above it, and stay operable and reachable by keyboard; it stops supplying when it starts to close, so they return to their place and are not carried out with the exit. Moving them keeps toast entries, timers, and focus handoff (`spec:AST-003` FR18, FR19). A non-modal Drawer supplies no outlet (`architecture:layer-runtime`). | `spec:AST-003` FR18 |+| FR19 | When a non-modal Drawer (`hasScrim={false}`) enters the top layer through `showPopover()`, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the drawer; the drawer supplies no outlet, and its close moves and re-enters nothing (`architecture:layer-runtime`). | `architecture:layer-runtime` |+| FR20 | Drawer's scrim is the theme's `--color-overlay` dim with no blur, on every pointer; under forced colors the drawer keeps a visible edge. | Owner decision, 2026-10-25: the overlay stays theme-controlled and unblurred on every pointer. |### Allowed variation@@ -319,22 +319,23 @@ block is optional during migration, so the map is deferred.## 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, 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` |-| FR15 | `Drawer.test.tsx` purpose suite | `info`, `form`, `required`; modal and non-modal; a sibling behind a required drawer | A `form` drawer closes on a scrim click, a `required` drawer closes or lets Escape reach the drawer behind it, or its role semantics drift. | `audit:Drawer/behavior` |-| 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` |-| FR16 | `Drawer.test.tsx` container padding suites; `defineTheme.test.ts` drawer mapping; browser evidence | default, `padding` prop, theme `padding`, lone padded Section child, Layout composition | The published inset differs from the applied padding, the default drawer changes geometry, or the block-end safe area is lost or double-subtracted. | `audit:Drawer/theming` |-| AR6 | `DrawerDirection.test.tsx` DOM-direction and closed/entry parity suites plus exact-head Storybook RTL evidence | start/end; self-applied, inherited, and nested opposite `dir`; closed and opening transforms | Any effective DOM direction or local override moves the panel from a different edge than its logical placement, or closed and opening transforms diverge. | `audit:Drawer/accessibility` |-| FR17 | `Drawer.ssr.test.tsx` | Open on the server; hydration; a closed Drawer's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:Drawer/accessibility` |-| FR18 | `ToastViewport.modalHost.test.tsx` "ToastViewport above a Drawer" suite; `DrawerToastOutlet.a11y.chromium.spec.ts` (hit testing, click and Tab at desktop and phone widths) | modal drawer opened over a page toast; toast raised from inside the drawer; drawer closing; drawer without a scrim | A toast viewport left outside an open modal drawer, a toast carried out with the closing drawer, a remounted toast row, or a non-modal drawer that takes the viewport fails. | `audit:Drawer/accessibility` |-| FR19 | `ToastViewport.modalHost.test.tsx` "ToastViewport above a Drawer" non-modal case; `DrawerToastOutlet.a11y.chromium.spec.ts` non-modal case | a toast shown before a scrimless drawer opens over its corner; the drawer closing | A toast the scrimless drawer covers, a viewport moved into the drawer, or a re-entry on close fails. | `audit:Drawer/accessibility` |-| FR20 | `modalBackdrop.test.tsx`; `ModalBackdrop.a11y.browser.spec.ts` in Chromium and WebKit | A finger at phone width; a mouse at desktop width; forced colors under either pointer | A `backdrop-filter` on the scrim at either width, or no visible edge in forced colors, fails. | `audit:Drawer/theming` |+| 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` |+| FR8 (unmount) | `Drawer.test.tsx` "Drawer unmounting while open" suite; `DrawerUnmountFocus.a11y.chromium.spec.ts` (click and Enter) | non-modal and modal drawer rendered only while open and removed by its own control; removed with its view; focus moved outside first; StrictMode remount | Focus left on the page body after an open drawer unmounts, focus pulled back from where the user moved it, or a StrictMode remount that moves focus fails. | `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` |+| FR15 | `Drawer.test.tsx` purpose suite | `info`, `form`, `required`; modal and non-modal; a sibling behind a required drawer | A `form` drawer closes on a scrim click, a `required` drawer closes or lets Escape reach the drawer behind it, or its role semantics drift. | `audit:Drawer/behavior` |+| 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` |+| FR16 | `Drawer.test.tsx` container padding suites; `defineTheme.test.ts` drawer mapping; browser evidence | default, `padding` prop, theme `padding`, lone padded Section child, Layout composition | The published inset differs from the applied padding, the default drawer changes geometry, or the block-end safe area is lost or double-subtracted. | `audit:Drawer/theming` |+| AR6 | `DrawerDirection.test.tsx` DOM-direction and closed/entry parity suites plus exact-head Storybook RTL evidence | start/end; self-applied, inherited, and nested opposite `dir`; closed and opening transforms | Any effective DOM direction or local override moves the panel from a different edge than its logical placement, or closed and opening transforms diverge. | `audit:Drawer/accessibility` |+| FR17 | `Drawer.ssr.test.tsx` | Open on the server; hydration; a closed Drawer's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:Drawer/accessibility` |+| FR18 | `ToastViewport.modalHost.test.tsx` "ToastViewport above a Drawer" suite; `DrawerToastOutlet.a11y.chromium.spec.ts` (hit testing, click and Tab at desktop and phone widths) | modal drawer opened over a page toast; toast raised from inside the drawer; drawer closing; drawer without a scrim | A toast viewport left outside an open modal drawer, a toast carried out with the closing drawer, a remounted toast row, or a non-modal drawer that takes the viewport fails. | `audit:Drawer/accessibility` |+| FR19 | `ToastViewport.modalHost.test.tsx` "ToastViewport above a Drawer" non-modal case; `DrawerToastOutlet.a11y.chromium.spec.ts` non-modal case | a toast shown before a scrimless drawer opens over its corner; the drawer closing | A toast the scrimless drawer covers, a viewport moved into the drawer, or a re-entry on close fails. | `audit:Drawer/accessibility` |+| FR20 | `modalBackdrop.test.tsx`; `ModalBackdrop.a11y.browser.spec.ts` in Chromium and WebKit | A finger at phone width; a mouse at desktop width; forced colors under either pointer | A `backdrop-filter` on the scrim at either width, or no visible edge in forced colors, fails. | `audit:Drawer/theming` |Read from source, with no focused test yet:diff --git a/packages/core/src/Drawer/Drawer.test.tsx b/packages/core/src/Drawer/Drawer.test.tsxindex 1fdd708847..2c68c1afae 100644--- a/packages/core/src/Drawer/Drawer.test.tsx+++ b/packages/core/src/Drawer/Drawer.test.tsx@@ -11,7 +11,7 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';-import {createContext, createRef, use, useState} from 'react';+import {StrictMode, createContext, createRef, use, useState} from 'react';import * as stylex from '@stylexjs/stylex';import {Drawer} from './Drawer';import {DrawerHeader} from './DrawerHeader';@@ -1509,3 +1509,123 @@ describe('Drawer focus region: a radio group is one Tab stop', () => {expectRadioGroupStartsTheCycle();});});++// FR8: a drawer that unmounts while open (rendered only while open, or+// removed with the rest of a view) returns focus to the element focused before+// it opened, as a close does.+describe('Drawer unmounting while open', () => {+ // Read at collection, before any test replaces `matches`, so the stand-in+ // below never calls itself.+ const nativeMatches = Element.prototype.matches;++ // A browser hides a popover host when it leaves the document, and a+ // non-modal drawer sets no `open` attribute. The file's stand-ins set+ // `open`, which jsdom keeps after removal.+ beforeEach(() => {+ const showing = new WeakSet<HTMLElement>();+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ showing.add(this);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ showing.delete(this);+ });+ vi.spyOn(HTMLElement.prototype, 'matches').mockImplementation(function (+ this: HTMLElement,+ selector: string,+ ) {+ return selector === ':popover-open'+ ? showing.has(this) && this.isConnected+ : nativeMatches.call(this, selector);+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ function Inspector({+ unmountWith,+ hasScrim,+ }: {+ unmountWith: 'save' | 'view';+ hasScrim: boolean;+ }) {+ const [isEditing, setIsEditing] = useState(false);+ const [showView, setShowView] = useState(true);+ return (+ <>+ <button type="button" onClick={() => setIsEditing(true)}>+ Edit+ </button>+ <button type="button">Elsewhere</button>+ {showView && isEditing ? (+ <Drawer+ isOpen+ onOpenChange={setIsEditing}+ label="Edit row"+ hasScrim={hasScrim}>+ <button+ type="button"+ onClick={() =>+ unmountWith === 'save'+ ? setIsEditing(false)+ : setShowView(false)+ }>+ Save+ </button>+ </Drawer>+ ) : null}+ </>+ );+ }++ function openAndFocusSave(): HTMLElement {+ const edit = screen.getByRole('button', {name: 'Edit'});+ edit.focus();+ fireEvent.click(edit);+ const save = screen.getByRole('button', {name: 'Save'});+ save.focus();+ return edit;+ }++ for (const hasScrim of [false, true]) {+ for (const unmountWith of ['save', 'view'] as const) {+ it(`returns focus to the opener (${hasScrim ? 'modal' : 'non-modal'}, ${unmountWith})`, async () => {+ render(<Inspector unmountWith={unmountWith} hasScrim={hasScrim} />);+ const edit = openAndFocusSave();++ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ await Promise.resolve();++ expect(screen.queryByRole('button', {name: 'Save'})).toBeNull();+ expect(edit).toHaveFocus();+ });+ }+ }++ it('leaves focus where the user moved it before the unmount', async () => {+ render(<Inspector unmountWith="save" hasScrim={false} />);+ openAndFocusSave();+ const save = screen.getByRole('button', {name: 'Save'});+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ elsewhere.focus();++ // The drawer's own control unmounts it while focus is outside.+ fireEvent.click(save);+ await Promise.resolve();++ expect(elsewhere).toHaveFocus();+ });++ it('a StrictMode remount leaves focus inside the open drawer', async () => {+ render(+ <StrictMode>+ <Inspector unmountWith="save" hasScrim={false} />+ </StrictMode>,+ );+ openAndFocusSave();+ await Promise.resolve();++ expect(screen.getByRole('button', {name: 'Save'})).toHaveFocus();+ });+});diff --git a/packages/core/src/Drawer/__tests__/DrawerUnmountFocus.a11y.chromium.spec.ts b/packages/core/src/Drawer/__tests__/DrawerUnmountFocus.a11y.chromium.spec.tsnew file mode 100644index 0000000000..ce1231c263--- /dev/null+++ b/packages/core/src/Drawer/__tests__/DrawerUnmountFocus.a11y.chromium.spec.ts@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/Drawer ^apps/storybook/stories/Drawer++/**+ * @file DrawerUnmountFocus.a11y.chromium.spec.ts+ * @input The built Core/Drawer UnmountWhileOpen story; real Chromium focus,+ * mouse and keyboard input+ * @output Browser evidence that a non-modal Drawer removed while open returns+ * focus to the button that opened it (Drawer FR8)+ * @position Chromium proof for useDrawerDialogPresence's removal path. In a+ * browser, removing the focused drawer drops focus to the page body; jsdom+ * only approximates that.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-drawer--unmount-while-open&viewMode=story`,+ );+ await holdMotionStill(page);+}++test('a click on Save inside the drawer returns focus to Edit row', async ({+ page,+}) => {+ await openStory(page);+ const edit = page.getByRole('button', {name: 'Edit row', exact: true});+ await edit.click();+ const drawer = page.getByRole('dialog', {name: 'Edit row'});+ await expect(drawer).toBeVisible();+ const save = drawer.getByRole('button', {name: 'Save'});+ await save.click();+ await expect(drawer).toHaveCount(0);+ await expect(edit).toBeFocused();+});++test('Enter on Save returns focus to Edit row', async ({page}) => {+ await openStory(page);+ const edit = page.getByRole('button', {name: 'Edit row', exact: true});+ await edit.focus();+ await page.keyboard.press('Enter');+ const drawer = page.getByRole('dialog', {name: 'Edit row'});+ await expect(drawer).toBeVisible();+ await drawer.getByRole('button', {name: 'Save'}).focus();+ await page.keyboard.press('Enter');+ await expect(drawer).toHaveCount(0);+ await expect(edit).toBeFocused();+});diff --git a/packages/core/src/Drawer/useDrawerDialogPresence.ts b/packages/core/src/Drawer/useDrawerDialogPresence.tsindex 43f0e435f1..43fdf58c0e 100644--- a/packages/core/src/Drawer/useDrawerDialogPresence.ts+++ b/packages/core/src/Drawer/useDrawerDialogPresence.ts@@ -5,7 +5,7 @@/*** @file useDrawerDialogPresence.ts* @input Controlled open state, modal mode, dialog ref, and rendered-state setter- * @output Coordinates native top-layer presence, the touch entrance's input hold, exit timing, focus restoration, and unmount cleanup+ * @output Coordinates native top-layer presence, the touch entrance's input hold, exit timing, focus restoration, and unmount cleanup, including focus return after removal while open* @position Drawer-internal hook; consumed only by Drawer.tsx** The drawer has two independent notions of presence:@@ -36,6 +36,7 @@ import {flushSync} from 'react-dom';import {holdEntranceInput} from '../Layer/holdEntranceInput';import {notifyTopLayerEntry} from '../Layer/modalOutlet';import {runPopoverOperation} from '../Layer/popoverOperations';+import {prepareFocusReturnOnRemoval} from '../utils/focusReturn';/** Slack past the computed transition before the backstop gives up waiting. */const EXIT_BACKSTOP_BUFFER_MS = 50;@@ -194,14 +195,19 @@ export function useDrawerDialogPresence({// that cleanup would cut off every delayed slide-out.useEffect(() => {const dialog = dialogRef.current;+ const returnFocusOnRemoval =+ dialog == null ? null : prepareFocusReturnOnRemoval(dialog);return () => {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).+ // The drawer is being torn down, so the owed synthetic close fires+ // immediately (still exactly once).dispatchDialogClose(dialog);}}+ // Removal already hid a popover host, so this runs outside the check+ // above. The trigger is null outside an open cycle.+ returnFocusOnRemoval?.(triggerElementRef.current);};}, [dialogRef, isModal]);}