Skip to content

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

TypeScript

feat(lab): align Drawer dismissal and close control with Dialog (#6877)

Xinzi Zhou06c8fa316553
diff --git a/apps/storybook/stories/Drawer.stories.tsx b/apps/storybook/stories/Drawer.stories.tsx
index 1da908a44e..8fe7dcdd09 100644
--- a/apps/storybook/stories/Drawer.stories.tsx
+++ b/apps/storybook/stories/Drawer.stories.tsx
@@ -2,10 +2,9 @@
import type {Meta, StoryObj} from '@storybook/react';
import {useState} from 'react';
-import {Drawer} from '@astryxdesign/lab';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
import {Button} from '@astryxdesign/core/Button';
import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
-import {Divider} from '@astryxdesign/core/Divider';
import {Heading} from '@astryxdesign/core/Heading';
import {Section} from '@astryxdesign/core/Section';
import {VStack, HStack} from '@astryxdesign/core/Stack';
@@ -64,15 +63,14 @@ export const Showcase: Story = {
onOpenChange={setIsOpen}
label="Deployment details"
width={400}>
+ <DrawerHeader
+ title="web-prod-04"
+ subtitle="us-east-1, deployed 12 min ago"
+ onOpenChange={setIsOpen}
+ hasDivider
+ />
<Section padding={4}>
<VStack gap={4}>
- <VStack gap={1}>
- <Heading level={3}>web-prod-04</Heading>
- <Text type="supporting" color="secondary">
- us-east-1, deployed 12 min ago
- </Text>
- </VStack>
- <Divider />
<VStack gap={2}>
<Text type="label">Status</Text>
<Text type="body">
@@ -413,19 +411,76 @@ export const Scrim: Story = {
isOpen={openWithout}
onOpenChange={setOpenWithout}
label="Non-modal details"
- hasScrim={false}
- hasCloseButton>
+ hasScrim={false}>
+ {/* No scrim to click, so the header's close button is the visible exit. */}
+ <DrawerHeader title="Non-modal" onOpenChange={setOpenWithout} />
<Section padding={4}>
- <VStack gap={4}>
- <Heading level={3}>Non-modal</Heading>
- <Text type="body">
- No scrim, no focus trap. The page behind keeps working while
- this stays open.
- </Text>
- </VStack>
+ <Text type="body">
+ No scrim, no focus trap. The page behind keeps working while this
+ stays open.
+ </Text>
</Section>
</Drawer>
</>
);
},
};
+
+/**
+ * `purpose` matches Dialog. `info` (default) closes on Escape and a scrim
+ * click; `form` ignores the scrim click so a stray click cannot discard input;
+ * `required` ignores both and is exposed as an `alertdialog`, so its content
+ * owns the way out. Drawer has no close button of its own: `DrawerHeader`
+ * renders one when given `onOpenChange`.
+ */
+export const Purpose: Story = {
+ render: () => {
+ const [purpose, setPurpose] = useState<'info' | 'form' | 'required' | null>(
+ null,
+ );
+ const close = () => setPurpose(null);
+ return (
+ <>
+ <HStack gap={2}>
+ <Button label="info" onClick={() => setPurpose('info')} />
+ <Button label="form" onClick={() => setPurpose('form')} />
+ <Button label="required" onClick={() => setPurpose('required')} />
+ </HStack>
+ <Drawer
+ isOpen={purpose != null}
+ onOpenChange={isOpen => !isOpen && close()}
+ label={`Purpose: ${purpose ?? 'info'}`}
+ purpose={purpose ?? 'info'}>
+ {purpose === 'required' ? (
+ <>
+ <DrawerHeader title="Accept the terms" />
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Text type="body">
+ Escape and the scrim do nothing. Only this button closes the
+ drawer.
+ </Text>
+ <Button label="Accept" data-autofocus onClick={close} />
+ </VStack>
+ </Section>
+ </>
+ ) : (
+ <>
+ <DrawerHeader
+ title={purpose === 'form' ? 'Edit details' : 'Details'}
+ onOpenChange={isOpen => !isOpen && close()}
+ />
+ <Section padding={4}>
+ <Text type="body">
+ {purpose === 'form'
+ ? 'Escape or the close button closes; a scrim click does not.'
+ : 'Escape, a scrim click, or the close button closes.'}
+ </Text>
+ </Section>
+ </>
+ )}
+ </Drawer>
+ </>
+ );
+ },
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index d67812b7fc..3c8eb9980e 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -556,6 +556,11 @@
"path": "components/lab/drawer",
"aliases": []
},
+ {
+ "name": "component-lab-drawer-header",
+ "path": "components/lab/drawer-header",
+ "aliases": []
+ },
{
"name": "component-lab-info-tip",
"path": "components/lab/info-tip",
diff --git a/packages/lab/blocks/DrawerFullWidthMobile.doc.mjs b/packages/lab/blocks/DrawerFullWidthMobile.doc.mjs
index 269d879d8a..8af96825b5 100644
--- a/packages/lab/blocks/DrawerFullWidthMobile.doc.mjs
+++ b/packages/lab/blocks/DrawerFullWidthMobile.doc.mjs
@@ -10,5 +10,5 @@ export default {
exampleFor: 'Drawer',
isReady: true,
aspectRatio: 16 / 9,
- componentsUsed: ['Drawer', 'Button', 'Section', 'VStack', 'Heading', 'Text'],
+ componentsUsed: ['Drawer', 'Button', 'Section', 'DrawerHeader', 'Text'],
};
diff --git a/packages/lab/blocks/DrawerFullWidthMobile.tsx b/packages/lab/blocks/DrawerFullWidthMobile.tsx
index 8ab7703c3c..ec073e9ff5 100644
--- a/packages/lab/blocks/DrawerFullWidthMobile.tsx
+++ b/packages/lab/blocks/DrawerFullWidthMobile.tsx
@@ -9,11 +9,10 @@
*/
import {useState} from 'react';
-import {Drawer} from '@astryxdesign/lab';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
import {Button} from '@astryxdesign/core/Button';
import {Section} from '@astryxdesign/core/Section';
-import {VStack} from '@astryxdesign/core/Stack';
-import {Heading, Text} from '@astryxdesign/core/Text';
+import {Text} from '@astryxdesign/core/Text';
export default function DrawerFullWidthMobile() {
const [isOpen, setIsOpen] = useState(false);
@@ -27,13 +26,11 @@ export default function DrawerFullWidthMobile() {
label="Wide panel"
width={560}
isFullWidthOnMobile>
+ <DrawerHeader title="Wide panel" onOpenChange={setIsOpen} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Wide panel</Heading>
- <Text type="body">
- A wide panel on desktop, the full viewport width on mobile.
- </Text>
- </VStack>
+ <Text type="body">
+ A wide panel on desktop, the full viewport width on mobile.
+ </Text>
</Section>
</Drawer>
</>
diff --git a/packages/lab/blocks/DrawerMobileReveal.doc.mjs b/packages/lab/blocks/DrawerMobileReveal.doc.mjs
index 1ee305a4ed..008a28c08a 100644
--- a/packages/lab/blocks/DrawerMobileReveal.doc.mjs
+++ b/packages/lab/blocks/DrawerMobileReveal.doc.mjs
@@ -10,5 +10,5 @@ export default {
exampleFor: 'Drawer',
isReady: true,
aspectRatio: 16 / 9,
- componentsUsed: ['Drawer', 'Button', 'Section', 'VStack', 'Heading', 'Text'],
+ componentsUsed: ['Drawer', 'Button', 'Section', 'DrawerHeader', 'Text'],
};
diff --git a/packages/lab/blocks/DrawerMobileReveal.tsx b/packages/lab/blocks/DrawerMobileReveal.tsx
index 47ccd00d07..7f004e303f 100644
--- a/packages/lab/blocks/DrawerMobileReveal.tsx
+++ b/packages/lab/blocks/DrawerMobileReveal.tsx
@@ -9,11 +9,10 @@
*/
import {useState} from 'react';
-import {Drawer} from '@astryxdesign/lab';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
import {Button} from '@astryxdesign/core/Button';
import {Section} from '@astryxdesign/core/Section';
-import {VStack} from '@astryxdesign/core/Stack';
-import {Heading, Text} from '@astryxdesign/core/Text';
+import {Text} from '@astryxdesign/core/Text';
export default function DrawerMobileReveal() {
const [isOpen, setIsOpen] = useState(false);
@@ -26,13 +25,11 @@ export default function DrawerMobileReveal() {
onOpenChange={setIsOpen}
label="Mobile reveal"
width={360}>
+ <DrawerHeader title="Mobile reveal" onOpenChange={setIsOpen} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Mobile reveal</Heading>
- <Text type="body">
- The page remains visible beside the drawer on mobile.
- </Text>
- </VStack>
+ <Text type="body">
+ The page remains visible beside the drawer on mobile.
+ </Text>
</Section>
</Drawer>
</>
diff --git a/packages/lab/blocks/DrawerScrim.doc.mjs b/packages/lab/blocks/DrawerScrim.doc.mjs
index b652b2d420..81e20f931d 100644
--- a/packages/lab/blocks/DrawerScrim.doc.mjs
+++ b/packages/lab/blocks/DrawerScrim.doc.mjs
@@ -15,8 +15,7 @@ export default {
'Button',
'Section',
'HStack',
- 'VStack',
- 'Heading',
+ 'DrawerHeader',
'Text',
],
};
diff --git a/packages/lab/blocks/DrawerScrim.tsx b/packages/lab/blocks/DrawerScrim.tsx
index 6aa79d54a7..338621ed47 100644
--- a/packages/lab/blocks/DrawerScrim.tsx
+++ b/packages/lab/blocks/DrawerScrim.tsx
@@ -9,11 +9,11 @@
*/
import {useState} from 'react';
-import {Drawer} from '@astryxdesign/lab';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
import {Button} from '@astryxdesign/core/Button';
import {Section} from '@astryxdesign/core/Section';
-import {HStack, VStack} from '@astryxdesign/core/Stack';
-import {Heading, Text} from '@astryxdesign/core/Text';
+import {HStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
export default function DrawerScrim() {
const [openModal, setOpenModal] = useState(false);
@@ -32,13 +32,11 @@ export default function DrawerScrim() {
isOpen={openModal}
onOpenChange={setOpenModal}
label="Edit details">
+ <DrawerHeader title="Edit details" onOpenChange={setOpenModal} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Edit details</Heading>
- <Text type="body">
- The scrim blocks the page behind this modal drawer.
- </Text>
- </VStack>
+ <Text type="body">
+ The scrim blocks the page behind this modal drawer.
+ </Text>
</Section>
</Drawer>
<Drawer
@@ -46,13 +44,11 @@ export default function DrawerScrim() {
onOpenChange={setOpenPanel}
label="Inspector"
hasScrim={false}>
+ <DrawerHeader title="Inspector" onOpenChange={setOpenPanel} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Inspector</Heading>
- <Text type="body">
- The page behind this non-modal drawer stays interactive.
- </Text>
- </VStack>
+ <Text type="body">
+ The page behind this non-modal drawer stays interactive.
+ </Text>
</Section>
</Drawer>
</>
diff --git a/packages/lab/blocks/DrawerShowcase.doc.mjs b/packages/lab/blocks/DrawerShowcase.doc.mjs
index 22a902b18b..102054d941 100644
--- a/packages/lab/blocks/DrawerShowcase.doc.mjs
+++ b/packages/lab/blocks/DrawerShowcase.doc.mjs
@@ -6,10 +6,10 @@ export default {
name: 'Basic',
displayName: 'Basic',
description:
- 'Open a modal drawer from a single trigger. The scrim dims the page; Escape, a scrim click, or the built-in close button closes it, and focus returns to the trigger.',
+ 'Open a modal drawer from a single trigger. The scrim dims the page; Escape, a scrim click, or the header close button closes it, and focus returns to the trigger.',
exampleFor: 'Drawer',
isReady: true,
isShowcase: true,
aspectRatio: 16 / 9,
- componentsUsed: ['Drawer', 'Button', 'Section', 'VStack', 'Heading', 'Text'],
+ componentsUsed: ['Drawer', 'Button', 'Section', 'DrawerHeader', 'Text'],
};
diff --git a/packages/lab/blocks/DrawerShowcase.tsx b/packages/lab/blocks/DrawerShowcase.tsx
index cb7dd9281b..3a87d8b744 100644
--- a/packages/lab/blocks/DrawerShowcase.tsx
+++ b/packages/lab/blocks/DrawerShowcase.tsx
@@ -9,11 +9,10 @@
*/
import {useState} from 'react';
-import {Drawer} from '@astryxdesign/lab';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
import {Button} from '@astryxdesign/core/Button';
import {Section} from '@astryxdesign/core/Section';
-import {VStack} from '@astryxdesign/core/Stack';
-import {Heading, Text} from '@astryxdesign/core/Text';
+import {Text} from '@astryxdesign/core/Text';
export default function DrawerShowcase() {
const [isOpen, setIsOpen] = useState(false);
@@ -26,13 +25,11 @@ export default function DrawerShowcase() {
onOpenChange={setIsOpen}
label="Details"
width={360}>
+ <DrawerHeader title="Details" onOpenChange={setIsOpen} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Details</Heading>
- <Text type="body">
- Close with Escape, the scrim, or the close button.
- </Text>
- </VStack>
+ <Text type="body">
+ Close with Escape, the scrim, or the close button.
+ </Text>
</Section>
</Drawer>
</>
diff --git a/packages/lab/blocks/DrawerStart.doc.mjs b/packages/lab/blocks/DrawerStart.doc.mjs
index fc6f40665e..be20dcd7e5 100644
--- a/packages/lab/blocks/DrawerStart.doc.mjs
+++ b/packages/lab/blocks/DrawerStart.doc.mjs
@@ -10,5 +10,5 @@ export default {
exampleFor: 'Drawer',
isReady: true,
aspectRatio: 16 / 9,
- componentsUsed: ['Drawer', 'Button', 'Section', 'VStack', 'Heading', 'Text'],
+ componentsUsed: ['Drawer', 'Button', 'Section', 'DrawerHeader', 'Text'],
};
diff --git a/packages/lab/blocks/DrawerStart.tsx b/packages/lab/blocks/DrawerStart.tsx
index 21bfb93cb9..dcef9ac986 100644
--- a/packages/lab/blocks/DrawerStart.tsx
+++ b/packages/lab/blocks/DrawerStart.tsx
@@ -9,11 +9,10 @@
*/
import {useState} from 'react';
-import {Drawer} from '@astryxdesign/lab';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
import {Button} from '@astryxdesign/core/Button';
import {Section} from '@astryxdesign/core/Section';
-import {VStack} from '@astryxdesign/core/Stack';
-import {Heading, Text} from '@astryxdesign/core/Text';
+import {Text} from '@astryxdesign/core/Text';
export default function DrawerStart() {
const [isOpen, setIsOpen] = useState(false);
@@ -26,13 +25,11 @@ export default function DrawerStart() {
onOpenChange={setIsOpen}
label="Navigation"
side="start">
+ <DrawerHeader title="Navigation" onOpenChange={setIsOpen} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Navigation</Heading>
- <Text type="body">
- The start edge follows the page's writing direction.
- </Text>
- </VStack>
+ <Text type="body">
+ The start edge follows the page's writing direction.
+ </Text>
</Section>
</Drawer>
</>
diff --git a/packages/lab/blocks/DrawerWidths.doc.mjs b/packages/lab/blocks/DrawerWidths.doc.mjs
index 85e017951e..f083c66cb2 100644
--- a/packages/lab/blocks/DrawerWidths.doc.mjs
+++ b/packages/lab/blocks/DrawerWidths.doc.mjs
@@ -15,8 +15,7 @@ export default {
'Button',
'Section',
'HStack',
- 'VStack',
- 'Heading',
+ 'DrawerHeader',
'Text',
],
};
diff --git a/packages/lab/blocks/DrawerWidths.tsx b/packages/lab/blocks/DrawerWidths.tsx
index 0c7e659514..b41c524b6c 100644
--- a/packages/lab/blocks/DrawerWidths.tsx
+++ b/packages/lab/blocks/DrawerWidths.tsx
@@ -9,11 +9,11 @@
*/
import {useState} from 'react';
-import {Drawer} from '@astryxdesign/lab';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
import {Button} from '@astryxdesign/core/Button';
import {Section} from '@astryxdesign/core/Section';
-import {HStack, VStack} from '@astryxdesign/core/Stack';
-import {Heading, Text} from '@astryxdesign/core/Text';
+import {HStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
export default function DrawerWidths() {
const [isOpen, setIsOpen] = useState(false);
@@ -36,13 +36,11 @@ export default function DrawerWidths() {
onOpenChange={setIsOpen}
label="Width budget"
width={width}>
+ <DrawerHeader title="Width budget" onOpenChange={setIsOpen} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Width budget</Heading>
- <Text type="body">
- Width: {typeof width === 'number' ? `${width}px` : width}
- </Text>
- </VStack>
+ <Text type="body">
+ Width: {typeof width === 'number' ? `${width}px` : width}
+ </Text>
</Section>
</Drawer>
</>
diff --git a/packages/lab/src/Drawer/Drawer.doc.mjs b/packages/lab/src/Drawer/Drawer.doc.mjs
index 8e83a8da7a..9bd4d62fda 100644
--- a/packages/lab/src/Drawer/Drawer.doc.mjs
+++ b/packages/lab/src/Drawer/Drawer.doc.mjs
@@ -2,7 +2,7 @@
/**
* @file Drawer.doc.mjs
- * @input Drawer props, panel anatomy, overlay playground config, and story-aligned examples
+ * @input Drawer props, panel anatomy, DrawerHeader composition, overlay playground config, and story-aligned examples
* @output Consumer documentation and examples for Drawer
* @position CLI and docsite metadata; runnable docsite demos live in packages/lab/blocks
*/
@@ -22,10 +22,10 @@ const anatomy = [
'Full-bleed scrollable region that receives children; compose your own header, body, and footer inside it.',
},
{
- name: 'Close button',
+ name: 'Header',
required: false,
description:
- 'Built-in dismissal affordance floating in the top-trailing corner; pass hasCloseButton={false} when the content provides its own.',
+ 'DrawerHeader, composed first in the content area: a title row with optional subtitle and start/end content. Pass it onOpenChange to show a close button, as with DialogHeader.',
},
{
name: 'Scrim',
@@ -82,7 +82,14 @@ export const docs = {
},
},
theming: {
- targets: [{className: 'astryx-drawer', visualProps: ['side']}],
+ targets: [
+ {className: 'astryx-drawer', visualProps: ['side']},
+ {className: 'astryx-drawer-header'},
+ {className: 'astryx-drawer-header-start-content'},
+ {className: 'astryx-drawer-header-title-block'},
+ {className: 'astryx-drawer-header-end-content'},
+ {className: 'astryx-drawer-header-close-icon'},
+ ],
},
description:
'Side panel that floats above page content, using the native <dialog> element. Slides in from the inline start or end edge; full height, never reflows the layout underneath.',
@@ -98,7 +105,7 @@ export const docs = {
name: 'onOpenChange',
type: '(isOpen: boolean) => void',
description:
- 'Called when the drawer requests an open-state change. Escape, scrim click, and the built-in close button call it with false. The caller owns the open state. With sibling drawers open, Escape only closes the last-opened one.',
+ 'Called when the drawer requests an open-state change. Escape and a scrim click call it with false as purpose allows; a DrawerHeader given the same callback calls it from its close button. The caller owns the open state. With sibling drawers open, Escape only closes the last-opened one.',
required: true,
},
{
@@ -140,21 +147,21 @@ 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 the manual Popover API for a non-modal top-layer 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 unless purpose prevents it; 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',
},
{
- name: 'hasCloseButton',
- type: 'boolean',
+ name: 'purpose',
+ type: "'required' | 'form' | 'info'",
description:
- 'Built-in close button in the top-trailing corner. Enabled by default for both modal and non-modal drawers so every overlay has an obvious dismissal affordance.',
- default: 'true',
+ 'Configures implicit dismissal, matching Dialog. info: Escape and a scrim click close. form: Escape closes, a scrim click does not. required: neither closes (Escape is consumed) and a modal drawer is exposed as an alertdialog, so give its content a way out. A non-modal drawer has no scrim, so form and info behave the same.',
+ default: "'info'",
},
],
usage: {
anatomy,
description:
- 'A side panel that floats above page content for inspectors and detail views: the "click a table row, see its details" pattern. Unlike a docked panel it overlays the layout instead of reflowing it. Works on desktop and touch: the width budget applies on desktop and the panel preserves a 56px page reveal below 640px without exceeding the width budget. Escape closes the drawer and focus returns to the element that opened it. Entry/exit slide animation respects prefers-reduced-motion. Stacking contract: sibling drawers stack last-opened on top, Escape closes only the topmost, and closing peels innermost-first; render them as siblings, never nested.\n\nThe content area is full-bleed: compose your own header, body, and footer. A plain recipe is all a drawer needs — Section padding={4} wrapping a VStack with a Heading, body content, and trailing actions; there is no DrawerHeader sub-component. The built-in close button floats above the content in the top-trailing corner, so leave it clearance in a custom header row, or pass hasCloseButton={false} when the content provides its own dismissal. Put data-autofocus on the control that should receive focus on open.\n\nChoosing a surface: use Dialog for a centered decision or short form, Drawer for full-height side detail that keeps the page in sight, BottomSheet for block-axis sheets on touch, and a docked panel (a layout column) when content should reflow the page instead of floating over it.\n\nTheming: the panel is the single stable target (astryx-drawer, with data-side reflecting side). The scrim is the panel\'s native ::backdrop, and the built-in close button is a ghost Button reachable through the astryx-button target.',
+ 'A side panel that floats above page content for inspectors and detail views: the "click a table row, see its details" pattern. Unlike a docked panel it overlays the layout instead of reflowing it. Works on desktop and touch: the width budget applies on desktop and the panel preserves a 56px page reveal below 640px without exceeding the width budget. Escape closes the drawer (unless purpose is required) and focus returns to the element that opened it. Entry/exit slide animation respects prefers-reduced-motion. Stacking contract: sibling drawers stack last-opened on top, Escape closes only the topmost, and closing peels innermost-first; render them as siblings, never nested.\n\nThe content area is full-bleed: compose the header, body, and footer. Start with DrawerHeader, a title row that shows a close button when you pass it onOpenChange, like DialogHeader; follow it with the body, for example Section padding={4}. Drawer renders no close button of its own, so give every drawer a visible way to close, especially a non-modal one, which has no scrim to click. Put data-autofocus on the control that should receive focus on open.\n\nChoosing a surface: use Dialog for a centered decision or short form, Drawer for full-height side detail that keeps the page in sight, BottomSheet for block-axis sheets on touch, and a docked panel (a layout column) when content should reflow the page instead of floating over it.\n\nTheming: the panel is the single stable target (astryx-drawer, with data-side reflecting side), and the scrim is the panel\'s native ::backdrop. DrawerHeader exposes astryx-drawer-header targets for its row, slots, and close icon.',
bestPractices: [
{
guidance: true,
@@ -176,6 +183,16 @@ export const docs = {
description:
'Keep the last-selected item rendered on close: children stay mounted during the exit animation, so nulling content mid-close blanks the panel while it slides out.',
},
+ {
+ guidance: true,
+ description:
+ 'Give every drawer a visible close action, usually DrawerHeader with onOpenChange; a non-modal drawer has no scrim to click.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use purpose="form" when a stray scrim click would discard unsaved input.',
+ },
{
guidance: false,
description:
@@ -210,16 +227,14 @@ export const docs = {
onOpenChange={setIsOpen}
label="Details"
width={360}>
+ <DrawerHeader title="Details" onOpenChange={setIsOpen} />
<Section padding={4}>
- <VStack gap={2}>
- <Heading level={3}>Details</Heading>
- <Text type="body">Close with Escape, the scrim, or the close button.</Text>
- </VStack>
+ <Text type="body">Close with Escape, the scrim, or the close button.</Text>
</Section>
</Drawer>
</>
// Modal by default: the scrim dims the page and focus is trapped. Escape, a
-// scrim click, or the built-in close button closes it, and focus returns to
+// scrim click, or the header's close button closes it, and focus returns to
// the trigger.`,
},
{
@@ -283,12 +298,14 @@ const [openPanel, setOpenPanel] = useState(false);
<Drawer isOpen={openModal} onOpenChange={setOpenModal} label="Edit details">
<EditForm />
</Drawer>
- {/* Non-modal: no scrim, no focus trap; the page behind stays interactive. */}
+ {/* Non-modal: no scrim, no focus trap; the page behind stays interactive.
+ With no scrim to click, the header's close button is the visible exit. */}
<Drawer
isOpen={openPanel}
onOpenChange={setOpenPanel}
label="Details"
hasScrim={false}>
+ <DrawerHeader title="Details" onOpenChange={setOpenPanel} />
<DetailsPanel />
</Drawer>
</>`,
@@ -313,10 +330,10 @@ export const docsZh = {
'不带内边距的可滚动区域,承载 children;页眉、正文、页脚在其中自行组合。',
},
{
- name: 'Close button',
+ name: 'Header',
required: false,
description:
- '内置关闭按钮,悬浮在顶部尾随角;内容自带关闭操作时用 hasCloseButton={false} 移除。',
+ 'DrawerHeader,放在内容区域最前面:包含标题,以及可选的副标题和首尾内容。传入 onOpenChange 即显示关闭按钮,与 DialogHeader 相同。',
},
{
name: 'Scrim',
@@ -326,7 +343,7 @@ export const docsZh = {
},
],
description:
- '浮在页面内容之上的侧边面板,用于检查器和详情视图——"点击表格行查看详情"的模式。与停靠面板不同,它覆盖在布局之上,不会挤压页面。桌面端按 width 设定宽度,宽度小于 640px 时保留 56px 的底层页面,并且不超过 width 上限。按 Escape 关闭抽屉,焦点返回到打开它的元素。滑入/滑出动画遵循 prefers-reduced-motion。堆叠约定:同级抽屉后开的在上层,Escape 只关闭最上层的,关闭顺序由内向外——请以同级方式渲染,切勿嵌套。\n\n内容区域不带内边距:页眉、正文、页脚由你自行组合。一个简单的配方即可——用 Section padding={4} 包裹 VStack,内含 Heading、正文与末尾操作;没有 DrawerHeader 子组件。内置关闭按钮悬浮在顶部尾随角上方,请在自定义页眉行中为它留出空间,或在内容自带关闭操作时传 hasCloseButton={false}。在打开时应获得焦点的控件上加 data-autofocus。\n\n如何选择:居中的决定或短表单用 Dialog;保持页面可见的全高侧边详情用 Drawer;触屏上的块轴面板用 BottomSheet;内容应当把页面挤开重排时用停靠面板(布局分栏),而不是浮层。\n\n主题化:面板是唯一的稳定目标(astryx-drawer,data-side 反映 side 值);遮罩是面板的原生 ::backdrop;内置关闭按钮是 ghost 变体的 Button,可通过 astryx-button 目标定制。',
+ '浮在页面内容之上的侧边面板,用于检查器和详情视图——"点击表格行查看详情"的模式。与停靠面板不同,它覆盖在布局之上,不会挤压页面。桌面端按 width 设定宽度,宽度小于 640px 时保留 56px 的底层页面,并且不超过 width 上限。按 Escape 关闭抽屉(purpose 为 required 时除外),焦点返回到打开它的元素。滑入/滑出动画遵循 prefers-reduced-motion。堆叠约定:同级抽屉后开的在上层,Escape 只关闭最上层的,关闭顺序由内向外——请以同级方式渲染,切勿嵌套。\n\n内容区域不带内边距:页眉、正文、页脚由你自行组合。先放 DrawerHeader——传入 onOpenChange 时显示关闭按钮的标题行,与 DialogHeader 相同;再放正文,例如 Section padding={4}。Drawer 本身不渲染关闭按钮,所以每个抽屉都要提供可见的关闭方式,非模态抽屉尤其如此,因为它没有可点击的遮罩。在打开时应获得焦点的控件上加 data-autofocus。\n\n如何选择:居中的决定或短表单用 Dialog;保持页面可见的全高侧边详情用 Drawer;触屏上的块轴面板用 BottomSheet;内容应当把页面挤开重排时用停靠面板(布局分栏),而不是浮层。\n\n主题化:面板是唯一的稳定目标(astryx-drawer,data-side 反映 side 值),遮罩是面板的原生 ::backdrop。DrawerHeader 为其标题行、插槽和关闭图标提供 astryx-drawer-header 系列目标。',
bestPractices: [
{
guidance: true,
@@ -348,6 +365,15 @@ export const docsZh = {
description:
'关闭时保留最后选中的内容:退出动画期间子内容仍然挂载,中途置空会让面板在滑出时变为空白。',
},
+ {
+ guidance: true,
+ description:
+ '为每个抽屉提供可见的关闭操作,通常是带 onOpenChange 的 DrawerHeader;非模态抽屉没有可点击的遮罩。',
+ },
+ {
+ guidance: true,
+ description: '误点遮罩会丢失未保存的输入时,使用 purpose="form"。',
+ },
{
guidance: false,
description:
@@ -379,7 +405,7 @@ export const docsDense = {
usage: {
anatomy,
description:
- 'Overlay side panel for inspectors and detail views; floats over content, never reflows it. width = desktop budget; 56px page reveal below 640px, capped by width (isFullWidthOnMobile for all of it). Escape closes topmost; focus restores to the opener. Siblings stack last-opened on top; never nest. Slide animation respects prefers-reduced-motion. Compose header/body/footer yourself in the full-bleed scroll area (Section padding={4} + VStack; no DrawerHeader; built-in close button floats top-trailing, hasCloseButton={false} to remove; data-autofocus picks the focus target). Choose: Dialog for centered decisions/short forms, Drawer for full-height side detail, BottomSheet for block-axis sheets, docked layout column to reflow instead of float. Theming: single target astryx-drawer (data-side); scrim is its ::backdrop; close button is a ghost Button (astryx-button).',
+ 'Overlay side panel for inspectors and detail views; floats over content, never reflows it. width = desktop budget; 56px page reveal below 640px, capped by width (isFullWidthOnMobile for all of it). Escape closes topmost (not when purpose=required); focus restores to the opener. Siblings stack last-opened on top; never nest. Slide animation respects prefers-reduced-motion. Compose header/body/footer in the full-bleed scroll area: DrawerHeader first (close button only when given onOpenChange, like DialogHeader), then the body (e.g. Section padding={4}); no built-in close button, so every drawer needs a visible exit; data-autofocus picks the focus target. purpose matches Dialog: info = Escape + scrim click, form = Escape only, required = neither (modal → alertdialog). Choose: Dialog for centered decisions/short forms, Drawer for full-height side detail, BottomSheet for block-axis sheets, docked layout column to reflow instead of float. Theming: single target astryx-drawer (data-side); scrim is its ::backdrop; DrawerHeader has astryx-drawer-header targets.',
bestPractices: [
{
guidance: true,
@@ -400,6 +426,16 @@ export const docsDense = {
description:
'Keep last-selected content rendered on close (children stay mounted during exit).',
},
+ {
+ guidance: true,
+ description:
+ 'Give every drawer a visible close action (DrawerHeader + onOpenChange); non-modal has no scrim.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use purpose="form" when a stray scrim click would lose input.',
+ },
{
guidance: false,
description:
diff --git a/packages/lab/src/Drawer/Drawer.spec.md b/packages/lab/src/Drawer/Drawer.spec.md
index 9f7f77d9d9..713741e351 100644
--- a/packages/lab/src/Drawer/Drawer.spec.md
+++ b/packages/lab/src/Drawer/Drawer.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/lab/src/Drawer/Drawer.test.tsx,
+ packages/lab/src/Drawer/DrawerHeader.test.tsx,
packages/core/src/Layer/useLayerDismissal.test.tsx,
packages/core/src/Layer/layerDismissalFamilies.test.tsx,
.github/scripts/modal-close-visibility.js,
@@ -37,15 +38,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. `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. |
+| Area | Contract |
+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Current Lab surface | Public-API change aligning Drawer with Dialog (DEC-1). At this commit, the experimental `@astryxdesign/lab` root exports `Drawer`, `DrawerProps`, `DrawerHeader`, and `DrawerHeaderProps`. `DrawerProps` extends `BaseProps<HTMLDialogElement>`, separately declares `ref`, requires `isOpen`, `onOpenChange`, `label`, and `children`, accepts `purpose` (`required`, `form`, or `info`; default `info`), and no longer accepts `hasCloseButton`. 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, and `purpose` decides, as in Dialog, whether Escape, platform close, and scrim click request close. Drawer renders no close control of its own; `DrawerHeader` renders one only when given `onOpenChange`. 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 | Drawers no longer paint a floating top-trailing close button; a close button appears in a `DrawerHeader` title row where the caller composes one. `form` drawers ignore scrim clicks, and `required` drawers ignore Escape, platform close, and scrim clicks; a modal `required` drawer is announced as an alert dialog. Layer behavior (shared topmost/IME Escape, top-layer paint order, one dismissal per request, focus return) is unchanged. |
+| Builder impact | Remove `hasCloseButton`. For a visible close action, compose `<DrawerHeader title onOpenChange>` first in the content, as with `DialogHeader`; callers that passed `hasCloseButton={false}` need no change beyond removing the prop. Set `purpose` where Dialog would. 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 | Breaking Lab API change: removes `hasCloseButton` and the built-in close button, adds `purpose` and `DrawerHeader`. Drawer remains experimental in Lab, this record remains `draft`, and its candidate statements require approval. FR13–FR14 record shared-family and top-layer conformance; FR7 and FR15 record the Dialog alignment. |
+| Review checks | Reject regional, docked, or block-axis models; claims that modality and scrim are currently independent; reintroduction of a Drawer-local Escape registry, a page-level z-index band, or a Drawer-owned close button; a dismissal policy that diverges from Dialog's `purpose`; 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–FR15 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.
@@ -56,21 +57,24 @@ 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 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.
+This draft records the viewport-only Lab component after its layer-lifecycle
+hardening and its alignment with Dialog's close control and dismissal policy
+(DEC-1). It introduces no 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: behavioral hardening inside Lab; public props, defaults,
- root element, styling inputs, and controlled ownership remain unchanged.
+- Compatibility class: breaking change inside Lab. `hasCloseButton` and the
+ built-in close button are removed; `purpose` and `DrawerHeader` are added. 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.
-- Migration decision: none.
+- Migration decision: Drawer is unreleased Lab, so no codemod. Callers remove
+ `hasCloseButton` and compose `DrawerHeader` with `onOpenChange` where they
+ relied on the built-in button.
Consumer migration instructions belong in consumer docs and release notes.
@@ -82,57 +86,62 @@ Consumer migration instructions belong in consumer docs and release notes.
entry/exit motion.
- The current presentation input: its value at native open selects `showModal()`
or the manual Popover API host. Changing it while open is unsupported.
-- Drawer-local focus entry/return, built-in close affordance, uncanceled
+- Drawer-local focus entry/return, the `purpose` dismissal policy, uncanceled
backdrop-click handling, and retention of its host through controlled exit
while rendering current caller-owned children.
+- `DrawerHeader`: a title row with optional subtitle and start/end content, and a
+ close action rendered only when `onOpenChange` is passed.
- 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**
-- Caller-provided headers, forms, inspectors, footers, or other content.
+- Caller-provided forms, inspectors, footers, or other content. `DrawerHeader`
+ is optional composition, not required anatomy.
- Block-axis sheets — owned by `component:BottomSheet`.
- Persistent panels that reserve layout space or push page content.
- 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`; Drawer participates through the shared owner.
-- Button painting for the built-in close affordance — delegated to
- `component:Button` through IconButton.
+- Button painting for the `DrawerHeader` close action — delegated to
+ `component:Button`; header row layout is delegated to `LayoutHeader`.
## Public concepts
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 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 |
+| 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 |
+| dismissal purpose | info, form, required | which implicit requests close: `info` allows Escape, platform close, and scrim click; `form` allows Escape and platform close; `required` allows none | all presentations; scrim click applies to modal only | info | `component:Drawer` | experimental Lab contract matching `component:Dialog` | closed type rejects other values |
+| header close action | rendered, absent | whether `DrawerHeader` renders its close button | wherever `DrawerHeader` is composed | absent unless `onOpenChange` is passed | `component:Drawer` | experimental Lab contract | an omitted callback renders no button |
+| 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 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 |
+| 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 and uncanceled modal-backdrop activation request `false` when `purpose` allows (FR15), 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 | 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 when `purpose` is `info`, and MUST NOT for `form` or `required`. 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 | Drawer MUST NOT render a close control of its own. `DrawerHeader` MUST render a close action with an accessible name only when `onOpenChange` is passed and call it with `false` without taking open-state ownership. It renders its title as an h2 and neither moves focus on mount nor names the Drawer. | DEC-1; close-control and `DrawerHeader.test.tsx` suites | Owner decision (DEC-1); pending approval |
+| 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`, `onCancel`, and, for a modal `required` drawer, `role="alertdialog"`. 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. `DrawerHeader` emits `drawer-header`, `drawer-header-start-content`, `drawer-header-title-block`, `drawer-header-end-content`, and `drawer-header-close-icon`, mirroring `DialogHeader`. 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 |
+| FR15 | `purpose` MUST match `component:Dialog`. `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 | Owner decision (DEC-1); pending approval |
### Allowed variation
@@ -145,21 +154,24 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
full-mobile mode uses `100dvw` instead.
- **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.
+- **AV4 — Close control.** Callers choose whether to render a close action,
+ normally `DrawerHeader` with `onOpenChange`, or their own control.
+- **AV6 — Dismissal purpose.** Callers choose `info`, `form`, or `required`.
- **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 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 |
+| 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, header close action, and purpose |
+| 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, header close action, and purpose |
+| Required modal drawer | Escape, platform close, and scrim click do not close; exposed as `alertdialog`; a lower layer does not receive the Escape | caller-provided way out |
+| 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
@@ -198,15 +210,18 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
or whitespace-only value.
- **AR2 — Modal truthfulness.** At open time, `hasScrim={true}` uses native modal
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
+ host and omits `aria-modal`. A modal `required` drawer uses
+ `role="alertdialog"`. 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.
+ registered layer through the shared stack and only when `purpose` allows; a
+ `required` drawer consumes it. 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.
-- **AR5 — Close affordance.** The built-in close action retains an accessible name
+- **AR5 — Close affordance.** Drawer provides no close control of its own. When
+ rendered, the `DrawerHeader` close action keeps its translated accessible name
and Button-owned keyboard/focus behavior in both presentations.
- **AR6 — Direction and motion.** Logical inset placement follows computed
direction; slide-direction mirroring currently requires a `[dir="rtl"]`
@@ -216,18 +231,18 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
## Design relationships
-| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
-| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------ | -------------- | ------------------ |
-| Panel | Paints the full-height side surface and owns edge, width, border, shadow, and motion. | Current source and public docs | Prominent | FR1–FR3, FR9, FR12 |
-| Content region | Provides full-height scrolling for caller-owned inspector content. | Current source and public docs | Prominent | FR4, AV1 |
-| Close button | Supplies the persistent top-trailing dismissal action when enabled. | `component:Button` | Supporting | FR7, AR5 |
-| Modal scrim | At initial modal open, communicates the scrim-backed presentation and provides root-click activation behind the panel. | Current source and public docs | Supporting | FR5, FR6, AR2 |
-| Page reveal | Preserves overlay context on narrow viewports unless full coverage is requested. | Current public docs | Supporting | FR3 |
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | -------------- | ------------------ |
+| Panel | Paints the full-height side surface and owns edge, width, border, shadow, and motion. | Current source and public docs | Prominent | FR1–FR3, FR9, FR12 |
+| Content region | Provides full-height scrolling for caller-owned inspector content. | Current source and public docs | Prominent | FR4, AV1 |
+| Header | `DrawerHeader` supplies the title row and, when given `onOpenChange`, the close action. | `component:Button`, `LayoutHeader` | Supporting | FR7, FR12, AR5 |
+| Modal scrim | At initial modal open, communicates the scrim-backed presentation and provides root-click activation behind the panel. | Current source and public docs | Supporting | FR5, FR6, AR2 |
+| Page reveal | Preserves overlay context on narrow viewports unless full coverage is requested. | Current public docs | Supporting | FR3 |
-The root Panel carries the current `drawer` target and reflects `side`. Consumer
-docs do not yet declare canonical `usage.anatomy`, and no separate Drawer target is
-currently reachable for Content region, Close button, or Modal scrim. This draft
-does not decide future target qualification.
+The root Panel carries the current `drawer` target and reflects `side`, and
+`DrawerHeader` carries its five `drawer-header` targets. No separate Drawer target
+is currently reachable for Content region or Modal scrim. This draft does not
+decide future target qualification.
## Family and system relationships
@@ -253,23 +268,35 @@ does not decide future target qualification.
| 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` |
+| FR1–FR7 | `Drawer.test.tsx` render, initial-mode, click, sizing, side, and control suites plus `DrawerHeader.test.tsx` | 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` |
+| 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`, `DrawerHeader.doc.mjs`, the `DrawerHeader` target test, 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
-None. This draft records current facts and introduces no component-local design,
-API, theming, scope, or layer-system decision.
+- **DEC-1 — Align the close control and dismissal policy with Dialog** (owner
+ decision, 2026-10-01). Drawer drops its built-in close button and
+ `hasCloseButton`, adopts Dialog's `purpose` values and default, and adds
+ `DrawerHeader` with `DialogHeader`'s API, so a close action lives in the header
+ only when `onOpenChange` is passed. A Drawer-owned header, rather than reusing
+ `DialogHeader`, keeps Drawer's focus entry (`data-autofocus` after native
+ presentation) and `label` naming and avoids `dialog-header` theme targets.
+ Rejected: keeping the built-in button and hiding it only for `required`;
+ reusing `DialogHeader`; removing the button with no header.
## Open questions
-None. Regional placement, independent modality/scrim axes, and block-axis sheets
+- Should `DrawerHeader` supply a default focus target and name the Drawer through
+ `aria-labelledby`, as `DialogHeader` does for Dialog? Today `label` is required
+ and focus entry uses `data-autofocus`.
+
+Regional placement, independent modality/scrim axes, and block-axis sheets
are outside the current component boundary. Any future proposal for them requires
fresh public-API and design authority rather than being inferred from this
current-state backfill.
diff --git a/packages/lab/src/Drawer/Drawer.test.tsx b/packages/lab/src/Drawer/Drawer.test.tsx
index 6df04911e5..5e4bd2347e 100644
--- a/packages/lab/src/Drawer/Drawer.test.tsx
+++ b/packages/lab/src/Drawer/Drawer.test.tsx
@@ -13,6 +13,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, act} from '@testing-library/react';
import {useState} from 'react';
import {Drawer} from './Drawer';
+import {DrawerHeader} from './DrawerHeader';
// Mock dialog methods since they're not fully implemented in jsdom
beforeEach(() => {
@@ -445,10 +446,10 @@ describe('Drawer', () => {
render(
<Drawer isOpen onOpenChange={() => {}} label="Details">
<button type="button">First action</button>
+ <button type="button">Last action</button>
</Drawer>,
);
- const closeButton = screen.getByRole('button', {name: 'Close'});
- closeButton.focus();
+ screen.getByRole('button', {name: 'Last action'}).focus();
fireEvent.keyDown(document, {key: 'Tab'});
@@ -552,61 +553,152 @@ describe('Drawer', () => {
});
});
- describe('close button', () => {
- it('renders a close button by default when modal', () => {
+ describe('close control', () => {
+ it('renders no close button of its own, modal or non-modal', () => {
+ const {rerender} = render(
+ <Drawer isOpen onOpenChange={() => {}} label="Details">
+ Content
+ </Drawer>,
+ );
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ rerender(
+ <Drawer isOpen onOpenChange={() => {}} label="Details" hasScrim={false}>
+ Content
+ </Drawer>,
+ );
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+
+ it('closes through a DrawerHeader given the same onOpenChange', () => {
const handleOpenChange = vi.fn();
render(
<Drawer isOpen onOpenChange={handleOpenChange} label="Details">
+ <DrawerHeader title="Details" onOpenChange={handleOpenChange} />
Content
</Drawer>,
);
- const closeButton = screen.getByRole('button', {name: 'Close'});
- fireEvent.click(closeButton);
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
expect(handleOpenChange).toHaveBeenCalledWith(false);
});
+ });
- it('renders a close button by default when non-modal', () => {
+ describe('purpose', () => {
+ it("defaults to 'info': Escape and a scrim click both request close", () => {
+ const handleOpenChange = vi.fn();
+ render(
+ <Drawer isOpen onOpenChange={handleOpenChange} label="Details">
+ Content
+ </Drawer>,
+ );
+ const dialog = screen.getByRole('dialog');
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ fireEvent.click(dialog);
+ expect(handleOpenChange).toHaveBeenCalledTimes(2);
+ expect(handleOpenChange).toHaveBeenNthCalledWith(1, false);
+ expect(handleOpenChange).toHaveBeenNthCalledWith(2, false);
+ });
+
+ it("'form' closes on Escape but ignores a scrim click", () => {
const handleOpenChange = vi.fn();
render(
<Drawer
isOpen
onOpenChange={handleOpenChange}
label="Details"
- hasScrim={false}>
+ purpose="form">
Content
</Drawer>,
);
- fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ const dialog = screen.getByRole('dialog');
+ fireEvent.click(dialog);
+ expect(handleOpenChange).not.toHaveBeenCalled();
+ fireEvent.keyDown(dialog, {key: 'Escape'});
expect(handleOpenChange).toHaveBeenCalledWith(false);
});
- it('hides the close button with hasCloseButton={false}', () => {
+ it("'required' ignores Escape, the native cancel event, and a scrim click", () => {
+ const handleOpenChange = vi.fn();
+ render(
+ <Drawer
+ isOpen
+ onOpenChange={handleOpenChange}
+ label="Accept terms"
+ purpose="required">
+ Content
+ </Drawer>,
+ );
+ const dialog = screen.getByRole('alertdialog');
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ fireEvent.click(dialog);
+ const cancelEvent = new Event('cancel', {cancelable: true});
+ fireEvent(dialog, cancelEvent);
+ expect(cancelEvent.defaultPrevented).toBe(true);
+ expect(handleOpenChange).not.toHaveBeenCalled();
+ });
+
+ it("'required' consumes Escape so a drawer behind it stays open", () => {
+ const closeOuter = vi.fn();
+ const closeInner = vi.fn();
+ function Harness() {
+ const [isInnerOpen, setIsInnerOpen] = useState(false);
+ return (
+ <>
+ <Drawer
+ isOpen
+ onOpenChange={closeOuter}
+ label="Order"
+ hasScrim={false}>
+ <button type="button" onClick={() => setIsInnerOpen(true)}>
+ Open terms
+ </button>
+ </Drawer>
+ <Drawer
+ isOpen={isInnerOpen}
+ onOpenChange={closeInner}
+ label="Accept terms"
+ purpose="required">
+ Terms
+ </Drawer>
+ </>
+ );
+ }
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open terms'}));
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(closeInner).not.toHaveBeenCalled();
+ expect(closeOuter).not.toHaveBeenCalled();
+ });
+
+ it("exposes a modal 'required' drawer as an alertdialog", () => {
render(
<Drawer
isOpen
onOpenChange={() => {}}
- label="Details"
- hasCloseButton={false}>
+ label="Accept terms"
+ purpose="required">
Content
</Drawer>,
);
expect(
- screen.queryByRole('button', {name: 'Close'}),
- ).not.toBeInTheDocument();
+ screen.getByRole('alertdialog', {name: 'Accept terms'}),
+ ).toHaveAttribute('aria-modal', 'true');
});
- it('keeps the close button when hasCloseButton is explicitly true in non-modal mode', () => {
+ it("keeps a non-modal 'required' drawer in the dialog role", () => {
render(
<Drawer
isOpen
onOpenChange={() => {}}
- label="Details"
- hasScrim={false}
- hasCloseButton>
+ label="Accept terms"
+ purpose="required"
+ hasScrim={false}>
Content
</Drawer>,
);
- expect(screen.getByRole('button', {name: 'Close'})).toBeInTheDocument();
+ expect(
+ screen.getByRole('dialog', {name: 'Accept terms'}),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
});
});
diff --git a/packages/lab/src/Drawer/Drawer.tsx b/packages/lab/src/Drawer/Drawer.tsx
index 720bb21960..23954d8394 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, shared focus/dismissal/depth primitives, i18n, scroll locking/dialog presence, BaseProps, merged refs/props, themeProps
+ * @input Uses React, StyleX, theme tokens and text defaults, the Dialog purpose type, shared focus/dismissal/depth primitives, 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
*
@@ -35,9 +35,15 @@
* Sibling drawers use the shared layer dismissal stack for topmost-only Escape
* handling and the browser top layer's chronological paint order.
*
+ * Dismissal follows Dialog: `purpose` decides whether Escape and a scrim click
+ * request close, and Drawer renders no close button of its own. Compose
+ * `DrawerHeader` with `onOpenChange` for a visible close action, as with
+ * `DialogHeader`.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/lab/src/Drawer/Drawer.doc.mjs (props table, features, usage)
* - /packages/lab/src/Drawer/Drawer.test.tsx (tests for new/changed behavior)
+ * - /packages/lab/src/Drawer/Drawer.spec.md (component contract)
* - /packages/lab/src/Drawer/index.ts (exports if types change)
* - /apps/storybook/stories/Drawer.stories.tsx (examples and visual coverage)
*/
@@ -51,19 +57,16 @@ import {
durationVars,
easeVars,
shadowVars,
- spacingVars,
typeScaleVars,
typographyVars,
} from '@astryxdesign/core/theme/tokens.stylex';
-import {Icon} from '@astryxdesign/core/Icon';
-import {IconButton} from '@astryxdesign/core/IconButton';
+import type {DialogPurpose} from '@astryxdesign/core/Dialog';
import {
useFocusTrap,
useMergedRefs,
useScrollLock,
} from '@astryxdesign/core/hooks';
import {LayerDepthProvider, useLayerDismissal} from '@astryxdesign/core/Layer';
-import {useTranslator} from '@astryxdesign/core/i18n';
import {
composeEventHandlers,
mergeProps,
@@ -235,16 +238,6 @@ const styles = stylex.create({
paddingBlockEnd: 'env(safe-area-inset-bottom, 0px)',
outline: 'none',
},
- // Close affordance floats in the top-trailing corner, above the
- // scrollable content.
- controls: {
- position: 'absolute',
- insetBlockStart: spacingVars['--spacing-2'],
- insetInlineEnd: spacingVars['--spacing-2'],
- display: 'flex',
- gap: spacingVars['--spacing-1'],
- zIndex: 1,
- },
});
const dynamicStyles = stylex.create({
@@ -274,10 +267,11 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {
isOpen: boolean;
/**
- * Called when the drawer requests an open-state change. Escape, scrim
- * click, and the built-in close button call it with `false`. The caller owns
- * the open state. When sibling drawers are open, Escape only closes the top
- * (last-opened) drawer.
+ * Called when the drawer requests an open-state change. Escape and a scrim
+ * click call it with `false` as `purpose` allows; a `DrawerHeader` close
+ * button calls it when you pass the same callback to the header. The caller
+ * owns the open state. When sibling drawers are open, Escape only closes the
+ * top (last-opened) drawer.
*/
onOpenChange: (isOpen: boolean) => void;
@@ -324,12 +318,16 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {
hasScrim?: boolean;
/**
- * Whether to render the built-in close button in the top-trailing
- * corner. Enabled by default for both modal and non-modal drawers so every
- * overlay has an obvious dismissal affordance.
- * @default true
+ * Configures how the drawer enables dismissals, matching Dialog.
+ * - required: Disables Escape and scrim click (for mandatory flows); a
+ * modal required drawer is exposed as an `alertdialog`
+ * - form: Prevents scrim click, allows the Escape key
+ * - info: Allows Escape and scrim click
+ *
+ * A non-modal drawer has no scrim, so `form` and `info` behave the same.
+ * @default 'info'
*/
- hasCloseButton?: boolean;
+ purpose?: DialogPurpose;
/**
* Drawer content. Rendered inside a full-height scrollable area.
@@ -359,13 +357,19 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {
* closes the top-most open drawer; focus returns to the element that
* opened it.
*
+ * Dismissal matches Dialog: `purpose` decides whether Escape and a scrim click
+ * close the drawer, and `DrawerHeader` renders a close button when given
+ * `onOpenChange`.
+ *
* @example
* ```
* const [selected, setSelected] = useState(null);
+ * const handleOpenChange = isOpen => !isOpen && setSelected(null);
* <Drawer
* isOpen={selected != null}
- * onOpenChange={isOpen => !isOpen && setSelected(null)}
+ * onOpenChange={handleOpenChange}
* label={`Details: ${selected?.name}`}>
+ * <DrawerHeader title={selected?.name} onOpenChange={handleOpenChange} />
* <HostDetails host={selected} />
* </Drawer>
* ```
@@ -378,7 +382,7 @@ export function Drawer({
isFullWidthOnMobile = false,
label,
hasScrim = true,
- hasCloseButton = true,
+ purpose = 'info',
children,
xstyle,
className,
@@ -393,7 +397,9 @@ export function Drawer({
isActive: isOpen && hasScrim,
});
const mergedDialogRef = useMergedRefs(ref, dialogRef, focusTrapRef);
- const t = useTranslator();
+ // Derive dismissal behavior from purpose, as Dialog does.
+ const allowEscape = purpose !== 'required';
+ const allowScrimClick = purpose === 'info';
// Whether the panel paints: true while open and for the whole slide-out.
const [isRendered, setIsRendered] = useState(isOpen);
@@ -423,6 +429,9 @@ export function Drawer({
// 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,
+ // A `required` drawer consumes Escape without closing, so the press cannot
+ // fall through and dismiss a layer behind it either.
+ escapeBehavior: allowEscape ? 'close' : 'block',
onDismiss: handleDismiss,
getContainer: () => dialogRef.current,
});
@@ -436,22 +445,22 @@ export function Drawer({
const handleCancel = useCallback(
(event: React.SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
- if (shouldDismissOnCloseRequest()) {
+ if (shouldDismissOnCloseRequest() && allowEscape) {
handleDismiss();
}
},
- [handleDismiss, shouldDismissOnCloseRequest],
+ [allowEscape, handleDismiss, shouldDismissOnCloseRequest],
);
// Clicks on the ::backdrop target the <dialog> element itself; clicks on
// drawer content always target a child (the content area fills the panel).
const handleClick = useCallback(
(event: React.MouseEvent<HTMLDialogElement>) => {
- if (event.target === event.currentTarget && hasScrim) {
+ if (event.target === event.currentTarget && hasScrim && allowScrimClick) {
onOpenChange(false);
}
},
- [hasScrim, onOpenChange],
+ [allowScrimClick, hasScrim, onOpenChange],
);
const widthValue = typeof width === 'number' ? `${width}px` : width;
@@ -501,6 +510,9 @@ export function Drawer({
popover={hasScrim ? undefined : 'manual'}
aria-label={label}
aria-modal={hasScrim ? 'true' : undefined}
+ {...(purpose === 'required' && hasScrim
+ ? {role: 'alertdialog'}
+ : undefined)}
onClick={composeEventHandlers(onClickProp, handleClick)}
onKeyDown={onKeyDownProp}
onCancel={handleCancel}>
@@ -510,16 +522,6 @@ export function Drawer({
<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/DrawerHeader.doc.mjs b/packages/lab/src/Drawer/DrawerHeader.doc.mjs
new file mode 100644
index 0000000000..78449ecf4b
--- /dev/null
+++ b/packages/lab/src/Drawer/DrawerHeader.doc.mjs
@@ -0,0 +1,288 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DrawerHeader.doc.mjs
+ * @input DrawerHeader props, anatomy, theming targets, and examples
+ * @output Consumer documentation for DrawerHeader, a sub-component of Drawer
+ * @position CLI and docsite metadata for the Lab Drawer header
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+
+export const docs = {
+ name: 'DrawerHeader',
+ subComponentOf: 'Drawer',
+ displayName: 'Drawer Header',
+ isHiddenFromOverview: true,
+ description:
+ 'Header for drawers with a title, optional subtitle, close button, and start/end content slots. Same API as DialogHeader.',
+ usage: {
+ description:
+ 'Compose DrawerHeader first inside a Drawer for a title row and, when you pass onOpenChange, a close button. Drawer renders no close button of its own. Unlike DialogHeader it does not take focus on open (Drawer uses data-autofocus) and does not name the drawer (Drawer label does).',
+ anatomy: [
+ {
+ name: 'Header row',
+ required: true,
+ description:
+ 'Arranges the title block, optional start/end content, and close control.',
+ },
+ {
+ name: 'Start content',
+ required: false,
+ description: 'Wraps optional leading content.',
+ },
+ {
+ name: 'Title block',
+ required: true,
+ description: 'Groups the title and optional subtitle.',
+ },
+ {
+ name: 'End content',
+ required: false,
+ description:
+ 'Groups optional trailing content with the optional close control.',
+ },
+ {
+ name: 'Close icon',
+ required: false,
+ description: 'Visual close glyph inside the close button.',
+ },
+ ],
+ },
+ props: [
+ {
+ name: 'title',
+ type: 'ReactNode',
+ description:
+ 'Drawer title, rendered as an h2. Keep it inline and non-interactive. It does not name the drawer; pass Drawer a label.',
+ required: true,
+ },
+ {
+ name: 'subtitle',
+ type: 'ReactNode',
+ description:
+ 'Subtitle below the title. Accepts inline content such as a Link; avoid block elements.',
+ },
+ {
+ name: 'onOpenChange',
+ type: '(isOpen: boolean) => unknown',
+ description:
+ "Close button callback, called with false (no button if omitted). Pass the Drawer's own onOpenChange.",
+ },
+ {
+ name: 'startContent',
+ type: 'ReactNode',
+ description: 'Content before the title (e.g., a back button).',
+ },
+ {
+ name: 'endContent',
+ type: 'ReactNode',
+ description: 'Content after the title, before the close button.',
+ },
+ {
+ name: 'endContentEdgeCompensation',
+ type: "'inline' | 'block' | 'all'",
+ description:
+ 'Selects compensation axes for the end-content slot. Omit to preserve automatic close-action compensation.',
+ },
+ {
+ name: 'hasDivider',
+ type: 'boolean',
+ description:
+ "Adds a border at the bottom edge. Defaults to the parent Layout's defaultHasDividers; directly inside a Drawer there is none.",
+ },
+ ],
+ playground: {
+ defaults: {
+ title: 'Host details',
+ subtitle: 'web-prod-04',
+ hasDivider: true,
+ },
+ },
+ theming: {
+ targets: [
+ {className: 'astryx-drawer-header'},
+ {className: 'astryx-drawer-header-start-content'},
+ {className: 'astryx-drawer-header-title-block'},
+ {className: 'astryx-drawer-header-end-content'},
+ {className: 'astryx-drawer-header-close-icon'},
+ ],
+ },
+ examples: [
+ {
+ label: 'With close button',
+ code: `
+import {useState} from 'react';
+import {Drawer, DrawerHeader} from '@astryxdesign/lab';
+
+function Inspector() {
+ const [isOpen, setIsOpen] = useState(true);
+
+ // Passing onOpenChange renders a close button that calls it with false.
+ return (
+ <Drawer isOpen={isOpen} onOpenChange={setIsOpen} label="Details">
+ <DrawerHeader title="Details" onOpenChange={setIsOpen} />
+ </Drawer>
+ );
+}
+`,
+ },
+ {
+ label: 'With subtitle and end content',
+ code: `
+import {DrawerHeader} from '@astryxdesign/lab';
+import {Badge} from '@astryxdesign/core/Badge';
+
+<DrawerHeader
+ title="web-prod-04"
+ subtitle="us-east-1"
+ endContent={<Badge label="Healthy" />}
+/>;
+`,
+ },
+ ],
+};
+
+export const docsZh = {
+ name: 'DrawerHeader',
+ isHiddenFromOverview: true,
+ displayName: 'Drawer Header',
+ description:
+ '抽屉头部,包含标题、可选副标题、关闭按钮以及首尾内容插槽;API 与 DialogHeader 相同。',
+ usage: {
+ description:
+ '在 Drawer 中最先放置 DrawerHeader,提供标题行;传入 onOpenChange 时显示关闭按钮。Drawer 本身不渲染关闭按钮。与 DialogHeader 不同,它不会在打开时获得焦点(Drawer 使用 data-autofocus),也不为抽屉命名(由 Drawer 的 label 命名)。',
+ anatomy: [
+ {
+ name: 'Header row',
+ required: true,
+ description: '排列标题区、可选的首尾内容和关闭控件。',
+ },
+ {
+ name: 'Start content',
+ required: false,
+ description: '包装可选的首部内容。',
+ },
+ {
+ name: 'Title block',
+ required: true,
+ description: '组合标题和可选副标题。',
+ },
+ {
+ name: 'End content',
+ required: false,
+ description: '组合可选尾部内容和可选关闭控件。',
+ },
+ {
+ name: 'Close icon',
+ required: false,
+ description: '关闭按钮内的关闭图标。',
+ },
+ ],
+ },
+ props: [
+ {
+ name: 'title',
+ type: 'ReactNode',
+ description:
+ '抽屉标题,渲染为 h2。请使用非交互的行内内容。它不为抽屉命名;请为 Drawer 传入 label。',
+ required: true,
+ },
+ {
+ name: 'subtitle',
+ type: 'ReactNode',
+ description: '标题下方的副标题,可包含链接等行内内容;避免使用块级元素。',
+ },
+ {
+ name: 'onOpenChange',
+ type: '(isOpen: boolean) => unknown',
+ description:
+ '关闭按钮的回调,以 false 调用(省略时不显示按钮)。传入 Drawer 自己的 onOpenChange。',
+ },
+ {
+ name: 'startContent',
+ type: 'ReactNode',
+ description: '标题之前的内容(例如返回按钮)。',
+ },
+ {
+ name: 'endContent',
+ type: 'ReactNode',
+ description: '标题之后、关闭按钮之前的内容。',
+ },
+ {
+ name: 'endContentEdgeCompensation',
+ type: "'inline' | 'block' | 'all'",
+ description: '选择尾部内容插槽的补偿轴;省略时保留关闭操作的自动补偿。',
+ },
+ {
+ name: 'hasDivider',
+ type: 'boolean',
+ description:
+ '在底部边缘添加分隔线。默认取父级 Layout 的 defaultHasDividers;直接放在 Drawer 中时没有分隔线。',
+ },
+ ],
+ theming: {
+ targets: [
+ {className: 'astryx-drawer-header'},
+ {className: 'astryx-drawer-header-start-content'},
+ {className: 'astryx-drawer-header-title-block'},
+ {className: 'astryx-drawer-header-end-content'},
+ {className: 'astryx-drawer-header-close-icon'},
+ ],
+ },
+};
+
+export const docsDense = {
+ name: 'DrawerHeader',
+ isHiddenFromOverview: true,
+ displayName: 'Drawer Header',
+ description:
+ 'drawer header w/ title, optional subtitle, close button, start/end content slots; same API as DialogHeader',
+ usage: {
+ description:
+ 'first child of Drawer; close button only when given onOpenChange (Drawer has none built in); no focus on open (Drawer uses data-autofocus); does not name the drawer (Drawer label does)',
+ anatomy: [
+ {
+ name: 'Header row',
+ required: true,
+ description:
+ 'arranges title block, optional start/end content, close control',
+ },
+ {
+ name: 'Start content',
+ required: false,
+ description: 'wraps optional leading content',
+ },
+ {
+ name: 'Title block',
+ required: true,
+ description: 'groups title + optional subtitle',
+ },
+ {
+ name: 'End content',
+ required: false,
+ description:
+ 'groups optional trailing content + optional close control',
+ },
+ {
+ name: 'Close icon',
+ required: false,
+ description: 'close glyph inside close button',
+ },
+ ],
+ },
+ propDescriptions: {
+ title:
+ 'drawer title node, rendered as h2; inline, non-interactive; does not name the drawer',
+ subtitle:
+ 'subtitle node below title; inline content ok (e.g. Link), no block elements',
+ onOpenChange:
+ "close button callback, called with false (omit=no button); pass the Drawer's onOpenChange",
+ startContent: 'content before title (e.g. back button)',
+ endContent: 'content after title, before close button',
+ endContentEdgeCompensation:
+ 'end-content slot axes: inline | block | all; omit=automatic close-action compensation',
+ hasDivider:
+ 'bottom border; default = parent Layout defaultHasDividers (none directly in Drawer)',
+ },
+};
diff --git a/packages/lab/src/Drawer/DrawerHeader.test.tsx b/packages/lab/src/Drawer/DrawerHeader.test.tsx
new file mode 100644
index 0000000000..8807acca03
--- /dev/null
+++ b/packages/lab/src/Drawer/DrawerHeader.test.tsx
@@ -0,0 +1,89 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DrawerHeader.test.tsx
+ * @input Uses vitest, @testing-library/react, DrawerHeader component
+ * @output Unit tests for DrawerHeader rendering, close action, slots, and theming targets
+ * @position Lab testing; validates DrawerHeader.tsx implementation
+ *
+ * SYNC: When DrawerHeader.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {DrawerHeader} from './DrawerHeader';
+
+describe('DrawerHeader', () => {
+ it('renders the title as an h2 and the subtitle below it', () => {
+ render(<DrawerHeader title="Host details" subtitle="web-prod-04" />);
+ expect(
+ screen.getByRole('heading', {level: 2, name: 'Host details'}),
+ ).toBeInTheDocument();
+ expect(screen.getByText('web-prod-04')).toBeInTheDocument();
+ });
+
+ it('renders no close button without onOpenChange', () => {
+ render(<DrawerHeader title="Details" />);
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+
+ it('renders a named close button that calls onOpenChange(false)', () => {
+ const handleOpenChange = vi.fn();
+ render(<DrawerHeader title="Details" onOpenChange={handleOpenChange} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));
+ expect(handleOpenChange).toHaveBeenCalledTimes(1);
+ expect(handleOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('renders start and end content around the title', () => {
+ render(
+ <DrawerHeader
+ title="Details"
+ startContent={<button type="button">Back</button>}
+ endContent={<button type="button">Edit</button>}
+ onOpenChange={() => {}}
+ />,
+ );
+ const names = screen
+ .getAllByRole('button')
+ .map(button => button.getAttribute('aria-label') ?? button.textContent);
+ expect(names).toEqual(['Back', 'Edit', 'Close']);
+ });
+
+ it('renders a 0 subtitle and skips an empty one', () => {
+ const {rerender, container} = render(
+ <DrawerHeader title="Details" subtitle={0} />,
+ );
+ expect(screen.getByText('0')).toBeInTheDocument();
+ rerender(<DrawerHeader title="Details" subtitle="" />);
+ const titleBlock = container.querySelector(
+ '.astryx-drawer-header-title-block',
+ );
+ expect(titleBlock?.children).toHaveLength(1);
+ });
+
+ it('emits its theming targets', () => {
+ const {container} = render(
+ <DrawerHeader
+ title="Details"
+ startContent="Start"
+ endContent="End"
+ onOpenChange={() => {}}
+ />,
+ );
+ for (const target of [
+ 'drawer-header',
+ 'drawer-header-start-content',
+ 'drawer-header-title-block',
+ 'drawer-header-end-content',
+ 'drawer-header-close-icon',
+ ]) {
+ expect(container.querySelector(`.astryx-${target}`)).not.toBeNull();
+ }
+ });
+
+ it('does not move focus on mount', () => {
+ render(<DrawerHeader title="Details" onOpenChange={() => {}} />);
+ expect(document.activeElement).toBe(document.body);
+ });
+});
diff --git a/packages/lab/src/Drawer/DrawerHeader.tsx b/packages/lab/src/Drawer/DrawerHeader.tsx
new file mode 100644
index 0000000000..1f20624aed
--- /dev/null
+++ b/packages/lab/src/Drawer/DrawerHeader.tsx
@@ -0,0 +1,237 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file DrawerHeader.tsx
+ * @input Uses React, StyleX, LayoutHeader, Button, Icon, Heading, Text, i18n, BaseProps, mergeProps, themeProps
+ * @output Exports DrawerHeader component and DrawerHeaderProps
+ * @position Lab Drawer header; composed as the first child of Drawer, tested by DrawerHeader.test.tsx
+ *
+ * Mirrors DialogHeader's API: a title, an optional subtitle, start/end content
+ * slots, and a close button that renders only when `onOpenChange` is passed.
+ * Two differences follow from Drawer's contract:
+ * - It does not move focus on mount. Drawer owns focus entry through
+ * `data-autofocus` once its native host is presented.
+ * - It does not name the drawer. Drawer's required `label` does.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Drawer/DrawerHeader.doc.mjs (props, anatomy, theming)
+ * - /packages/lab/src/Drawer/DrawerHeader.test.tsx (tests for new/changed behavior)
+ * - /packages/lab/src/Drawer/index.ts (exports if types change)
+ * - /apps/storybook/stories/Drawer.stories.tsx (examples and visual coverage)
+ */
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {BaseProps} from '@astryxdesign/core';
+import {
+ sizeVars,
+ spacingVars,
+ typeScaleVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {Button} from '@astryxdesign/core/Button';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Icon} from '@astryxdesign/core/Icon';
+import {LayoutHeader} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+import {useTranslator} from '@astryxdesign/core/i18n';
+import {mergeProps, themeProps} from '@astryxdesign/core/utils';
+
+const styles = stylex.create({
+ container: {
+ display: 'flex',
+ alignItems: 'flex-start',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-3'],
+ },
+ // Compensate for the medium icon button's visual padding on the end slot.
+ endBlockEdgeCompensation: {
+ marginBlock: `calc(-1 * ${spacingVars['--spacing-2']})`,
+ },
+ endInlineEdgeCompensation: {
+ marginInlineEnd: `calc(-1 * ${spacingVars['--spacing-2']})`,
+ },
+ titleWrapper: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0'],
+ flex: 1,
+ minWidth: 0,
+ // Align the title's center with the close button's center, as
+ // DialogHeader does.
+ marginBlock: `calc(${sizeVars['--size-element-md']} / 2 - ${spacingVars['--spacing-2']} - ${typeScaleVars['--text-heading-2-size']} * ${typeScaleVars['--text-heading-2-leading']} / 2)`,
+ },
+ actions: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ flexShrink: 0,
+ },
+});
+
+export interface DrawerHeaderProps extends BaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
+
+ /**
+ * The title of the drawer, rendered as an h2. Keep it inline and
+ * non-interactive. It does not name the drawer; Drawer's `label` does.
+ */
+ title: ReactNode;
+
+ /**
+ * Optional subtitle displayed below the title in smaller, secondary text.
+ * Accepts inline content such as a Link; it renders inside a span, so
+ * avoid block elements. Nothing renders for `null`, `undefined`, booleans,
+ * or an empty string.
+ */
+ subtitle?: ReactNode;
+
+ /**
+ * Called with `false` when the close button is clicked. Pass the Drawer's
+ * own `onOpenChange`. If not provided, no close button is rendered.
+ */
+ onOpenChange?: (isOpen: boolean) => unknown;
+
+ /**
+ * Content to render before the title (e.g., a back button).
+ */
+ startContent?: ReactNode;
+
+ /**
+ * Content to render after the title, before the close button (e.g., action
+ * buttons).
+ */
+ endContent?: ReactNode;
+
+ /**
+ * Overrides automatic end-slot compensation. When omitted, rendering the
+ * close action applies block and logical inline-end compensation. Use
+ * `inline`, `block`, or `all` to select the axes explicitly.
+ */
+ endContentEdgeCompensation?: 'inline' | 'block' | 'all';
+
+ /**
+ * Adds a themed border at the bottom edge.
+ * When false, spacing collapse is applied automatically for seamless visual flow.
+ * Defaults to the parent Layout's `defaultHasDividers` context value.
+ */
+ hasDivider?: boolean;
+}
+
+/**
+ * Header for a Drawer: a title, optional subtitle and start/end content, and a
+ * close button when `onOpenChange` is passed. Same API as DialogHeader.
+ *
+ * Uses LayoutHeader internally for consistent styling with other layout headers.
+ *
+ * @example
+ * ```
+ * <Drawer isOpen={isOpen} onOpenChange={setIsOpen} label="Details">
+ * <DrawerHeader title="Details" onOpenChange={setIsOpen} />
+ * <Section padding={4}>Content</Section>
+ * </Drawer>
+ * ```
+ */
+export function DrawerHeader({
+ title,
+ subtitle,
+ onOpenChange,
+ startContent,
+ endContent,
+ endContentEdgeCompensation,
+ hasDivider,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...rest
+}: DrawerHeaderProps) {
+ const t = useTranslator();
+ // A node subtitle may be `0`: render it inside Text instead of letting a
+ // truthiness check leak a bare text node, and skip only empty values.
+ const hasSubtitle =
+ subtitle != null && typeof subtitle !== 'boolean' && subtitle !== '';
+ const shouldCompensateEndBlock =
+ endContentEdgeCompensation == null
+ ? onOpenChange != null
+ : endContentEdgeCompensation === 'block' ||
+ endContentEdgeCompensation === 'all';
+ const shouldCompensateEndInline =
+ endContentEdgeCompensation == null
+ ? onOpenChange != null
+ : endContentEdgeCompensation === 'inline' ||
+ endContentEdgeCompensation === 'all';
+
+ return (
+ <LayoutHeader
+ ref={ref}
+ hasDivider={hasDivider}
+ xstyle={xstyle}
+ className={className}
+ style={style}
+ {...rest}>
+ <div
+ {...mergeProps(
+ themeProps('drawer-header'),
+ stylex.props(styles.container),
+ )}>
+ {startContent && (
+ <div
+ {...mergeProps(
+ themeProps('drawer-header-start-content'),
+ stylex.props(styles.actions),
+ )}>
+ {startContent}
+ </div>
+ )}
+ <div
+ {...mergeProps(
+ themeProps('drawer-header-title-block'),
+ stylex.props(styles.titleWrapper),
+ )}>
+ <Heading level={2}>{title}</Heading>
+ {hasSubtitle && (
+ <Text type="body" size="sm" color="secondary">
+ {subtitle}
+ </Text>
+ )}
+ </div>
+ {(endContent || onOpenChange) && (
+ <div
+ {...mergeProps(
+ themeProps('drawer-header-end-content'),
+ stylex.props(
+ styles.actions,
+ shouldCompensateEndBlock && styles.endBlockEdgeCompensation,
+ shouldCompensateEndInline && styles.endInlineEdgeCompensation,
+ ),
+ )}>
+ {endContent}
+ {onOpenChange && (
+ <Button
+ variant="ghost"
+ label={t('@astryx.dialog.close')}
+ tooltip={t('@astryx.dialog.close')}
+ icon={
+ <Icon
+ icon="close"
+ color="inherit"
+ {...themeProps('drawer-header-close-icon')}
+ />
+ }
+ onClick={() => {
+ onOpenChange(false);
+ }}
+ isIconOnly
+ />
+ )}
+ </div>
+ )}
+ </div>
+ </LayoutHeader>
+ );
+}
+
+DrawerHeader.displayName = 'DrawerHeader';
diff --git a/packages/lab/src/Drawer/index.ts b/packages/lab/src/Drawer/index.ts
index 64b780d3e5..6b0eec2750 100644
--- a/packages/lab/src/Drawer/index.ts
+++ b/packages/lab/src/Drawer/index.ts
@@ -2,10 +2,12 @@
/**
* @file index.ts
- * @input Drawer.tsx
- * @output Re-exports Drawer component and DrawerProps type
+ * @input Drawer.tsx, DrawerHeader.tsx
+ * @output Re-exports Drawer and DrawerHeader components and their prop types
* @position Lab entry point for the Drawer directory
*/
export {Drawer} from './Drawer';
export type {DrawerProps} from './Drawer';
+export {DrawerHeader} from './DrawerHeader';
+export type {DrawerHeaderProps} from './DrawerHeader';
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 0a0b58f47a..d66e45e746 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -43,7 +43,12 @@ export {
export * from './Chat';
// Drawer — experimental overlay panel
-export {Drawer, type DrawerProps} from './Drawer';
+export {
+ Drawer,
+ DrawerHeader,
+ type DrawerProps,
+ type DrawerHeaderProps,
+} from './Drawer';
// Tour — guided product-tour / NUX walkthrough (facebook/astryx#4239)
export {