An open source design system that's fully customizable and agent ready
TypeScript
feat(core): Drawer — side-panel overlay for inspectors and detail views (#3327)
David Petersend869d88d10ff
diff --git a/apps/storybook/stories/Drawer.stories.tsx b/apps/storybook/stories/Drawer.stories.tsxnew file mode 100644index 0000000000..b5567790ac--- /dev/null+++ b/apps/storybook/stories/Drawer.stories.tsx@@ -0,0 +1,179 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {Drawer} 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} from '@astryxdesign/core/Stack';+import {Text} from '@astryxdesign/core/Text';++const meta: Meta<typeof Drawer> = {+ title: 'Lab/Drawer',+ component: Drawer,+ tags: ['autodocs'],+ parameters: {+ layout: 'centered',+ },+ decorators: [+ Story => (+ <div style={{width: 560, minHeight: 360, padding: 32}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof Drawer>;++const HOSTS = [+ {id: 'web-01', region: 'us-east-1', status: 'Healthy', cpu: '32%'},+ {id: 'web-02', region: 'us-east-1', status: 'Healthy', cpu: '41%'},+ {id: 'worker-01', region: 'eu-west-1', status: 'Degraded', cpu: '87%'},+];++const REGIONS = ['us-east-1', 'eu-west-1', 'ap-south-1'];++export const Showcase: Story = {+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <Button label="Open inspector" onClick={() => setIsOpen(true)} />+ <Drawer+ isOpen={isOpen}+ onClose={() => setIsOpen(false)}+ label="Deployment details"+ size={400}>+ <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">+ Healthy - all 6 instances passing readiness checks.+ </Text>+ </VStack>+ <VStack gap={2}>+ <Text type="label">Build</Text>+ <Text type="body">#4821 - main @ 03536f1</Text>+ </VStack>+ </VStack>+ </Section>+ </Drawer>+ </>+ );+ },+};++export const RowInspector: Story = {+ render: () => {+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const selected = HOSTS.find(host => host.id === selectedId);+ return (+ <>+ <VStack gap={1}>+ {HOSTS.map(host => (+ <Button+ key={host.id}+ variant="ghost"+ label={`${host.id} / ${host.region}`}+ onClick={() => setSelectedId(host.id)}+ />+ ))}+ </VStack>+ <Drawer+ isOpen={selected != null}+ onClose={() => setSelectedId(null)}+ label={selected ? `Host details: ${selected.id}` : 'Host details'}+ hasScrim={false}+ size={360}>+ {selected != null && (+ <Section padding={4}>+ <VStack gap={4}>+ <VStack gap={1}>+ <Heading level={3}>{selected.id}</Heading>+ <Text type="supporting" color="secondary">+ {selected.region}+ </Text>+ </VStack>+ <Divider />+ <VStack gap={2}>+ <Text type="label">Status</Text>+ <Text type="body">{selected.status}</Text>+ <Text type="label">CPU</Text>+ <Text type="body">{selected.cpu}</Text>+ </VStack>+ <Button+ label="Close inspector"+ variant="secondary"+ onClick={() => setSelectedId(null)}+ />+ </VStack>+ </Section>+ )}+ </Drawer>+ </>+ );+ },+};++export const BottomSheet: Story = {+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ const [selected, setSelected] = useState<string[]>(REGIONS.slice(0, 1));+ return (+ <>+ <Button label="Filter regions" onClick={() => setIsOpen(true)} />+ <Drawer+ isOpen={isOpen}+ onClose={() => setIsOpen(false)}+ label="Region filters"+ side="bottom"+ size="40dvh">+ <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+ />+ </VStack>+ </Section>+ </Drawer>+ </>+ );+ },+};diff --git a/packages/lab/src/Drawer/Drawer.doc.mjs b/packages/lab/src/Drawer/Drawer.doc.mjsnew file mode 100644index 0000000000..5cdb4e167b--- /dev/null+++ b/packages/lab/src/Drawer/Drawer.doc.mjs@@ -0,0 +1,157 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @type {import('../../core/src/docs-types').ComponentDoc} */++export const docs = {+ name: 'Drawer',+ displayName: 'Drawer',+ group: 'Drawer',+ category: 'Overlay',+ keywords: ["drawer","side panel","panel","inspector","detail view","overlay","slide","sheet","bottom sheet","sidebar","dialog","collapse","rail"],+ theming: {+ 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).',+ props: [+ {+ name: 'isOpen',+ type: 'boolean',+ description: 'Whether the drawer is open. Fully controlled — pair with onClose.',+ 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.',+ 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.',+ 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.',+ 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.",+ default: "'end'",+ },+ {+ name: 'size',+ 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.",+ default: '400',+ },+ {+ name: 'hasScrim',+ type: 'boolean',+ description: 'Modal scrim behind the drawer. true uses showModal() (top layer, focus trap, scroll lock; clicking the scrim closes — modal only); false uses show() for a non-modal overlay that does NOT trap focus and keeps the page behind interactive.',+ default: 'true',+ },+ {+ name: 'hasCloseButton',+ 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',+ },+ {+ name: 'isCollapsed',+ 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.',+ },+ ],+ 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.',+ 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.' },+ ],+ },+ examples: [+ {+ label: 'Bottom sheet',+ code: `const [isOpen, setIsOpen] = useState(false);+<Drawer+ isOpen={isOpen}+ onClose={() => setIsOpen(false)}+ label="Filters"+ side="bottom"+ size="40dvh">+ <FilterControls />+</Drawer>`,+ },+ {+ label: 'Stacked drill-in (siblings, not nested)',+ code: `const [order, setOrder] = useState(null);+const [lineItem, setLineItem] = useState(null);+<>+ <Drawer+ isOpen={order != null}+ onClose={() => setOrder(null)}+ label="Order details"+ hasScrim={false}>+ <OrderDetails order={order} onSelectLineItem={setLineItem} />+ </Drawer>+ <Drawer+ isOpen={lineItem != null}+ onClose={() => setLineItem(null)}+ label="Line item"+ hasScrim={false}>+ <LineItemDetails item={lineItem} />+ </Drawer>+</>+// Last-opened stacks on top; Escape closes the line item first.`,+ },+ ],+};++/** @type {import('../docs-types').TranslationDoc} */+export const docsZh = {+ usage: {+ description: '用于检查器、详情视图和面板的边缘浮层——"点击表格行查看详情"的模式。按 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 先关闭它。' },+ ],+ },+};++/** @type {import('../docs-types').TranslationDoc} */+export const docsDense = {+ description: 'edge-anchored overlay (native <dialog>): start/end side panel or top/bottom sheet',+ 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.',+ 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.' },+ ],+ },+};diff --git a/packages/lab/src/Drawer/Drawer.test.tsx b/packages/lab/src/Drawer/Drawer.test.tsxnew file mode 100644index 0000000000..31e2496e06--- /dev/null+++ b/packages/lab/src/Drawer/Drawer.test.tsx@@ -0,0 +1,636 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Drawer.test.tsx+ * @input Uses vitest, @testing-library/react, Drawer component+ * @output Unit tests for Drawer component behavior+ * @position Lab testing; validates Drawer.tsx implementation+ *+ * SYNC: When Drawer.tsx changes, update tests to match new behavior+ */++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';++// Mock dialog methods since they're not fully implemented in jsdom+beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });++ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockReturnValue({+ matches: false,+ media: '',+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ }),+ );+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('Drawer', () => {+ it('renders children when open', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Host details">+ Drawer content+ </Drawer>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ expect(screen.getByText('Drawer content')).toBeInTheDocument();+ });++ it('does not show when isOpen is false', () => {+ render(+ <Drawer isOpen={false} onClose={() => {}} label="Host details">+ Hidden content+ </Drawer>,+ );+ const dialog = screen.getByRole('dialog', {hidden: true});+ expect(dialog).not.toHaveAttribute('open');+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();+ });++ it('applies the accessible label', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Host details">+ Content+ </Drawer>,+ );+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Host details');+ });++ describe('modal vs non-modal', () => {+ it('opens with showModal() and aria-modal by default (hasScrim)', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details">+ Content+ </Drawer>,+ );+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalled();+ expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();+ expect(screen.getByRole('dialog')).toHaveAttribute('aria-modal', 'true');+ });++ it('opens with show() and no aria-modal when hasScrim is false', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details" hasScrim={false}>+ Content+ </Drawer>,+ );+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalled();+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();+ expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-modal');+ });+ });++ describe('Escape key', () => {+ it('calls onClose on Escape keydown', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details">+ Content+ </Drawer>,+ );+ fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});+ expect(handleClose).toHaveBeenCalledTimes(1);+ });++ it('calls onClose on Escape in non-modal mode (no native cancel)', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details" hasScrim={false}>+ Content+ </Drawer>,+ );+ fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});+ expect(handleClose).toHaveBeenCalledTimes(1);+ });++ it('prevents the native cancel event and routes through onClose', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details">+ Content+ </Drawer>,+ );+ const cancelEvent = new Event('cancel', {cancelable: true});+ fireEvent(screen.getByRole('dialog'), cancelEvent);+ expect(handleClose).toHaveBeenCalledTimes(1);+ expect(cancelEvent.defaultPrevented).toBe(true);+ });++ it('ignores other keys', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details">+ Content+ </Drawer>,+ );+ fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Enter'});+ expect(handleClose).not.toHaveBeenCalled();+ });+ });++ describe('scrim click', () => {+ it('calls onClose when the ::backdrop (dialog element itself) is clicked', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details">+ Content+ </Drawer>,+ );+ fireEvent.click(screen.getByRole('dialog'));+ expect(handleClose).toHaveBeenCalledTimes(1);+ });++ it('does not close when drawer content is clicked', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details">+ <button type="button">Inside</button>+ </Drawer>,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Inside'}));+ expect(handleClose).not.toHaveBeenCalled();+ });++ it('does not close on self-click when non-modal (no scrim to click)', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details" hasScrim={false}>+ Content+ </Drawer>,+ );+ fireEvent.click(screen.getByRole('dialog'));+ expect(handleClose).not.toHaveBeenCalled();+ });+ });++ describe('close and focus restore', () => {+ function Harness() {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setIsOpen(true)}>+ Open inspector+ </button>+ <Drawer+ isOpen={isOpen}+ onClose={() => setIsOpen(false)}+ label="Inspector">+ <button type="button" onClick={() => setIsOpen(false)}>+ Close inspector+ </button>+ </Drawer>+ </>+ );+ }++ it('delays dialog.close() so the exit transition can play', () => {+ vi.useFakeTimers();+ try {+ render(<Harness />);+ fireEvent.click(screen.getByRole('button', {name: 'Open inspector'}));+ const dialog = screen.getByRole('dialog', {hidden: true});+ expect(dialog).toHaveAttribute('open');++ fireEvent.click(screen.getByRole('button', {name: 'Close inspector'}));+ // Still open while the slide-out transition plays+ expect(dialog).toHaveAttribute('open');+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('restores focus to the trigger element on close', () => {+ vi.useFakeTimers();+ try {+ render(<Harness />);+ const trigger = screen.getByRole('button', {name: 'Open inspector'});+ trigger.focus();+ fireEvent.click(trigger);++ fireEvent.click(screen.getByRole('button', {name: 'Close inspector'}));+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(trigger).toHaveFocus();+ } finally {+ vi.useRealTimers();+ }+ });++ it('can be re-opened after closing', () => {+ vi.useFakeTimers();+ try {+ render(<Harness />);+ const dialog = screen.getByRole('dialog', {hidden: true});++ fireEvent.click(screen.getByRole('button', {name: 'Open inspector'}));+ expect(dialog).toHaveAttribute('open');++ fireEvent.click(screen.getByRole('button', {name: 'Close inspector'}));+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(dialog).not.toHaveAttribute('open');++ fireEvent.click(screen.getByRole('button', {name: 'Open inspector'}));+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(dialog).toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });+ });++ it('focuses the element with data-autofocus on open', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details">+ <button type="button">First</button>+ <button type="button" data-autofocus>+ Second+ </button>+ </Drawer>,+ );+ expect(screen.getByRole('button', {name: 'Second'})).toHaveFocus();+ });++ it('renders the side as a data attribute for theming', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details" side="start">+ Content+ </Drawer>,+ );+ expect(screen.getByRole('dialog')).toHaveAttribute('data-side', 'start');+ });++ describe('sides', () => {+ it.each(['start', 'end', 'top', 'bottom'] as const)(+ 'renders side="%s" with the matching data attribute',+ side => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details" side={side}>+ Content+ </Drawer>,+ );+ expect(screen.getByRole('dialog')).toHaveAttribute('data-side', side);+ },+ );+ });++ describe('size', () => {+ it('applies the default 400px inline budget', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details">+ Content+ </Drawer>,+ );+ expect(screen.getByRole('dialog').getAttribute('style')).toContain(+ '400px',+ );+ });++ it('accepts a number of pixels', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details" size={320}>+ Content+ </Drawer>,+ );+ expect(screen.getByRole('dialog').getAttribute('style')).toContain(+ '320px',+ );+ });++ it('accepts any CSS length string', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details" size="50%">+ Content+ </Drawer>,+ );+ expect(screen.getByRole('dialog').getAttribute('style')).toContain('50%');+ });++ it('applies the size to the block axis for sheets', () => {+ render(+ <Drawer+ isOpen+ onClose={() => {}}+ label="Details"+ side="bottom"+ size="40dvh">+ Content+ </Drawer>,+ );+ expect(screen.getByRole('dialog').getAttribute('style')).toContain(+ '40dvh',+ );+ });++ it('sheets stretch to full viewport width (regression: UA width: fit-content left the sheet content-width in a corner)', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details" side="bottom">+ 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');+ });+ });++ describe('close button', () => {+ it('renders a close button by default when modal', () => {+ const handleClose = vi.fn();+ render(+ <Drawer isOpen onClose={handleClose} label="Details">+ Content+ </Drawer>,+ );+ const closeButton = screen.getByRole('button', {name: 'Close'});+ fireEvent.click(closeButton);+ expect(handleClose).toHaveBeenCalledTimes(1);+ });++ it('does not render a close button by default when non-modal', () => {+ render(+ <Drawer isOpen onClose={() => {}} label="Details" hasScrim={false}>+ Content+ </Drawer>,+ );+ expect(+ screen.queryByRole('button', {name: 'Close'}),+ ).not.toBeInTheDocument();+ });++ it('hides the close button with hasCloseButton={false}', () => {+ render(+ <Drawer+ isOpen+ onClose={() => {}}+ label="Details"+ hasCloseButton={false}>+ Content+ </Drawer>,+ );+ expect(+ screen.queryByRole('button', {name: 'Close'}),+ ).not.toBeInTheDocument();+ });++ it('shows the close button on a non-modal drawer with hasCloseButton', () => {+ render(+ <Drawer+ isOpen+ onClose={() => {}}+ label="Details"+ hasScrim={false}+ hasCloseButton>+ Content+ </Drawer>,+ );+ expect(screen.getByRole('button', {name: 'Close'})).toBeInTheDocument();+ });+ });++ 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 consoleError = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ try {+ render(+ <Drawer+ isOpen+ onClose={() => {}}+ label="Inspector"+ isCollapsed+ onCollapsedChange={() => {}}>+ Content+ </Drawer>,+ );+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('[Drawer]'),+ );+ expect(+ screen.queryByRole('button', {name: 'Expand Inspector'}),+ ).not.toBeInTheDocument();+ } finally {+ consoleError.mockRestore();+ }+ });++ it('dev-warns and ignores isCollapsed on a sheet', () => {+ const consoleError = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ try {+ render(+ <Drawer+ isOpen+ onClose={() => {}}+ label="Inspector"+ side="bottom"+ hasScrim={false}+ isCollapsed+ onCollapsedChange={() => {}}>+ Content+ </Drawer>,+ );+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('[Drawer]'),+ );+ expect(+ screen.queryByRole('button', {name: 'Expand Inspector'}),+ ).not.toBeInTheDocument();+ } finally {+ consoleError.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}>+ First content+ </Drawer>+ <Drawer isOpen onClose={closeSecond} label="Second" hasScrim={false}>+ Second content+ </Drawer>+ </>,+ );++ // Escape inside the first (bottom-of-stack) drawer is ignored.+ fireEvent.keyDown(screen.getByRole('dialog', {name: 'First'}), {+ key: 'Escape',+ });+ expect(closeFirst).not.toHaveBeenCalled();+ expect(closeSecond).not.toHaveBeenCalled();++ // Escape inside the last-opened drawer closes it.+ fireEvent.keyDown(screen.getByRole('dialog', {name: 'Second'}), {+ key: 'Escape',+ });+ expect(closeSecond).toHaveBeenCalledTimes(1);+ expect(closeFirst).not.toHaveBeenCalled();+ });++ function StackHarness() {+ const [outerOpen, setOuterOpen] = useState(true);+ const [innerOpen, setInnerOpen] = useState(true);+ return (+ <>+ <Drawer+ isOpen={outerOpen}+ onClose={() => setOuterOpen(false)}+ label="Outer"+ hasScrim={false}>+ Outer content+ </Drawer>+ <Drawer+ isOpen={innerOpen}+ onClose={() => setInnerOpen(false)}+ label="Inner"+ hasScrim={false}>+ Inner content+ </Drawer>+ </>+ );+ }++ it('closes stacked drawers innermost-first', () => {+ vi.useFakeTimers();+ try {+ render(<StackHarness />);+ const outer = screen.getByRole('dialog', {name: 'Outer'});+ const inner = screen.getByRole('dialog', {name: 'Inner'});++ fireEvent.keyDown(inner, {key: 'Escape'});+ // Inner unregistered when isOpen flipped — outer is now the top.+ fireEvent.keyDown(outer, {key: 'Escape'});+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(inner).not.toHaveAttribute('open');+ expect(outer).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ it('unregisters unmounted drawers so the remaining one becomes top', () => {+ const closeFirst = vi.fn();+ const {rerender} = render(+ <>+ <Drawer isOpen onClose={closeFirst} label="First" hasScrim={false}>+ First content+ </Drawer>+ <Drawer isOpen onClose={() => {}} label="Second" hasScrim={false}>+ Second content+ </Drawer>+ </>,+ );+ rerender(+ <Drawer isOpen onClose={closeFirst} label="First" hasScrim={false}>+ First content+ </Drawer>,+ );+ fireEvent.keyDown(screen.getByRole('dialog', {name: 'First'}), {+ key: 'Escape',+ });+ expect(closeFirst).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/packages/lab/src/Drawer/Drawer.tsx b/packages/lab/src/Drawer/Drawer.tsxnew file mode 100644index 0000000000..248bac4328--- /dev/null+++ b/packages/lab/src/Drawer/Drawer.tsx@@ -0,0 +1,741 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file Drawer.tsx+ * @input Uses React, StyleX, theme tokens, Icon/IconButton, useScrollLock, BaseProps, mergeProps/mergeRefs, themeProps+ * @output Exports Drawer component and DrawerProps+ * @position Lab implementation; consumed by index.ts, tested by Drawer.test.tsx, demonstrated in Storybook+ *+ * 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).+ *+ * Uses the native `<dialog>` element (same precedent as Dialog/MobileNav):+ * - `showModal()` when `hasScrim` (default) — top-layer rendering, focus+ * trapping, `::backdrop`, no z-index management.+ * - `show()` when `hasScrim={false}` — non-modal overlay; the page behind+ * stays interactive (e.g. master-detail inspectors).+ *+ * Entry animation uses `@starting-style` + `transition-behavior:+ * allow-discrete` (see CLAUDE.md dialog-entry pattern); exit slides out+ * before a delayed `dialog.close()` releases the top layer and restores+ * focus to the element that opened the drawer.+ *+ * Sibling drawers coordinate through a module-level LIFO registry: Escape+ * closes only the top (last-opened) drawer, and non-modal drawers stack+ * last-opened-on-top via registry-assigned z-indexes.+ *+ * 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/index.ts (exports if types change)+ * - /apps/storybook/stories/Drawer.stories.tsx (examples and visual coverage)+ */++import {+ useCallback,+ useEffect,+ useId,+ useRef,+ useState,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '@astryxdesign/core';+import {+ borderVars,+ colorVars,+ durationVars,+ easeVars,+ shadowVars,+ spacingVars,+ typeScaleVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import {Icon} from '@astryxdesign/core/Icon';+import {IconButton} from '@astryxdesign/core/IconButton';+import {useScrollLock} from '@astryxdesign/core/hooks';+import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';++// =============================================================================+// LIFO stacking registry (internal)+// =============================================================================++// Module-level registry of currently open drawers, in open order (last entry+// is the top of the stack). SSR-safe: only mutated inside effects. Escape+// handling consults isTopDrawer() so sibling drawers close innermost-first,+// and non-modal (show()) drawers get incrementing z-indexes so the+// last-opened one paints on top; modal drawers rely on the native top+// layer's chronological stacking instead.+type DrawerRegistryEntry = {id: string; close: () => void};++// Without the top layer (hasScrim={false} uses show(), not showModal())+// the panel needs explicit stacking. No z-index token exists in the theme;+// 1000 matches the app-level drawer convention.+const NON_MODAL_BASE_Z = 1000;++const openDrawerStack: DrawerRegistryEntry[] = [];+let registrationCounter = 0;++function registerDrawer(id: string, close: () => void): number {+ openDrawerStack.push({id, close});+ registrationCounter += 1;+ return NON_MODAL_BASE_Z + registrationCounter - 1;+}++function unregisterDrawer(id: string): void {+ const index = openDrawerStack.findIndex(entry => entry.id === id);+ if (index !== -1) {+ openDrawerStack.splice(index, 1);+ }+ if (openDrawerStack.length === 0) {+ registrationCounter = 0;+ }+}++function isTopDrawer(id: string): boolean {+ return openDrawerStack[openDrawerStack.length - 1]?.id === id;+}++// =============================================================================+// Styles+// =============================================================================++// 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;++const styles = stylex.create({+ dialog: {+ // Reset native <dialog> defaults — the dialog element IS the panel.+ position: 'fixed',+ margin: 0,+ padding: 0,+ border: 'none',+ maxWidth: 'none',+ maxHeight: 'none',+ boxSizing: 'border-box',+ flexDirection: 'column',+ backgroundColor: colorVars['--color-background-surface'],+ boxShadow: shadowVars['--shadow-high'],+ overflow: 'hidden',+ overscrollBehavior: 'contain',+ outline: 'none',+ // 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.+ display: 'none',+ transitionProperty: 'transform, max-width, display',+ transitionDuration: durationVars['--duration-medium'],+ transitionTimingFunction: easeVars['--ease-standard'],+ transitionBehavior: 'allow-discrete',+ '@media (prefers-reduced-motion: reduce)': {+ transitionDuration: '0.01s',+ },+ },+ // Open state applied via isOpen prop, not :where([open]) — attribute+ // selectors have zero specificity and can lose to default styles+ // depending on CSS source order (same rationale as Dialog/MobileNav).+ 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.+ end: {+ insetBlockStart: 0,+ insetBlockEnd: 0,+ insetInlineEnd: 0,+ insetInlineStart: 'auto',+ height: '100dvh',+ borderInlineStartWidth: borderVars['--border-width'],+ borderInlineStartStyle: 'solid',+ borderInlineStartColor: colorVars['--color-border'],+ transform: {+ default: 'translateX(100%)',+ ':is([dir="rtl"] *)': 'translateX(-100%)',+ },+ },+ endOpen: {+ transform: {+ default: 'translateX(0)',+ '@starting-style': {+ default: 'translateX(100%)',+ ':is([dir="rtl"] *)': 'translateX(-100%)',+ },+ },+ },+ start: {+ insetBlockStart: 0,+ insetBlockEnd: 0,+ insetInlineStart: 0,+ insetInlineEnd: 'auto',+ height: '100dvh',+ borderInlineEndWidth: borderVars['--border-width'],+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: colorVars['--color-border'],+ transform: {+ default: 'translateX(-100%)',+ ':is([dir="rtl"] *)': 'translateX(100%)',+ },+ },+ startOpen: {+ transform: {+ default: 'translateX(0)',+ '@starting-style': {+ default: 'translateX(-100%)',+ ':is([dir="rtl"] *)': 'translateX(100%)',+ },+ },+ },+ // 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': {+ backgroundColor: colorVars['--color-overlay'],+ backdropFilter: 'blur(2px)',+ opacity: 0,+ transitionProperty: 'opacity',+ transitionDuration: durationVars['--duration-medium'],+ transitionTimingFunction: easeVars['--ease-standard'],+ },+ '@media (prefers-reduced-motion: reduce)': {+ '::backdrop': {+ transitionDuration: '0.01s',+ },+ },+ },+ scrimOpen: {+ '::backdrop': {+ opacity: {+ default: 1,+ '@starting-style': 0,+ },+ },+ },+ // 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).+ content: {+ flexGrow: 1,+ minHeight: 0,+ width: '100%',+ overflowY: 'auto',+ overflowX: 'hidden',+ overscrollBehavior: 'contain',+ touchAction: 'pan-y',+ 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+ // scrollable content.+ controls: {+ position: 'absolute',+ insetBlockStart: spacingVars['--spacing-2'],+ insetInlineEnd: spacingVars['--spacing-2'],+ display: 'flex',+ 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,+ }),+ stackZ: (z: number) => ({+ zIndex: z,+ }),+});++// =============================================================================+// Types+// =============================================================================++export interface DrawerProps extends BaseProps<HTMLDialogElement> {+ /** Ref forwarded to the root <dialog> element */+ ref?: React.Ref<HTMLDialogElement>;++ /**+ * Whether the drawer is open. Fully controlled — pair with `onClose`.+ */+ 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.+ */+ onClose: () => 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';++ /**+ * 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.+ * @default 400+ */+ size?: number | string;++ /**+ * 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.+ */+ label: string;++ /**+ * Whether to render a modal scrim behind the drawer.+ * - `true` (default) — `showModal()`: top layer, focus trap, body scroll+ * lock, click-outside-to-close.+ * - `false` — `show()`: non-modal overlay; the page behind stays+ * interactive. Escape still closes while focus is inside the drawer.+ * @default true+ */+ hasScrim?: boolean;++ /**+ * 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+ */+ 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.+ */+ children: ReactNode;++ /**+ * Test ID for the root element.+ */+ 'data-testid'?: string;+}++// =============================================================================+// Component+// =============================================================================++/**+ * An edge-anchored overlay panel for inspectors, detail views, and sheets.+ *+ * 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`.+ *+ * @example+ * ```+ * const [selected, setSelected] = useState(null);+ * <Drawer+ * isOpen={selected != null}+ * onClose={() => setSelected(null)}+ * label={`Details: ${selected?.name}`}>+ * <HostDetails host={selected} />+ * </Drawer>+ * ```+ */+export function Drawer({+ isOpen,+ onClose,+ side = 'end',+ size = 400,+ label,+ hasScrim = true,+ hasCloseButton,+ isCollapsed,+ onCollapsedChange,+ children,+ xstyle,+ className,+ style,+ ref,+ ...props+}: DrawerProps) {+ const dialogRef = useRef<HTMLDialogElement>(null);+ const closeTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);+ // Element focused when the drawer opened — restored on close.+ const triggerElementRef = useRef<HTMLElement | null>(null);+ // Registry identity + latest onClose (stable across re-renders so the+ // registration effect doesn't churn on every onClose identity change).+ const drawerId = useId();+ const onCloseRef = useRef(onClose);+ useEffect(() => {+ onCloseRef.current = onClose;+ }, [onClose]);+ // 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 (repo idiom:+ // console.error, see BaseTable plugin errors).+ const hasInvalidCollapse = isCollapsed != null && !canCollapse;+ useEffect(() => {+ if (hasInvalidCollapse) {+ console.error(+ '[Drawer] `isCollapsed` is only supported for non-modal drawers ' ++ '(hasScrim={false}) with side="start" or side="end". The prop is ' ++ 'ignored.',+ );+ }+ }, [hasInvalidCollapse]);++ // Open/close the native dialog. close() is delayed so the slide-out+ // transition can play; focus restore happens after close() because a+ // modal dialog makes the rest of the document inert (focus() on the+ // trigger would silently fail while the dialog is still open).+ useEffect(() => {+ const dialog = dialogRef.current;+ if (!dialog) {+ return;+ }++ if (closeTimeoutRef.current) {+ clearTimeout(closeTimeoutRef.current);+ closeTimeoutRef.current = null;+ }++ if (isOpen) {+ if (!dialog.open) {+ triggerElementRef.current =+ document.activeElement as HTMLElement | null;+ if (hasScrim) {+ dialog.showModal();+ } else {+ dialog.show();+ }+ // React's autoFocus calls .focus() during commit, before the dialog+ // is shown, so it silently fails — honor data-autofocus instead+ // (same contract as Dialog).+ const autofocusTarget =+ dialog.querySelector<HTMLElement>('[data-autofocus]');+ if (autofocusTarget) {+ autofocusTarget.focus();+ }+ }+ } else if (dialog.open) {+ const duration = window.matchMedia('(prefers-reduced-motion: reduce)')+ .matches+ ? 10+ : 250;+ closeTimeoutRef.current = setTimeout(() => {+ dialog.close();+ // Return focus to the element that opened the drawer.+ triggerElementRef.current?.focus();+ triggerElementRef.current = null;+ }, duration);+ }++ return () => {+ if (closeTimeoutRef.current) {+ clearTimeout(closeTimeoutRef.current);+ closeTimeoutRef.current = null;+ }+ };+ }, [isOpen, hasScrim]);++ // Close the native dialog on unmount if it's still open. When the drawer+ // is mounted inside an <Activity> that flips to mode="hidden", React runs+ // effect cleanups (with a stale isOpen) instead of re-running the effect+ // with isOpen=false — leaving the <dialog> `open` would skip showModal()+ // on the next open and the drawer could never be re-opened (see+ // MobileNavReopen.test.tsx for the original repro). This must be a+ // separate unmount-only effect: putting it in the open/close effect above+ // would close the dialog on every isOpen flip and cut off the delayed+ // slide-out close.+ useEffect(() => {+ const dialog = dialogRef.current;+ return () => {+ if (dialog?.open) {+ dialog.close();+ }+ };+ }, []);++ // LIFO registry membership: register on open, unregister on close or+ // unmount. The returned z-index stacks non-modal siblings in open order.+ useEffect(() => {+ if (!isOpen) {+ return;+ }+ const z = registerDrawer(drawerId, () => onCloseRef.current());+ setStackZ(z);+ return () => unregisterDrawer(drawerId);+ }, [isOpen, drawerId]);++ // Lock body scroll while a modal drawer is open (iOS Safari workaround).+ useScrollLock(isOpen && hasScrim);++ // Escape closes. The native `cancel` event only fires for showModal();+ // this 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) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ if (isTopDrawer(drawerId)) {+ onClose();+ }+ }+ };++ dialog.addEventListener('keydown', handleKeyDown);+ return () => dialog.removeEventListener('keydown', handleKeyDown);+ }, [isOpen, onClose, drawerId]);++ // Native cancel event (browser Escape handling) — prevent the browser+ // from closing the dialog directly and route through onClose 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();+ }+ },+ [onClose, drawerId],+ );++ // 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) {+ onClose();+ }+ },+ [hasScrim, onClose],+ );++ 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];++ // Filter out native `open` to prevent InvalidStateError when passed+ const {open: _open, ...safeProps} = props as Record<string, unknown>;++ return (+ <dialog+ ref={mergeRefs(ref, dialogRef)}+ aria-label={label}+ aria-modal={hasScrim ? 'true' : undefined}+ onClick={handleClick}+ onCancel={handleCancel}+ {...mergeProps(+ themeProps('drawer', {side}),+ stylex.props(+ styles.dialog,+ sideStyle,+ isSheet+ ? dynamicStyles.blockSize(sizeValue)+ : dynamicStyles.inlineSize(sizeValue),+ isOpen && styles.open,+ isOpen && sideOpenStyle,+ hasScrim ? styles.scrim : dynamicStyles.stackZ(stackZ),+ hasScrim && isOpen && styles.scrimOpen,+ collapsed && styles.collapsedRail,+ xstyle,+ ),+ className,+ style,+ )}+ {...safeProps}>+ {/* 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)}>+ {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>+ )+ )}+ </dialog>+ );+}++Drawer.displayName = 'Drawer';diff --git a/packages/lab/src/Drawer/index.ts b/packages/lab/src/Drawer/index.tsnew file mode 100644index 0000000000..64b780d3e5--- /dev/null+++ b/packages/lab/src/Drawer/index.ts@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file index.ts+ * @input Drawer.tsx+ * @output Re-exports Drawer component and DrawerProps type+ * @position Lab entry point for the Drawer directory+ */++export {Drawer} from './Drawer';+export type {DrawerProps} from './Drawer';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 1ed041621f..00d305072a 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -31,6 +31,9 @@ export {type ChatReasoningProps,} from './ChatReasoning/ChatReasoning';+// Drawer — experimental overlay panel+export {Drawer, type DrawerProps} from './Drawer';+// Schedule — experimental full-calendar viewsexport * from './Schedule';