An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): define Drawer as a responsive side overlay (#5246)
rubyycheungc2bb31b61fb8
diff --git a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsxindex 9a7a2711ce..39376db429 100644--- a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx@@ -1036,7 +1036,7 @@ export default function ComponentScoresPage() {ref={drawerRef}id={AUDIT_PANEL_ID}isOpen={isAuditPanelOpen && selectedRow?.entry != null}- onClose={() => setIsAuditPanelOpen(false)}+ onOpenChange={setIsAuditPanelOpen}label={selectedRow? selectedRow.component +@@ -1047,7 +1047,7 @@ export default function ComponentScoresPage() {}hasScrim={false}hasCloseButton- size={560}>+ width={560}>{selectedRow ? (<AuditDetailsrow={selectedRow}diff --git a/apps/sandbox/src/app/(sandbox)/templates/page.tsx b/apps/sandbox/src/app/(sandbox)/templates/page.tsxindex e699bbaf1d..ee8ec51180 100644--- a/apps/sandbox/src/app/(sandbox)/templates/page.tsx+++ b/apps/sandbox/src/app/(sandbox)/templates/page.tsx@@ -981,7 +981,7 @@ export default function TemplatesPage() {ref={drawerRef}id={AUDIT_PANEL_ID}isOpen={isAuditPanelOpen && selectedRow?.audit != null}- onClose={() => setIsAuditPanelOpen(false)}+ onOpenChange={setIsAuditPanelOpen}label={selectedRow? selectedRow.name + ' template audit details'@@ -989,7 +989,7 @@ export default function TemplatesPage() {}hasScrim={false}hasCloseButton- size={560}>+ width={560}>{selectedRow ? <TemplateAuditDetails row={selectedRow} /> : null}</Drawer></>diff --git a/apps/storybook/stories/Drawer.stories.tsx b/apps/storybook/stories/Drawer.stories.tsxindex b5567790ac..2020a72e56 100644--- a/apps/storybook/stories/Drawer.stories.tsx+++ b/apps/storybook/stories/Drawer.stories.tsx@@ -8,7 +8,7 @@ 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} from '@astryxdesign/core/Stack';+import {VStack, HStack} from '@astryxdesign/core/Stack';import {Text} from '@astryxdesign/core/Text';const meta: Meta<typeof Drawer> = {@@ -17,6 +17,27 @@ const meta: Meta<typeof Drawer> = {tags: ['autodocs'],parameters: {layout: 'centered',+ docs: {+ description: {+ component: [+ 'A side panel that **floats above** page content — it overlays the',+ 'layout instead of reflowing it, which is what separates a drawer',+ 'from a docked panel.',+ '',+ '- Anchors to the **inline start or end** edge only (left/right in',+ ' LTR); block-axis sheets are `BottomSheet`.',+ '- Works on **desktop and touch**: `width` is the desktop budget',+ ' budget, and below 640px the panel preserves a 56px reveal',+ ' without exceeding that budget (`isFullWidthOnMobile` makes it',+ ' edge to edge).',+ '- **Scrim optional**: modal with a scrim by default, or',+ ' `hasScrim={false}` for a non-modal overlay that leaves the page',+ ' behind interactive.',+ '- **Square corners** (0px radius) — the panel is flush with three',+ ' viewport edges.',+ ].join('\n'),+ },+ },},decorators: [Story => (@@ -46,9 +67,9 @@ export const Showcase: Story = {<Button label="Open inspector" onClick={() => setIsOpen(true)} /><DrawerisOpen={isOpen}- onClose={() => setIsOpen(false)}+ onOpenChange={setIsOpen}label="Deployment details"- size={400}>+ width={400}><Section padding={4}><VStack gap={4}><VStack gap={1}>@@ -94,10 +115,10 @@ export const RowInspector: Story = {</VStack><DrawerisOpen={selected != null}- onClose={() => setSelectedId(null)}+ onOpenChange={isOpen => !isOpen && setSelectedId(null)}label={selected ? `Host details: ${selected.id}` : 'Host details'}hasScrim={false}- size={360}>+ width={360}>{selected != null && (<Section padding={4}><VStack gap={4}>@@ -128,48 +149,246 @@ export const RowInspector: Story = {},};-export const BottomSheet: Story = {+/**+ * Both edges. `side="start"` is left in LTR (and right in RTL) — use it for+ * navigation-adjacent content; `end` is the inspector convention.+ */+export const Sides: Story = {render: () => {- const [isOpen, setIsOpen] = useState(false);+ const [side, setSide] = useState<'start' | 'end' | null>(null);+ return (+ <>+ <HStack gap={2}>+ <Button label="Open from start" onClick={() => setSide('start')} />+ <Button label="Open from end" onClick={() => setSide('end')} />+ </HStack>+ <Drawer+ isOpen={side != null}+ onOpenChange={isOpen => !isOpen && setSide(null)}+ label={`Filters (${side ?? 'end'})`}+ side={side ?? 'end'}>+ <Section padding={4}>+ <VStack gap={4}>+ <Heading level={3}>Filter by region</Heading>+ <Text type="supporting" color="secondary">+ Sliding in from the {side} edge.+ </Text>+ </VStack>+ </Section>+ </Drawer>+ </>+ );+ },+};++/**+ * `width` is the desktop budget: a number of pixels or any CSS length.+ * Narrow the browser below 640px: each width remains an upper bound while+ * the drawer preserves a 56px reveal of the page behind.+ */+export const Widths: Story = {+ render: () => {+ const [width, setWidth] = useState<number | string | null>(null);+ return (+ <>+ <HStack gap={2}>+ <Button label="320px" onClick={() => setWidth(320)} />+ <Button label="480px" onClick={() => setWidth(480)} />+ <Button label="50%" onClick={() => setWidth('50%')} />+ </HStack>+ <Drawer+ isOpen={width != null}+ onOpenChange={isOpen => !isOpen && setWidth(null)}+ label="Details"+ width={width ?? 400}>+ <Section padding={4}>+ <VStack gap={4}>+ <Heading level={3}>web-prod-04</Heading>+ <Text type="body">Desktop width budget: {String(width)}</Text>+ </VStack>+ </Section>+ </Drawer>+ </>+ );+ },+};++/**+ * On touch viewports (below 640px) the drawer preserves a 56px reveal of the+ * page behind without exceeding its width budget; `isFullWidthOnMobile` makes+ * it edge to edge. Resize the preview below 640px to compare.+ */+export const MobileWidth: Story = {+ render: () => {+ const [openFull, setOpenFull] = useState(false);+ const [openPartial, setOpenPartial] = useState(false);const [selected, setSelected] = useState<string[]>(REGIONS.slice(0, 1));+ const filters = (+ <Section padding={4}>+ <VStack gap={4}>+ <VStack gap={1}>+ <Heading level={3}>Filter by region</Heading>+ <Text type="supporting" color="secondary">+ Showing hosts in {selected.length} of {REGIONS.length} regions+ </Text>+ </VStack>+ <VStack gap={2}>+ {REGIONS.map(region => (+ <CheckboxInput+ key={region}+ label={region}+ value={selected.includes(region)}+ onChange={checked =>+ setSelected(current =>+ checked+ ? [...current, region]+ : current.filter(r => r !== region),+ )+ }+ />+ ))}+ </VStack>+ <Button+ label="Apply filters"+ onClick={() => {+ setOpenFull(false);+ setOpenPartial(false);+ }}+ data-autofocus+ />+ </VStack>+ </Section>+ );return (<>- <Button label="Filter regions" onClick={() => setIsOpen(true)} />+ <HStack gap={2}>+ <Button+ label="56px reveal on mobile"+ onClick={() => setOpenPartial(true)}+ />+ <Button+ label="Full width on mobile"+ variant="secondary"+ onClick={() => setOpenFull(true)}+ />+ </HStack>+ <Drawer+ isOpen={openPartial}+ onOpenChange={setOpenPartial}+ label="Region filters">+ {filters}+ </Drawer>+ <Drawer+ isOpen={openFull}+ onOpenChange={setOpenFull}+ label="Region filters (full width)"+ isFullWidthOnMobile>+ {filters}+ </Drawer>+ </>+ );+ },+};++/**+ * A drawer floats above the page: the content underneath keeps its layout+ * and never reflows to make room, which is the difference between a drawer+ * and a docked panel. Compare the text column with the drawer open and+ * closed — nothing behind it moves.+ */+export const FloatsOverContent: Story = {+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <VStack gap={3}>+ <Button+ label={isOpen ? 'Close drawer' : 'Open drawer'}+ onClick={() => setIsOpen(open => !open)}+ />+ <Heading level={3}>Deployment log</Heading>+ {[+ 'The page keeps its full width while the drawer is open.',+ 'No column reflows, no content jumps, nothing is pushed aside.',+ 'The drawer is painted on top and the layout underneath is',+ 'untouched — which is exactly what a docked panel would not do.',+ ].map(line => (+ <Text key={line} type="body">+ {line}+ </Text>+ ))}+ </VStack><DrawerisOpen={isOpen}- onClose={() => setIsOpen(false)}- label="Region filters"- side="bottom"- size="40dvh">+ onOpenChange={setIsOpen}+ label="Deployment details"+ hasScrim={false}><Section padding={4}><VStack gap={4}>- <VStack gap={1}>- <Heading level={3}>Filter by region</Heading>- <Text type="supporting" color="secondary">- Showing hosts in {selected.length} of {REGIONS.length} regions- </Text>- </VStack>- <VStack gap={2}>- {REGIONS.map(region => (- <CheckboxInput- key={region}- label={region}- value={selected.includes(region)}- onChange={checked =>- setSelected(current =>- checked- ? [...current, region]- : current.filter(r => r !== region),- )- }- />- ))}- </VStack>- <Button- label="Apply filters"- onClick={() => setIsOpen(false)}- data-autofocus- />+ <Heading level={3}>web-prod-04</Heading>+ <Text type="supporting" color="secondary">+ Floating above the page, not docked beside it.+ </Text>+ </VStack>+ </Section>+ </Drawer>+ </>+ );+ },+};++/**+ * With a scrim (default) the drawer is modal: the page behind dims, focus is+ * trapped, and clicking the scrim closes it. Without one it is a plain+ * overlay — no dimming, no focus trap, and the page behind stays clickable,+ * which is what master-detail flows want.+ */+export const Scrim: Story = {+ render: () => {+ const [openWith, setOpenWith] = useState(false);+ const [openWithout, setOpenWithout] = useState(false);+ return (+ <>+ <VStack gap={3}>+ <HStack gap={2}>+ <Button label="With scrim" onClick={() => setOpenWith(true)} />+ <Button+ label="Without scrim"+ variant="secondary"+ onClick={() => setOpenWithout(true)}+ />+ </HStack>+ <Text type="supporting" color="secondary">+ These buttons stay clickable while the scrim-less drawer is open.+ </Text>+ </VStack>+ <Drawer+ isOpen={openWith}+ onOpenChange={setOpenWith}+ label="Modal details">+ <Section padding={4}>+ <VStack gap={4}>+ <Heading level={3}>Modal</Heading>+ <Text type="body">+ Scrim dims the page, focus is trapped, Escape or a scrim click+ closes.+ </Text>+ </VStack>+ </Section>+ </Drawer>+ <Drawer+ isOpen={openWithout}+ onOpenChange={setOpenWithout}+ label="Non-modal details"+ hasScrim={false}+ hasCloseButton>+ <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></Section></Drawer>diff --git a/packages/lab/src/Drawer/Drawer.doc.mjs b/packages/lab/src/Drawer/Drawer.doc.mjsindex a8a81abea3..f01610273c 100644--- a/packages/lab/src/Drawer/Drawer.doc.mjs+++ b/packages/lab/src/Drawer/Drawer.doc.mjs@@ -6,95 +6,144 @@ export const docs = {displayName: 'Drawer',group: 'Drawer',category: 'Overlay',- keywords: ["drawer","side panel","panel","inspector","detail view","overlay","slide","sheet","bottom sheet","sidebar","dialog","collapse","rail"],+ keywords: [+ 'drawer',+ 'side panel',+ 'panel',+ 'inspector',+ 'detail view',+ 'overlay',+ 'slide',+ 'sidebar',+ 'dialog',+ 'side drawer',+ ],theming: {- targets: [- {className: 'astryx-drawer', visualProps: ['side']},- ],+ targets: [{className: 'astryx-drawer', visualProps: ['side']}],},- description: 'Edge-anchored overlay panel using the native <dialog> element. Slides in from the start/end edge (side panel) or top/bottom edge (full-width sheet).',+ 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.',props: [{name: 'isOpen',type: 'boolean',- description: 'Whether the drawer is open. Fully controlled; pair with onClose.',+ description:+ 'Whether the drawer is open. Fully controlled; pair with onOpenChange.',required: true,},{- name: 'onClose',- type: '() => void',- description: 'Called when the drawer requests to be closed (Escape key, scrim click, built-in close button). The caller owns the open state. With sibling drawers open, Escape only closes the last-opened one.',+ 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.',required: true,},{name: 'label',type: 'string',- description: 'Accessible label for the drawer. Required; the drawer has no built-in heading to derive a name from. Also names the built-in collapse/expand affordances.',+ description:+ 'Accessible label for the drawer. Required; the drawer has no built-in heading to derive a name from.',required: true,},{name: 'children',type: 'ReactNode',- description: 'Drawer content, rendered inside a full-height scrollable area. Compose your own header/body/footer; an element with data-autofocus is focused on open. Children stay mounted during the exit animation; keep the last-selected item rendered instead of nulling content on close.',+ description:+ 'Drawer content, rendered inside a full-height scrollable area. Compose your own header/body/footer; an element with data-autofocus is focused on open. Children stay mounted during the exit animation; keep the last-selected item rendered instead of nulling content on close.',required: true,},{name: 'side',- type: "'start' | 'end' | 'top' | 'bottom'",- description: "Edge the drawer slides from: 'end' is right in LTR (the inspector convention), 'start' is left; 'top' and 'bottom' render full-width sheets on the block axis.",+ type: "'start' | 'end'",+ description:+ "Edge the drawer slides from: 'end' is right in LTR (the inspector convention), 'start' is left. Inline axis only; for a bottom sheet use BottomSheet.",default: "'end'",},{- name: 'size',+ name: 'width',type: 'number | string',- description: "Size budget along the slide axis: width for start/end, height for top/bottom. A number is pixels; a string is any CSS length ('50%', '40dvh'). On viewports smaller than the budget the drawer fills the axis.",+ description:+ "Desktop width budget. A number is pixels; a string is any CSS length ('50%', '32rem'). Below the 640px mobile breakpoint this remains the maximum while the drawer preserves a 56px reveal of the page behind.",default: '400',},{- name: 'hasScrim',+ name: 'isFullWidthOnMobile',type: 'boolean',- description: 'Modal scrim behind the drawer. true uses showModal() (top layer, focus trap, scroll lock; clicking the scrim closes; modal only); false uses show() for a non-modal overlay that does NOT trap focus and keeps the page behind interactive.',- default: 'true',+ description:+ 'Cover the full viewport width below the 640px mobile breakpoint instead of preserving the default 56px reveal of the page behind. The reveal makes the drawer read as an overlay, not a navigation.',+ default: 'false',},{- name: 'hasCloseButton',+ name: 'hasScrim',type: 'boolean',- description: 'Built-in close button in the top-trailing corner. Defaults to the hasScrim value: modal drawers get one, non-modal drawers don\'t.',- default: 'hasScrim',+ description:+ 'Modal scrim behind the drawer. true uses showModal() (top layer, focus trap, scroll lock; clicking the scrim closes; modal only); false uses show() for a non-modal overlay that does NOT trap focus and keeps the page behind interactive.',+ default: 'true',},{- name: 'isCollapsed',+ name: 'hasCloseButton',type: 'boolean',- description: 'Collapse the drawer to a narrow click-to-expand rail showing the label vertically. Only supported for non-modal (hasScrim={false}) start/end drawers; ignored with a dev warning otherwise. Controlled; pair with onCollapsedChange.',- },- {- name: 'onCollapsedChange',- type: '(collapsed: boolean) => void',- description: 'Called by the built-in collapse/expand affordances. Providing it renders a collapse toggle next to the close button while expanded; the collapsed rail always expands on click.',+ 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',},],usage: {- description: 'An edge-anchored overlay for inspectors, detail views, and sheets: the "click a table row, see its details" pattern. 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.',+ 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.',bestPractices: [- { guidance: true, description: 'Use for contextual detail views (row inspectors, entity details) where the user should keep the underlying list in sight.' },- { guidance: true, description: 'Keep the caller as the source of truth: derive isOpen from selection state and clear the selection in onClose.' },- { guidance: true, description: 'Use hasScrim={false} for master-detail flows; non-modal drawers do not trap focus and the page behind stays interactive.' },- { guidance: true, 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: 'Use isCollapsed/onCollapsedChange for persistent non-modal side panels; the collapsed rail is click-to-expand.' },- { guidance: false, description: 'Use a Drawer for short confirmations or small forms; use Dialog or AlertDialog instead.' },- { guidance: false, description: 'Nest a Drawer inside another Drawer; render drawers as siblings; the last-opened stacks on top and Escape closes it first.' },+ {+ guidance: true,+ description:+ 'Use for contextual detail views (row inspectors, entity details) where the user should keep the underlying list in sight.',+ },+ {+ guidance: true,+ description:+ 'Keep the caller as the source of truth: derive isOpen from selection state and clear the selection in onOpenChange.',+ },+ {+ guidance: true,+ description:+ 'Use hasScrim={false} for master-detail flows; non-modal drawers do not trap focus and the page behind stays interactive.',+ },+ {+ guidance: true,+ 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: false,+ description:+ 'Use a Drawer for short confirmations or small forms; use Dialog or AlertDialog instead.',+ },+ {+ guidance: false,+ description:+ 'Reach for a Drawer when the content should push the page aside; a Drawer floats over content, so use a docked panel or layout column instead.',+ },+ {+ guidance: false,+ description:+ 'Use a Drawer as a bottom or top sheet; it is inline-axis only, so use BottomSheet for block-axis sheets.',+ },+ {+ guidance: false,+ description:+ 'Nest a Drawer inside another Drawer; render drawers as siblings; the last-opened stacks on top and Escape closes it first.',+ },],},examples: [{- label: 'Bottom sheet',+ label: 'Wide desktop panel, full-width on mobile',code: `const [isOpen, setIsOpen] = useState(false);<DrawerisOpen={isOpen}- onClose={() => setIsOpen(false)}+ onOpenChange={setIsOpen}label="Filters"- side="bottom"- size="40dvh">+ width={560}+ isFullWidthOnMobile><FilterControls /></Drawer>`,},@@ -105,14 +154,14 @@ const [lineItem, setLineItem] = useState(null);<><DrawerisOpen={order != null}- onClose={() => setOrder(null)}+ onOpenChange={isOpen => !isOpen && setOrder(null)}label="Order details"hasScrim={false}><OrderDetails order={order} onSelectLineItem={setLineItem} /></Drawer><DrawerisOpen={lineItem != null}- onClose={() => setLineItem(null)}+ onOpenChange={isOpen => !isOpen && setLineItem(null)}label="Line item"hasScrim={false}><LineItemDetails item={lineItem} />@@ -126,32 +175,95 @@ const [lineItem, setLineItem] = useState(null);/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsZh = {usage: {- description: '用于检查器、详情视图和面板的边缘浮层——"点击表格行查看详情"的模式。按 Escape 关闭抽屉,焦点返回到打开它的元素。滑入/滑出动画遵循 prefers-reduced-motion。堆叠约定:同级抽屉后开的在上层,Escape 只关闭最上层的,关闭顺序由内向外——请以同级方式渲染,切勿嵌套。',+ description:+ '浮在页面内容之上的侧边面板,用于检查器和详情视图——"点击表格行查看详情"的模式。与停靠面板不同,它覆盖在布局之上,不会挤压页面。桌面端按 width 设定宽度,宽度小于 640px 时保留 56px 的底层页面,并且不超过 width 上限。按 Escape 关闭抽屉,焦点返回到打开它的元素。滑入/滑出动画遵循 prefers-reduced-motion。堆叠约定:同级抽屉后开的在上层,Escape 只关闭最上层的,关闭顺序由内向外——请以同级方式渲染,切勿嵌套。',bestPractices: [- { guidance: true, description: '用于上下文详情视图(行检查器、实体详情),让用户保持对底层列表的可见性。' },- { guidance: true, description: '让调用方作为唯一数据源:从选中状态派生 isOpen,并在 onClose 中清除选中。' },- { guidance: true, description: '在主从流程中使用 hasScrim={false}——非模态抽屉不捕获焦点,抽屉后面的页面保持可交互。' },- { guidance: true, description: '关闭时保留最后选中的内容:退出动画期间子内容仍然挂载,中途置空会让面板在滑出时变为空白。' },- { guidance: true, description: '对常驻的非模态侧面板使用 isCollapsed/onCollapsedChange;折叠后的窄条点击即可展开。' },- { guidance: false, description: '用 Drawer 做简短确认或小表单——请改用 Dialog 或 AlertDialog。' },- { guidance: false, description: '在 Drawer 中嵌套另一个 Drawer;应以同级方式渲染——后开的堆叠在上层,Escape 先关闭它。' },+ {+ guidance: true,+ description:+ '用于上下文详情视图(行检查器、实体详情),让用户保持对底层列表的可见性。',+ },+ {+ guidance: true,+ description:+ '让调用方作为唯一数据源:从选中状态派生 isOpen,并在 onOpenChange 中清除选中。',+ },+ {+ guidance: true,+ description:+ '在主从流程中使用 hasScrim={false}——非模态抽屉不捕获焦点,抽屉后面的页面保持可交互。',+ },+ {+ guidance: true,+ description:+ '关闭时保留最后选中的内容:退出动画期间子内容仍然挂载,中途置空会让面板在滑出时变为空白。',+ },+ {+ guidance: false,+ description:+ '用 Drawer 做简短确认或小表单——请改用 Dialog 或 AlertDialog。',+ },+ {+ guidance: false,+ description:+ '需要把页面内容挤开时不要用 Drawer——它浮在内容之上,请改用停靠面板或布局分栏。',+ },+ {+ guidance: false,+ description:+ '不要把 Drawer 当作底部/顶部面板使用——它只支持行内轴,块轴面板请用 BottomSheet。',+ },+ {+ guidance: false,+ description:+ '在 Drawer 中嵌套另一个 Drawer;应以同级方式渲染——后开的堆叠在上层,Escape 先关闭它。',+ },],},};/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsDense = {- description: 'edge-anchored overlay (native <dialog>): start/end side panel or top/bottom sheet',+ description:+ 'side panel floating over content (native <dialog>): start/end edge, full height',usage: {- description: 'Overlay for inspectors, detail views, and sheets. Escape closes topmost; focus restores to the opener. Siblings stack last-opened on top; never nest. Slide animation respects prefers-reduced-motion.',+ 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.',bestPractices: [- { guidance: true, description: 'Use for row inspectors and entity detail views.' },- { guidance: true, description: 'Derive isOpen from selection state; clear it in onClose.' },- { guidance: true, description: 'Use hasScrim={false} for non-modal master-detail flows (no focus trap, page stays interactive).' },- { guidance: true, description: 'Keep last-selected content rendered on close (children stay mounted during exit).' },- { guidance: true, description: 'Use isCollapsed/onCollapsedChange for persistent panels; rail is click-to-expand.' },- { guidance: false, description: 'Use for confirmations or small forms; use Dialog instead.' },- { guidance: false, description: 'Nest Drawers: render as siblings; Escape closes the last-opened first.' },+ {+ guidance: true,+ description: 'Use for row inspectors and entity detail views.',+ },+ {+ guidance: true,+ description:+ 'Derive isOpen from selection state; clear it in onOpenChange.',+ },+ {+ guidance: true,+ description:+ 'Use hasScrim={false} for non-modal master-detail flows (no focus trap, page stays interactive).',+ },+ {+ guidance: true,+ description:+ 'Keep last-selected content rendered on close (children stay mounted during exit).',+ },+ {+ guidance: false,+ description:+ 'Use for confirmations or small forms; use Dialog instead.',+ },+ {+ guidance: false,+ description:+ 'Use when content should push the page aside (it floats over) or as a bottom sheet (use BottomSheet).',+ },+ {+ guidance: false,+ description:+ 'Nest Drawers: render as siblings; Escape closes the last-opened first.',+ },],},};diff --git a/packages/lab/src/Drawer/Drawer.test.tsx b/packages/lab/src/Drawer/Drawer.test.tsxindex 0cf341ad65..6fb0933cc7 100644--- a/packages/lab/src/Drawer/Drawer.test.tsx+++ b/packages/lab/src/Drawer/Drawer.test.tsx@@ -50,7 +50,7 @@ afterEach(() => {describe('Drawer', () => {it('renders children when open', () => {render(- <Drawer isOpen onClose={() => {}} label="Host details">+ <Drawer isOpen onOpenChange={() => {}} label="Host details">Drawer content</Drawer>,);@@ -60,7 +60,7 @@ describe('Drawer', () => {it('does not show when isOpen is false', () => {render(- <Drawer isOpen={false} onClose={() => {}} label="Host details">+ <Drawer isOpen={false} onOpenChange={() => {}} label="Host details">Hidden content</Drawer>,);@@ -71,7 +71,7 @@ describe('Drawer', () => {it('applies the accessible label', () => {render(- <Drawer isOpen onClose={() => {}} label="Host details">+ <Drawer isOpen onOpenChange={() => {}} label="Host details">Content</Drawer>,);@@ -81,7 +81,7 @@ describe('Drawer', () => {describe('modal vs non-modal', () => {it('opens with showModal() and aria-modal by default (hasScrim)', () => {render(- <Drawer isOpen onClose={() => {}} label="Details">+ <Drawer isOpen onOpenChange={() => {}} label="Details">Content</Drawer>,);@@ -92,7 +92,7 @@ describe('Drawer', () => {it('opens with show() and no aria-modal when hasScrim is false', () => {render(- <Drawer isOpen onClose={() => {}} label="Details" hasScrim={false}>+ <Drawer isOpen onOpenChange={() => {}} label="Details" hasScrim={false}>Content</Drawer>,);@@ -103,85 +103,127 @@ describe('Drawer', () => {});describe('Escape key', () => {- it('calls onClose on Escape keydown', () => {- const handleClose = vi.fn();+ it('calls onOpenChange(false) on Escape keydown', () => {+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details">+ <Drawer isOpen onOpenChange={handleOpenChange} label="Details">Content</Drawer>,);fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});- expect(handleClose).toHaveBeenCalledTimes(1);+ expect(handleOpenChange).toHaveBeenCalledWith(false);});- it('calls onClose on Escape in non-modal mode (no native cancel)', () => {- const handleClose = vi.fn();+ it('calls onOpenChange(false) on Escape in non-modal mode (no native cancel)', () => {+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details" hasScrim={false}>+ <Drawer+ isOpen+ onOpenChange={handleOpenChange}+ label="Details"+ hasScrim={false}>Content</Drawer>,);fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});- expect(handleClose).toHaveBeenCalledTimes(1);+ expect(handleOpenChange).toHaveBeenCalledWith(false);});- it('prevents the native cancel event and routes through onClose', () => {- const handleClose = vi.fn();+ it('prevents the native cancel event and routes through onOpenChange(false)', () => {+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details">+ <Drawer isOpen onOpenChange={handleOpenChange} label="Details">Content</Drawer>,);const cancelEvent = new Event('cancel', {cancelable: true});fireEvent(screen.getByRole('dialog'), cancelEvent);- expect(handleClose).toHaveBeenCalledTimes(1);+ expect(handleOpenChange).toHaveBeenCalledWith(false);expect(cancelEvent.defaultPrevented).toBe(true);});it('ignores other keys', () => {- const handleClose = vi.fn();+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details">+ <Drawer isOpen onOpenChange={handleOpenChange} label="Details">Content</Drawer>,);fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Enter'});- expect(handleClose).not.toHaveBeenCalled();+ expect(handleOpenChange).not.toHaveBeenCalled();+ });+ });++ describe('consumer event handlers', () => {+ it('composes a consumer onKeyDown with built-in Escape handling', () => {+ const handleKeyDown = vi.fn();+ const handleOpenChange = vi.fn();+ render(+ <Drawer+ isOpen+ onOpenChange={handleOpenChange}+ label="Details"+ onKeyDown={handleKeyDown}>+ Content+ </Drawer>,+ );+ fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});+ expect(handleKeyDown).toHaveBeenCalledTimes(1);+ expect(handleOpenChange).toHaveBeenCalledWith(false);+ });++ it('lets a consumer preventDefault opt out of built-in Escape handling', () => {+ const handleOpenChange = vi.fn();+ render(+ <Drawer+ isOpen+ onOpenChange={handleOpenChange}+ label="Details"+ onKeyDown={event => event.preventDefault()}>+ Content+ </Drawer>,+ );+ fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});+ expect(handleOpenChange).not.toHaveBeenCalled();});});describe('scrim click', () => {- it('calls onClose when the ::backdrop (dialog element itself) is clicked', () => {- const handleClose = vi.fn();+ it('calls onOpenChange(false) when the ::backdrop (dialog element itself) is clicked', () => {+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details">+ <Drawer isOpen onOpenChange={handleOpenChange} label="Details">Content</Drawer>,);fireEvent.click(screen.getByRole('dialog'));- expect(handleClose).toHaveBeenCalledTimes(1);+ expect(handleOpenChange).toHaveBeenCalledWith(false);});it('does not close when drawer content is clicked', () => {- const handleClose = vi.fn();+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details">+ <Drawer isOpen onOpenChange={handleOpenChange} label="Details"><button type="button">Inside</button></Drawer>,);fireEvent.click(screen.getByRole('button', {name: 'Inside'}));- expect(handleClose).not.toHaveBeenCalled();+ expect(handleOpenChange).not.toHaveBeenCalled();});it('does not close on self-click when non-modal (no scrim to click)', () => {- const handleClose = vi.fn();+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details" hasScrim={false}>+ <Drawer+ isOpen+ onOpenChange={handleOpenChange}+ label="Details"+ hasScrim={false}>Content</Drawer>,);fireEvent.click(screen.getByRole('dialog'));- expect(handleClose).not.toHaveBeenCalled();+ expect(handleOpenChange).not.toHaveBeenCalled();});});@@ -193,10 +235,7 @@ describe('Drawer', () => {<button type="button" onClick={() => setIsOpen(true)}>Open inspector</button>- <Drawer- isOpen={isOpen}- onClose={() => setIsOpen(false)}- label="Inspector">+ <Drawer isOpen={isOpen} onOpenChange={setIsOpen} label="Inspector"><button type="button" onClick={() => setIsOpen(false)}>Close inspector</button>@@ -271,7 +310,7 @@ describe('Drawer', () => {it('focuses the element with data-autofocus on open', () => {render(- <Drawer isOpen onClose={() => {}} label="Details">+ <Drawer isOpen onOpenChange={() => {}} label="Details"><button type="button">First</button><button type="button" data-autofocus>Second@@ -283,7 +322,7 @@ describe('Drawer', () => {it('renders the side as a data attribute for theming', () => {render(- <Drawer isOpen onClose={() => {}} label="Details" side="start">+ <Drawer isOpen onOpenChange={() => {}} label="Details" side="start">Content</Drawer>,);@@ -291,11 +330,11 @@ describe('Drawer', () => {});describe('sides', () => {- it.each(['start', 'end', 'top', 'bottom'] as const)(+ it.each(['start', 'end'] as const)('renders side="%s" with the matching data attribute',side => {render(- <Drawer isOpen onClose={() => {}} label="Details" side={side}>+ <Drawer isOpen onOpenChange={() => {}} label="Details" side={side}>Content</Drawer>,);@@ -304,10 +343,10 @@ describe('Drawer', () => {);});- describe('size', () => {+ describe('width', () => {it('applies the default 400px inline budget', () => {render(- <Drawer isOpen onClose={() => {}} label="Details">+ <Drawer isOpen onOpenChange={() => {}} label="Details">Content</Drawer>,);@@ -318,7 +357,7 @@ describe('Drawer', () => {it('accepts a number of pixels', () => {render(- <Drawer isOpen onClose={() => {}} label="Details" size={320}>+ <Drawer isOpen onOpenChange={() => {}} label="Details" width={320}>Content</Drawer>,);@@ -329,74 +368,76 @@ describe('Drawer', () => {it('accepts any CSS length string', () => {render(- <Drawer isOpen onClose={() => {}} label="Details" size="50%">+ <Drawer isOpen onOpenChange={() => {}} label="Details" width="50%">Content</Drawer>,);expect(screen.getByRole('dialog').getAttribute('style')).toContain('50%');});- it('applies the size to the block axis for sheets', () => {+ it('preserves a 56px page reveal without exceeding the width budget on mobile', () => {render(- <Drawer- isOpen- onClose={() => {}}- label="Details"- side="bottom"- size="40dvh">+ <Drawer isOpen onOpenChange={() => {}} label="Details">Content</Drawer>,);- expect(screen.getByRole('dialog').getAttribute('style')).toContain(- '40dvh',- );+ // Desktop budget and mobile cap are both emitted as custom properties;+ // the media query itself is compiled CSS that jsdom cannot evaluate,+ // so assert both values reach the element.+ const style = screen.getByRole('dialog').getAttribute('style') ?? '';+ expect(style).toContain('400px');+ expect(style).toContain('min(400px, calc(100dvw - 56px))');});- it('sheets stretch to full viewport width (regression: UA width: fit-content left the sheet content-width in a corner)', () => {+ it('covers the full viewport on mobile with isFullWidthOnMobile', () => {render(- <Drawer isOpen onClose={() => {}} label="Details" side="bottom">+ <Drawer+ isOpen+ onOpenChange={() => {}}+ label="Details"+ isFullWidthOnMobile>Content</Drawer>,);- // The explicit width: 100dvw lives in the static bottom side style —- // insetInline: 0 alone loses to the dialog UA stylesheet's- // `width: fit-content`. jsdom can't resolve class-compiled CSS, so- // assert the side style class is applied; the declaration itself is- // covered by the source and visual verification.- const className = screen.getByRole('dialog').getAttribute('class') ?? '';- expect(className).toContain('Drawer__styles.bottom');+ const style = screen.getByRole('dialog').getAttribute('style') ?? '';+ expect(style).toContain('100dvw');+ expect(style).not.toContain('100dvw - 56px');});});describe('close button', () => {it('renders a close button by default when modal', () => {- const handleClose = vi.fn();+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={handleClose} label="Details">+ <Drawer isOpen onOpenChange={handleOpenChange} label="Details">Content</Drawer>,);const closeButton = screen.getByRole('button', {name: 'Close'});fireEvent.click(closeButton);- expect(handleClose).toHaveBeenCalledTimes(1);+ expect(handleOpenChange).toHaveBeenCalledWith(false);});- it('does not render a close button by default when non-modal', () => {+ it('renders a close button by default when non-modal', () => {+ const handleOpenChange = vi.fn();render(- <Drawer isOpen onClose={() => {}} label="Details" hasScrim={false}>+ <Drawer+ isOpen+ onOpenChange={handleOpenChange}+ label="Details"+ hasScrim={false}>Content</Drawer>,);- expect(- screen.queryByRole('button', {name: 'Close'}),- ).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', {name: 'Close'}));+ expect(handleOpenChange).toHaveBeenCalledWith(false);});it('hides the close button with hasCloseButton={false}', () => {render(<DrawerisOpen- onClose={() => {}}+ onOpenChange={() => {}}label="Details"hasCloseButton={false}>Content@@ -407,11 +448,11 @@ describe('Drawer', () => {).not.toBeInTheDocument();});- it('shows the close button on a non-modal drawer with hasCloseButton', () => {+ it('keeps the close button when hasCloseButton is explicitly true in non-modal mode', () => {render(<DrawerisOpen- onClose={() => {}}+ onOpenChange={() => {}}label="Details"hasScrim={false}hasCloseButton>@@ -422,131 +463,24 @@ describe('Drawer', () => {});});- describe('collapse to rail', () => {- it('renders a full-size expand button with the label when collapsed', () => {- render(- <Drawer- isOpen- onClose={() => {}}- label="Inspector"- hasScrim={false}- isCollapsed- onCollapsedChange={() => {}}>- Content- </Drawer>,- );- const expandButton = screen.getByRole('button', {- name: 'Expand Inspector',- });- expect(expandButton).toHaveTextContent('Inspector');- // Close/collapse controls are hidden while collapsed.- expect(- screen.queryByRole('button', {name: 'Collapse Inspector'}),- ).not.toBeInTheDocument();- expect(- screen.queryByRole('button', {name: 'Close'}),- ).not.toBeInTheDocument();- });-- it('calls onCollapsedChange(false) when the rail is clicked', () => {- const handleCollapsedChange = vi.fn();- render(- <Drawer- isOpen- onClose={() => {}}- label="Inspector"- hasScrim={false}- isCollapsed- onCollapsedChange={handleCollapsedChange}>- Content- </Drawer>,- );- fireEvent.click(screen.getByRole('button', {name: 'Expand Inspector'}));- expect(handleCollapsedChange).toHaveBeenCalledWith(false);- });-- it('renders a collapse toggle while expanded when onCollapsedChange is provided', () => {- const handleCollapsedChange = vi.fn();- render(- <Drawer- isOpen- onClose={() => {}}- label="Inspector"- hasScrim={false}- isCollapsed={false}- onCollapsedChange={handleCollapsedChange}>- Content- </Drawer>,- );- fireEvent.click(screen.getByRole('button', {name: 'Collapse Inspector'}));- expect(handleCollapsedChange).toHaveBeenCalledWith(true);- });-- it('dev-warns and ignores isCollapsed on a modal drawer', () => {- const consoleWarn = vi- .spyOn(console, 'warn')- .mockImplementation(() => {});- try {- render(- <Drawer- isOpen- onClose={() => {}}- label="Inspector"- isCollapsed- onCollapsedChange={() => {}}>- Content- </Drawer>,- );- expect(consoleWarn).toHaveBeenCalledWith(- expect.stringContaining('Drawer:'),- );- expect(- screen.queryByRole('button', {name: 'Expand Inspector'}),- ).not.toBeInTheDocument();- } finally {- consoleWarn.mockRestore();- }- });-- it('dev-warns and ignores isCollapsed on a sheet', () => {- const consoleWarn = vi- .spyOn(console, 'warn')- .mockImplementation(() => {});- try {- render(- <Drawer- isOpen- onClose={() => {}}- label="Inspector"- side="bottom"- hasScrim={false}- isCollapsed- onCollapsedChange={() => {}}>- Content- </Drawer>,- );- expect(consoleWarn).toHaveBeenCalledWith(- expect.stringContaining('Drawer:'),- );- expect(- screen.queryByRole('button', {name: 'Expand Inspector'}),- ).not.toBeInTheDocument();- } finally {- consoleWarn.mockRestore();- }- });- });-describe('LIFO stacking', () => {it('Escape only closes the last-opened drawer', () => {const closeFirst = vi.fn();const closeSecond = vi.fn();render(<>- <Drawer isOpen onClose={closeFirst} label="First" hasScrim={false}>+ <Drawer+ isOpen+ onOpenChange={closeFirst}+ label="First"+ hasScrim={false}>First content</Drawer>- <Drawer isOpen onClose={closeSecond} label="Second" hasScrim={false}>+ <Drawer+ isOpen+ onOpenChange={closeSecond}+ label="Second"+ hasScrim={false}>Second content</Drawer></>,@@ -563,7 +497,7 @@ describe('Drawer', () => {fireEvent.keyDown(screen.getByRole('dialog', {name: 'Second'}), {key: 'Escape',});- expect(closeSecond).toHaveBeenCalledTimes(1);+ expect(closeSecond).toHaveBeenCalledWith(false);expect(closeFirst).not.toHaveBeenCalled();});@@ -574,14 +508,14 @@ describe('Drawer', () => {<><DrawerisOpen={outerOpen}- onClose={() => setOuterOpen(false)}+ onOpenChange={setOuterOpen}label="Outer"hasScrim={false}>Outer content</Drawer><DrawerisOpen={innerOpen}- onClose={() => setInnerOpen(false)}+ onOpenChange={setInnerOpen}label="Inner"hasScrim={false}>Inner content@@ -614,23 +548,31 @@ describe('Drawer', () => {const closeFirst = vi.fn();const {rerender} = render(<>- <Drawer isOpen onClose={closeFirst} label="First" hasScrim={false}>+ <Drawer+ isOpen+ onOpenChange={closeFirst}+ label="First"+ hasScrim={false}>First content</Drawer>- <Drawer isOpen onClose={() => {}} label="Second" hasScrim={false}>+ <Drawer+ isOpen+ onOpenChange={() => {}}+ label="Second"+ hasScrim={false}>Second content</Drawer></>,);rerender(- <Drawer isOpen onClose={closeFirst} label="First" hasScrim={false}>+ <Drawer isOpen onOpenChange={closeFirst} label="First" hasScrim={false}>First content</Drawer>,);fireEvent.keyDown(screen.getByRole('dialog', {name: 'First'}), {key: 'Escape',});- expect(closeFirst).toHaveBeenCalledTimes(1);+ expect(closeFirst).toHaveBeenCalledWith(false);});});diff --git a/packages/lab/src/Drawer/Drawer.tsx b/packages/lab/src/Drawer/Drawer.tsxindex 9810680bc7..c189953264 100644--- a/packages/lab/src/Drawer/Drawer.tsx+++ b/packages/lab/src/Drawer/Drawer.tsx@@ -8,10 +8,17 @@* @output Exports Drawer component and DrawerProps* @position Lab implementation; consumed by index.ts, tested by Drawer.test.tsx, demonstrated in Storybook*- * Edge-anchored overlay panel for inspectors, detail views, and sheets —- * the "click a table row, see its details" pattern. Slides in from any of- * the four edges: inline start/end (side panels) or block top/bottom- * (full-width sheets).+ * Overlay panel for inspectors and detail views — the "click a table row,+ * see its details" pattern. Slides in from the inline start or end edge and+ * floats above the page content: unlike a docked panel it never reflows the+ * layout underneath, it overlays it (with or without a scrim).+ *+ * Inline axis only (start/end). Block-axis sheets are BottomSheet's job;+ * a drawer is always a full-height side panel.+ *+ * Sizing is viewport-aware: `width` is the desktop budget, and below+ * the mobile breakpoint it preserves a 56px reveal of the page behind, capped+ * by the requested width (or fills the viewport with `isFullWidthOnMobile`).** Uses the native `<dialog>` element (same precedent as Dialog/MobileNav):* - `showModal()` when `hasScrim` (default) — top-layer rendering, focus@@ -52,12 +59,16 @@ import {easeVars,shadowVars,spacingVars,- typeScaleVars,} from '@astryxdesign/core/theme/tokens.stylex';import {Icon} from '@astryxdesign/core/Icon';import {IconButton} from '@astryxdesign/core/IconButton';-import {useScrollLock, useDevWarning} from '@astryxdesign/core/hooks';-import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';+import {useScrollLock} from '@astryxdesign/core/hooks';+import {+ composeEventHandlers,+ mergeProps,+ mergeRefs,+ themeProps,+} from '@astryxdesign/core/utils';import {overlayPaddingReset} from '@astryxdesign/core/Layout';// =============================================================================@@ -104,9 +115,16 @@ function isTopDrawer(id: string): boolean {// Styles// =============================================================================-// Structural rail width when collapsed — wide enough for a 44px touch-// target, matching the raw-number convention used for the size default.-const RAIL_WIDTH = 44;+// Below this viewport width the drawer preserves a fixed reveal of the page+// behind instead of growing proportionally with the viewport. 640px is the+// repo's mobile breakpoint.+const MOBILE_BREAKPOINT = 640;++// Material's established mobile drawer pattern leaves a 56dp reveal. Using+// the same value in CSS pixels gives the overlay a stable visual relationship+// to the page behind while the requested width remains an upper bound.+const MOBILE_PAGE_REVEAL = 56;+const MOBILE_WIDTH_FULL = '100dvw';const styles = stylex.create({dialog: {@@ -115,6 +133,9 @@ const styles = stylex.create({margin: 0,padding: 0,border: 'none',+ // Square corners: the drawer is flush with the viewport edge on three+ // sides, so a radius would only ever cut the two edge-adjacent corners.+ borderRadius: 0,maxWidth: 'none',maxHeight: 'none',boxSizing: 'border-box',@@ -124,12 +145,15 @@ const styles = stylex.create({overflow: 'hidden',overscrollBehavior: 'contain',outline: 'none',+ // Full-height side panel, pinned across the block axis.+ insetBlockStart: 0,+ insetBlockEnd: 0,+ height: '100dvh',// Closed state. `display` participates in the transition with// allow-discrete so it flips to none only after the slide-out finishes- // (@starting-style covers the none -> flex entry). max-width animates- // the collapse-to-rail transition.+ // (@starting-style covers the none -> flex entry).display: 'none',- transitionProperty: 'transform, max-width, display',+ transitionProperty: 'transform, display',transitionDuration: durationVars['--duration-medium'],transitionTimingFunction: easeVars['--ease-standard'],transitionBehavior: 'allow-discrete',@@ -143,15 +167,11 @@ const styles = stylex.create({open: {display: 'flex',},- // Inline-axis panels (start/end): full height, pinned to one inline edge.- // start/end transforms flip under RTL; top/bottom (block axis) need no- // flip because the block axis is direction-safe.+ // start/end transforms flip under RTL so the panel always slides in from+ // the edge it is anchored to.end: {- insetBlockStart: 0,- insetBlockEnd: 0,insetInlineEnd: 0,insetInlineStart: 'auto',- height: '100dvh',borderInlineStartWidth: borderVars['--border-width'],borderInlineStartStyle: 'solid',borderInlineStartColor: colorVars['--color-border'],@@ -170,11 +190,8 @@ const styles = stylex.create({},},start: {- insetBlockStart: 0,- insetBlockEnd: 0,insetInlineStart: 0,insetInlineEnd: 'auto',- height: '100dvh',borderInlineEndWidth: borderVars['--border-width'],borderInlineEndStyle: 'solid',borderInlineEndColor: colorVars['--color-border'],@@ -192,44 +209,6 @@ const styles = stylex.create({},},},- // Block-axis sheets (top/bottom): full width, pinned to one block edge.- // width must be explicit — the UA stylesheet gives <dialog>- // `width: fit-content`, which beats the insetInline: 0 stretch and- // would leave the sheet content-width in a corner.- top: {- width: '100dvw',- insetInlineStart: 0,- insetInlineEnd: 0,- insetBlockStart: 0,- insetBlockEnd: 'auto',- borderBlockEndWidth: borderVars['--border-width'],- borderBlockEndStyle: 'solid',- borderBlockEndColor: colorVars['--color-border'],- transform: 'translateY(-100%)',- },- topOpen: {- transform: {- default: 'translateY(0)',- '@starting-style': 'translateY(-100%)',- },- },- bottom: {- width: '100dvw',- insetInlineStart: 0,- insetInlineEnd: 0,- insetBlockEnd: 0,- insetBlockStart: 'auto',- borderBlockStartWidth: borderVars['--border-width'],- borderBlockStartStyle: 'solid',- borderBlockStartColor: colorVars['--color-border'],- transform: 'translateY(100%)',- },- bottomOpen: {- transform: {- default: 'translateY(0)',- '@starting-style': 'translateY(100%)',- },- },// Scrim via the browser's ::backdrop pseudo-element (top layer).scrim: {'::backdrop': {@@ -254,13 +233,11 @@ const styles = stylex.create({},},},- // Collapsed rail: the whole panel shrinks to a narrow strip; max-width- // participates in the base transition so expand/collapse animates.- collapsedRail: {- maxWidth: RAIL_WIDTH,- },// Scrollable content area — full-bleed; consumers compose their own- // header/body/footer padding (see Drawer blocks for the pattern).+ // header/body/footer padding.+ // touch-action + overscroll containment keep momentum scrolling inside+ // the panel on touch devices; the safe-area inset keeps the last row of+ // content clear of the home indicator.content: {flexGrow: 1,minHeight: 0,@@ -269,14 +246,10 @@ const styles = stylex.create({overflowX: 'hidden',overscrollBehavior: 'contain',touchAction: 'pan-y',+ paddingBlockEnd: 'env(safe-area-inset-bottom, 0px)',outline: 'none',},- // Children stay mounted while collapsed (state is preserved); only the- // presentation is hidden.- contentHidden: {- display: 'none',- },- // Close/collapse affordances float in the top-trailing corner, above the+ // Close affordance floats in the top-trailing corner, above the// scrollable content.controls: {position: 'absolute',@@ -286,56 +259,18 @@ const styles = stylex.create({gap: spacingVars['--spacing-1'],zIndex: 1,},- // Full-size expand button shown while collapsed. The label reads- // vertically (vertical-rl matches right-side rail convention; flipped- // 180deg on the start side so the text still reads top-down).- railButton: {- appearance: 'none',- borderStyle: 'none',- margin: 0,- paddingBlock: spacingVars['--spacing-3'],- paddingInline: spacingVars['--spacing-1'],- flexGrow: 1,- width: '100%',- minHeight: 0,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- cursor: 'pointer',- backgroundColor: {- default: 'transparent',- ':hover': colorVars['--color-background-muted'],- },- color: colorVars['--color-text-secondary'],- fontFamily: 'inherit',- fontSize: typeScaleVars['--text-label-size'],- fontWeight: typeScaleVars['--text-label-weight'],- lineHeight: typeScaleVars['--text-label-leading'],- whiteSpace: 'nowrap',- overflow: 'hidden',- textOverflow: 'ellipsis',- writingMode: 'vertical-rl',- outline: 'none',- },- railButtonStart: {- transform: 'rotate(180deg)',- },});const dynamicStyles = stylex.create({- // Inline-axis budget (start/end): full width on viewports narrower than- // the budget (reference drawers collapse to a full overlay on small- // screens).- inlineSize: (s: string) => ({- width: '100dvw',- maxWidth: s,- }),- // Block-axis budget (top/bottom sheets): height caps at the budget,- // full-height on shorter viewports — mirrors the inline-axis approach.- // (Full-bleed width lives in the static top/bottom side styles.)- blockSize: (s: string) => ({- height: '100dvh',- maxHeight: s,+ // Width budget: the `width` prop on desktop, a share of the viewport below+ // the mobile breakpoint. maxWidth keeps a large desktop budget from+ // overflowing a narrow window.+ inlineSize: (desktopWidth: string, mobileWidth: string) => ({+ width: {+ default: desktopWidth,+ [`@media (max-width: ${MOBILE_BREAKPOINT}px)`]: mobileWidth,+ },+ maxWidth: '100dvw',}),stackZ: (z: number) => ({zIndex: z,@@ -351,40 +286,47 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {ref?: React.Ref<HTMLDialogElement>;/**- * Whether the drawer is open. Fully controlled — pair with `onClose`.+ * Whether the drawer is open. Fully controlled — pair with `onOpenChange`.*/isOpen: boolean;/**- * Called when the drawer requests to be closed- * (Escape key, scrim click, built-in close button). 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, 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.*/- onClose: () => void;+ onOpenChange: (isOpen: boolean) => void;/*** Which edge the drawer slides from.* - `'end'` — inline-end edge (right in LTR) — the inspector convention* - `'start'` — inline-start edge (left in LTR)- * - `'top'` / `'bottom'` — full-width sheets on the block axis* @default 'end'*/- side?: 'start' | 'end' | 'top' | 'bottom';+ side?: 'start' | 'end';/**- * Size budget of the panel along its slide axis: width for- * `side="start"/"end"`, height for `side="top"/"bottom"`. A number is- * pixels; a string is any CSS length (`'50%'`, `'40dvh'`). On viewports- * smaller than the budget the drawer fills the axis.+ * Desktop width budget. A number is pixels; a string is any CSS length+ * (`'50%'`, `'32rem'`). Below the mobile breakpoint (640px), this+ * remains the maximum while the drawer preserves a 56px reveal of the page+ * behind — see `isFullWidthOnMobile`.* @default 400*/- size?: number | string;+ width?: number | string;++ /**+ * Whether the drawer covers the full viewport width on mobile+ * (below 640px) instead of preserving the default 56px reveal of the page+ * behind. The reveal makes the drawer read as an overlay rather than a+ * navigation.+ * @default false+ */+ isFullWidthOnMobile?: boolean;/*** Accessible label for the drawer (required — the drawer has no- * built-in heading to derive a name from). Also names the built-in- * collapse/expand affordances.+ * built-in heading to derive a name from).*/label: string;@@ -400,27 +342,12 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {/*** Whether to render the built-in close button in the top-trailing- * corner. Defaults to the `hasScrim` value: modal drawers get a close- * button, non-modal drawers don't.- * @default hasScrim+ * corner. Enabled by default for both modal and non-modal drawers so every+ * overlay has an obvious dismissal affordance.+ * @default true*/hasCloseButton?: boolean;- /**- * Collapse the drawer to a narrow click-to-expand rail. Only supported- * for non-modal (`hasScrim={false}`) drawers with `side="start"/"end"`;- * ignored (with a dev warning) otherwise. Controlled — pair with- * `onCollapsedChange`.- */- isCollapsed?: boolean;-- /**- * Called when the built-in collapse/expand affordances are used.- * Providing it renders a collapse toggle next to the close button while- * expanded; the collapsed rail always expands on click.- */- onCollapsedChange?: (collapsed: boolean) => void;-/*** Drawer content. Rendered inside a full-height scrollable area.* Focus the element with `data-autofocus` on open, if present.@@ -438,21 +365,23 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {// =============================================================================/**- * An edge-anchored overlay panel for inspectors, detail views, and sheets.+ * An overlay panel for inspectors and detail views.*- * Slides in from the logical start/end edge (side panel) or the top/bottom- * edge (full-width sheet) using the native `<dialog>` element: modal with a- * scrim by default, or a non-modal inline overlay with `hasScrim={false}`.- * Escape closes the top-most open drawer; focus returns to the element that- * opened the drawer. Non-modal side drawers can collapse to a rail via- * `isCollapsed`/`onCollapsedChange`.+ * Slides in from the logical start or end edge and floats above the page+ * using the native `<dialog>` element: modal with a scrim by default, or a+ * non-modal overlay with `hasScrim={false}` that leaves the page behind+ * interactive. `width` is the desktop budget; below 640px the panel preserves+ * a 56px page reveal without exceeding that budget (or fills the viewport+ * with `isFullWidthOnMobile`). Escape+ * closes the top-most open drawer; focus returns to the element that+ * opened it.** @example* ```* const [selected, setSelected] = useState(null);* <Drawer* isOpen={selected != null}- * onClose={() => setSelected(null)}+ * onOpenChange={isOpen => !isOpen && setSelected(null)}* label={`Details: ${selected?.name}`}>* <HostDetails host={selected} />* </Drawer>@@ -460,18 +389,19 @@ export interface DrawerProps extends BaseProps<HTMLDialogElement> {*/export function Drawer({isOpen,- onClose,+ onOpenChange,side = 'end',- size = 400,+ width = 400,+ isFullWidthOnMobile = false,label,hasScrim = true,- hasCloseButton,- isCollapsed,- onCollapsedChange,+ hasCloseButton = true,children,xstyle,className,style,+ onClick: onClickProp,+ onKeyDown: onKeyDownProp,ref,...props}: DrawerProps) {@@ -479,31 +409,16 @@ export function Drawer({const closeTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);// Element focused when the drawer opened — restored on close.const triggerElementRef = useRef<HTMLElement | null>(null);- // Registry identity + latest onClose (stable across re-renders so the- // registration effect doesn't churn on every onClose identity change).+ // Registry identity + latest onOpenChange (stable across re-renders so the+ // registration effect doesn't churn on every onOpenChange identity change).const drawerId = useId();- const onCloseRef = useRef(onClose);+ const onOpenChangeRef = useRef(onOpenChange);useEffect(() => {- onCloseRef.current = onClose;- }, [onClose]);+ onOpenChangeRef.current = onOpenChange;+ }, [onOpenChange]);// z-index assigned by the registry on open (non-modal stacking only).const [stackZ, setStackZ] = useState(NON_MODAL_BASE_Z);- const isSheet = side === 'top' || side === 'bottom';- // Collapse only makes sense for a persistent (non-modal) side panel.- const canCollapse = !hasScrim && !isSheet;- const collapsed = canCollapse && isCollapsed === true;- const showCloseButton = hasCloseButton ?? hasScrim;-- // Dev warning for unsupported collapse combinations.- useDevWarning(- 'Drawer',- '`isCollapsed` is only supported for non-modal drawers ' +- '(hasScrim={false}) with side="start" or side="end". The prop is ' +- 'ignored.',- isCollapsed != null && !canCollapse,- );-// Open/close the native dialog. close() is delayed so the slide-out// transition can play; focus restore happens after close() because a// modal dialog makes the rest of the document inert (focus() on the@@ -582,7 +497,7 @@ export function Drawer({if (!isOpen) {return;}- const z = registerDrawer(drawerId, () => onCloseRef.current());+ const z = registerDrawer(drawerId, () => onOpenChangeRef.current(false));setStackZ(z);return () => unregisterDrawer(drawerId);}, [isOpen, drawerId]);@@ -591,40 +506,33 @@ export function Drawer({useScrollLock(isOpen && hasScrim);// Escape closes. The native `cancel` event only fires for showModal();- // this keydown handler covers the non-modal show() path too. Only the+ // this React keydown handler covers the non-modal show() path too. Only the// top of the drawer stack closes, so stacked siblings peel off// innermost-first.- useEffect(() => {- const dialog = dialogRef.current;- if (!dialog || !isOpen) {- return;- }-- const handleKeyDown = (event: KeyboardEvent) => {+ const handleKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLDialogElement>) => {if (event.key === 'Escape') {event.preventDefault();if (isTopDrawer(drawerId)) {- onClose();+ onOpenChange(false);}}- };-- dialog.addEventListener('keydown', handleKeyDown);- return () => dialog.removeEventListener('keydown', handleKeyDown);- }, [isOpen, onClose, drawerId]);+ },+ [onOpenChange, drawerId],+ );// Native cancel event (browser Escape handling) — prevent the browser- // from closing the dialog directly and route through onClose so the+ // from closing the dialog directly and route through onOpenChange so the// caller's state stays the source of truth. Same top-of-stack rule as// the keydown path.const handleCancel = useCallback((event: React.SyntheticEvent<HTMLDialogElement>) => {event.preventDefault();if (isTopDrawer(drawerId)) {- onClose();+ onOpenChange(false);}},- [onClose, drawerId],+ [onOpenChange, drawerId],);// Clicks on the ::backdrop target the <dialog> element itself; clicks on@@ -632,26 +540,19 @@ export function Drawer({const handleClick = useCallback((event: React.MouseEvent<HTMLDialogElement>) => {if (event.target === event.currentTarget && hasScrim) {- onClose();+ onOpenChange(false);}},- [hasScrim, onClose],+ [hasScrim, onOpenChange],);- const sizeValue = typeof size === 'number' ? `${size}px` : size;-- const sideStyle = {- start: styles.start,- end: styles.end,- top: styles.top,- bottom: styles.bottom,- }[side];- const sideOpenStyle = {- start: styles.startOpen,- end: styles.endOpen,- top: styles.topOpen,- bottom: styles.bottomOpen,- }[side];+ const widthValue = typeof width === 'number' ? `${width}px` : width;+ const mobileWidth = isFullWidthOnMobile+ ? MOBILE_WIDTH_FULL+ : `min(${widthValue}, calc(100dvw - ${MOBILE_PAGE_REVEAL}px))`;++ const sideStyle = side === 'start' ? styles.start : styles.end;+ const sideOpenStyle = side === 'start' ? styles.startOpen : styles.endOpen;// Filter out native `open` to prevent InvalidStateError when passedconst {open: _open, ...safeProps} = props as Record<string, unknown>;@@ -659,78 +560,42 @@ export function Drawer({return (<dialogref={mergeRefs(ref, dialogRef)}- aria-label={label}- aria-modal={hasScrim ? 'true' : undefined}- onClick={handleClick}- onCancel={handleCancel}{...mergeProps(themeProps('drawer', {side}),stylex.props(styles.dialog,overlayPaddingReset.reset,sideStyle,- isSheet- ? dynamicStyles.blockSize(sizeValue)- : dynamicStyles.inlineSize(sizeValue),+ dynamicStyles.inlineSize(widthValue, mobileWidth),isOpen && styles.open,isOpen && sideOpenStyle,hasScrim ? styles.scrim : dynamicStyles.stackZ(stackZ),hasScrim && isOpen && styles.scrimOpen,- collapsed && styles.collapsedRail,xstyle,),className,style,)}- {...safeProps}>+ {...safeProps}+ aria-label={label}+ aria-modal={hasScrim ? 'true' : undefined}+ onClick={composeEventHandlers(onClickProp, handleClick)}+ onKeyDown={composeEventHandlers(onKeyDownProp, handleKeyDown)}+ onCancel={handleCancel}>{/* Scrollable content area — tabIndex so the dialog's focusing steps- land on the panel body rather than the first button inside.- Children stay mounted while collapsed so their state survives. */}- <div- tabIndex={-1}- {...stylex.props(styles.content, collapsed && styles.contentHidden)}>+ land on the panel body rather than the first button inside. */}+ <div tabIndex={-1} {...stylex.props(styles.content)}>{children}</div>- {collapsed ? (- // Collapsed rail: one full-size expand button with the label- // reading vertically.- <button- type="button"- aria-label={`Expand ${label}`}- onClick={() => onCollapsedChange?.(false)}- {...stylex.props(- styles.railButton,- side === 'start' && styles.railButtonStart,- )}>- {label}- </button>- ) : (- (showCloseButton || (canCollapse && onCollapsedChange != null)) && (- <div {...stylex.props(styles.controls)}>- {canCollapse && onCollapsedChange != null && (- <IconButton- icon={- <Icon- icon={side === 'start' ? 'chevronLeft' : 'chevronRight'}- size="sm"- color="inherit"- />- }- label={`Collapse ${label}`}- variant="ghost"- onClick={() => onCollapsedChange(true)}- />- )}- {showCloseButton && (- <IconButton- icon={<Icon icon="close" size="sm" color="inherit" />}- label="Close"- variant="ghost"- onClick={onClose}- />- )}- </div>- )+ {hasCloseButton && (+ <div {...stylex.props(styles.controls)}>+ <IconButton+ icon={<Icon icon="close" size="sm" color="inherit" />}+ label="Close"+ variant="ghost"+ onClick={() => onOpenChange(false)}+ />+ </div>)}</dialog>);