An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): explore shared-dialog BottomSheetSwitcher API (#5023)
Xinzi Zhoufb0b7a99f198
diff --git a/apps/storybook/stories/BottomSheetSwitcher.stories.tsx b/apps/storybook/stories/BottomSheetSwitcher.stories.tsxnew file mode 100644index 0000000000..0bb8dbd620--- /dev/null+++ b/apps/storybook/stories/BottomSheetSwitcher.stories.tsx@@ -0,0 +1,251 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {BottomSheet, BottomSheetSwitcher} 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 {HStack, VStack} from '@astryxdesign/core/Stack';+import {Text} from '@astryxdesign/core/Text';+import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';++const meta: Meta<typeof BottomSheetSwitcher> = {+ title: 'Lab/BottomSheetSwitcher',+ component: BottomSheetSwitcher,+ tags: ['autodocs'],+ parameters: {+ layout: 'fullscreen',+ docs: {+ story: {inline: false, height: '560px'},+ },+ },+ decorators: [+ Story => (+ <div style={{minHeight: 480, padding: 32}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof BottomSheetSwitcher>;+type NotificationSheetHeight = 'hug' | 'capped';++interface NotificationOverviewSheetProps {+ height: NotificationSheetHeight;+ onCancel: () => void;+ onContinue: () => void;+}++function NotificationOverviewSheet({+ height,+ onCancel,+ onContinue,+}: NotificationOverviewSheetProps) {+ return (+ <BottomSheet+ sheetId="overview"+ label="Set up notifications"+ height={height}>+ <Section padding={4}>+ <VStack gap={4}>+ <VStack gap={1}>+ <Heading level={3}>Set up notifications</Heading>+ <Text type="supporting" color="secondary">+ Step 1 of 3+ </Text>+ </VStack>+ <Divider />+ <Text type="supporting" color="secondary">+ Stay informed about activity that matters without checking back+ throughout the day.+ </Text>+ <VStack gap={3}>+ <VStack gap={1}>+ <Text type="label">Important activity</Text>+ <Text type="supporting" color="secondary">+ Know when someone mentions you or needs your attention.+ </Text>+ </VStack>+ <VStack gap={1}>+ <Text type="label">Timely reminders</Text>+ <Text type="supporting" color="secondary">+ Get a reminder before work reaches its due date.+ </Text>+ </VStack>+ <VStack gap={1}>+ <Text type="label">Useful summaries</Text>+ <Text type="supporting" color="secondary">+ Catch up on anything you may have missed.+ </Text>+ </VStack>+ </VStack>+ <HStack gap={2} hAlign="end">+ <Button label="Cancel" variant="secondary" onClick={onCancel} />+ <Button label="Continue" onClick={onContinue} />+ </HStack>+ </VStack>+ </Section>+ </BottomSheet>+ );+}++interface NotificationFrequencySheetProps {+ height: NotificationSheetHeight;+ onBack: () => void;+ onContinue: () => void;+}++function NotificationFrequencySheet({+ height,+ onBack,+ onContinue,+}: NotificationFrequencySheetProps) {+ const [frequency, setFrequency] = useState('daily');++ return (+ <BottomSheet+ sheetId="frequency"+ label="Notification frequency"+ height={height}>+ <Section padding={4}>+ <VStack gap={4}>+ <VStack gap={1}>+ <Heading level={3}>How often?</Heading>+ <Text type="supporting" color="secondary">+ Step 2 of 3+ </Text>+ </VStack>+ <Divider />+ <RadioList+ label="Notification frequency"+ isLabelHidden+ value={frequency}+ onChange={setFrequency}>+ <RadioListItem label="Immediately" value="immediately" />+ <RadioListItem label="Daily" value="daily" />+ <RadioListItem label="Weekly" value="weekly" />+ </RadioList>+ <HStack gap={2} hAlign="end">+ <Button label="Back" variant="secondary" onClick={onBack} />+ <Button label="Continue" onClick={onContinue} />+ </HStack>+ </VStack>+ </Section>+ </BottomSheet>+ );+}++interface NotificationChannelsSheetProps {+ height: NotificationSheetHeight;+ onBack: () => void;+ onFinish: () => void;+}++function NotificationChannelsSheet({+ height,+ onBack,+ onFinish,+}: NotificationChannelsSheetProps) {+ const [email, setEmail] = useState(true);+ const [pushNotifications, setPushNotifications] = useState(true);+ const [textMessages, setTextMessages] = useState(false);++ return (+ <BottomSheet+ sheetId="channels"+ label="Notification channels"+ height={height}>+ <Section padding={4}>+ <VStack gap={4}>+ <VStack gap={1}>+ <Heading level={3}>Where should we notify you?</Heading>+ <Text type="supporting" color="secondary">+ Step 3 of 3+ </Text>+ </VStack>+ <Divider />+ <Text type="supporting" color="secondary">+ Choose any combination. You can change these preferences later.+ </Text>+ <VStack gap={2}>+ <CheckboxInput label="Email" value={email} onChange={setEmail} />+ <CheckboxInput+ label="Push notifications"+ value={pushNotifications}+ onChange={setPushNotifications}+ />+ <CheckboxInput+ label="Text messages"+ value={textMessages}+ onChange={setTextMessages}+ />+ </VStack>+ <HStack gap={2} hAlign="end">+ <Button label="Back" variant="secondary" onClick={onBack} />+ <Button label="Finish" onClick={onFinish} />+ </HStack>+ </VStack>+ </Section>+ </BottomSheet>+ );+}++interface MultiStepSwitcherExampleProps {+ height: NotificationSheetHeight;+ hasScrim?: boolean;+}++function MultiStepSwitcherExample({+ height,+ hasScrim = true,+}: MultiStepSwitcherExampleProps) {+ const [activeSheet, setActiveSheet] = useState<string | null>(null);++ return (+ <>+ <Button+ label="Set up notifications"+ onClick={() => setActiveSheet('overview')}+ />+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}+ hasScrim={hasScrim}>+ <NotificationOverviewSheet+ height={height}+ onCancel={() => setActiveSheet(null)}+ onContinue={() => setActiveSheet('frequency')}+ />+ <NotificationFrequencySheet+ height={height}+ onBack={() => setActiveSheet('overview')}+ onContinue={() => setActiveSheet('channels')}+ />+ <NotificationChannelsSheet+ height={height}+ onBack={() => setActiveSheet('frequency')}+ onFinish={() => setActiveSheet(null)}+ />+ </BottomSheetSwitcher>+ </>+ );+}++export const HugContent: Story = {+ name: 'Hug content',+ render: () => <MultiStepSwitcherExample height="hug" />,+};++export const Capped: Story = {+ render: () => <MultiStepSwitcherExample height="capped" />,+};++export const NoScrim: Story = {+ name: 'No scrim',+ render: () => <MultiStepSwitcherExample height="hug" hasScrim={false} />,+};diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex dfb3d84581..00b6d885bc 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -11,7 +11,11 @@* SYNC: When modified, update this header*/-export {useFocusTrap} from './useFocusTrap';+export {+ hasActiveFocusTrapEscape,+ isImeKeyEvent,+ useFocusTrap,+} from './useFocusTrap';export type {UseFocusTrapOptions, UseFocusTrapReturn} from './useFocusTrap';export {useAnnounce} from './useAnnounce';diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsxindex 6d6aa33267..4ff4052dca 100644--- a/packages/core/src/hooks/useFocusTrap.test.tsx+++ b/packages/core/src/hooks/useFocusTrap.test.tsx@@ -192,6 +192,22 @@ describe('useFocusTrap tabbable model (infra-8)', () => {fireEvent.keyDown(document, {key: 'Tab'});expect(screen.getByTestId('first')).toHaveFocus();});++ it('keeps a programmatic focus target when the trap has no tabbable controls', () => {+ render(+ <Trap>+ <div tabIndex={-1} data-testid="programmatic-target">+ Read-only dialog content+ </div>+ </Trap>,+ );+ const target = screen.getByTestId('programmatic-target');+ target.focus();++ expect(fireEvent.keyDown(target, {key: 'Tab'})).toBe(false);+ expect(target).toHaveFocus();+ expect(screen.getByTestId('outside')).not.toHaveFocus();+ });});describe('FOCUSABLE_SELECTOR href matching', () => {diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex d81f709aac..dae073bbc6 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -332,12 +332,21 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(lastFocusRef.current = target as Element;} else if (isKeyboardNavigationRef.current) {// Focus escaped via keyboard - redirect it back- focusFirstDescendant(container);+ const focusedFirst = focusFirstDescendant(container);// If we're back at the same element (Shift+Tab from first element),// try focusing the last element instead- if (lastFocusRef.current === document.activeElement) {+ if (focusedFirst && lastFocusRef.current === document.activeElement) {focusLastDescendant(container);+ } else if (+ !focusedFirst &&+ lastFocusRef.current instanceof HTMLElement &&+ container.contains(lastFocusRef.current)+ ) {+ // A modal surface may intentionally have no tabbable controls and+ // place initial focus on a tabIndex={-1} heading or panel. Preserve+ // that programmatic focus target instead of letting Tab escape.+ attemptFocus(lastFocusRef.current);}lastFocusRef.current = document.activeElement;@@ -410,6 +419,15 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(const focusable = getFocusableElements(container);if (focusable.length === 0) {+ // There is nowhere to advance to. Keep focus on the current+ // programmatic target (for example a dialog panel with tabIndex=-1)+ // rather than allowing the browser to move into background content.+ event.preventDefault();+ const active = document.activeElement;+ if (active instanceof HTMLElement && container.contains(active)) {+ lastFocusRef.current = active;+ }+ isKeyboardNavigationRef.current = false;return;}diff --git a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs b/packages/lab/src/BottomSheet/BottomSheet.doc.mjsindex 7b3dd99f73..bfe69ea7e3 100644--- a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs@@ -26,21 +26,25 @@ export const docs = {targets: [{className: 'astryx-bottom-sheet', visualProps: []}],},description:- 'A mobile touch sheet that rises from the bottom edge, with animated entrance and exit, a grab handle, drag-to-resize snap points, and swipe-to-dismiss. Built on a native modal <dialog>.',+ "A mobile touch sheet that rises from the bottom edge, with animated entrance and exit, a grab handle, drag-to-resize snap points, and swipe-to-dismiss. A standalone sheet owns a native <dialog>; inside BottomSheetSwitcher it renders a panel in the switcher's shared dialog. In both modes, ref and shared DOM props target the visual panel <div>.",props: [{name: 'isOpen',type: 'boolean',description:- 'Whether the sheet is open. Fully controlled; pair with onOpenChange.',- required: true,+ 'Whether a standalone sheet is open. Fully controlled; pair with onOpenChange. Omit inside BottomSheetSwitcher.',},{name: 'onOpenChange',type: '(isOpen: boolean) => void',description:- 'Called when the sheet opens or closes. The boolean is the requested next state (false on Escape, scrim click, or a swipe past the dismiss threshold). The caller owns the open state.',- required: true,+ 'For a standalone sheet, called when it requests an open-state change (false on Escape, scrim click, or a swipe past the dismiss threshold). Omit inside BottomSheetSwitcher.',+ },+ {+ name: 'sheetId',+ type: 'string',+ description:+ 'Unique ID for this sheet inside BottomSheetSwitcher. The switcher opens it when activeSheet matches. Omit isOpen and onOpenChange when sheetId is used.',},{name: 'label',@@ -67,7 +71,7 @@ export const docs = {name: 'hasScrim',type: 'boolean',description:- 'Whether to render a scrim, the semi-transparent overlay that covers and blocks the background, behind the sheet. true (default) uses showModal(): top layer, focus trap, ::backdrop scrim, body scroll lock, and tap-scrim-to-dismiss, with the background inert. false still renders a viewport-anchored overlay above the page, not inline content, but uses show() with no scrim, leaving the page behind interactive and scrollable. Escape still closes while focus is inside, and drag/flick-to-dismiss still work.',+ 'For a standalone BottomSheet, whether to render a scrim—the semi-transparent overlay that covers and blocks the background. true (default) uses showModal(): top layer, focus trap, ::backdrop scrim, body scroll lock, and tap-scrim-to-dismiss, with the background inert. false uses show() with no scrim, leaving the page behind interactive and scrollable. For a multi-step flow, configure hasScrim on BottomSheetSwitcher instead; it owns one shared dialog across every child.',default: 'true',},],@@ -85,6 +89,11 @@ export const docs = {description:'Keep the caller as the source of truth: derive isOpen from state and clear it in onOpenChange.',},+ {+ guidance: true,+ description:+ 'Use BottomSheetSwitcher with a unique sheetId per sheet for multi-step flows; it owns one shared dialog while the new top sheet enters and a taller previous sheet simultaneously aligns downward behind a shorter step, then fades it afterward.',+ },{guidance: true,description:@@ -139,6 +148,23 @@ export const docs = {height="hug"><ShareActions /></BottomSheet>`,+ },+ {+ label: 'Multi-step flow (one sheet at a time)',+ code: `const [activeSheet, setActiveSheet] = useState(null);+<>+ <Button label="Start" onClick={() => setActiveSheet('details')} />+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}>+ <BottomSheet sheetId="details" label="Details">+ <Button label="Continue" onClick={() => setActiveSheet('confirm')} />+ </BottomSheet>+ <BottomSheet sheetId="confirm" label="Confirm">+ <Button label="Back" onClick={() => setActiveSheet('details')} />+ </BottomSheet>+ </BottomSheetSwitcher>+</>`,},{label: 'Mobile keyboard (a long form)',@@ -193,6 +219,11 @@ export const docsDense = {guidance: true,description: 'Derive isOpen from state; clear it in onOpenChange.',},+ {+ guidance: true,+ description:+ 'Use BottomSheetSwitcher + sheetId for mutually exclusive multi-step flows in one shared dialog.',+ },{guidance: true,description:diff --git a/packages/lab/src/BottomSheet/BottomSheet.test.tsx b/packages/lab/src/BottomSheet/BottomSheet.test.tsxindex 9082a73604..023caa30a4 100644--- a/packages/lab/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/lab/src/BottomSheet/BottomSheet.test.tsx@@ -10,8 +10,8 @@*/import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';-import {render, screen, fireEvent, act} from '@testing-library/react';-import {useState} from 'react';+import {act, render, screen, fireEvent} from '@testing-library/react';+import {createRef, useState} from 'react';import {BottomSheet} from './BottomSheet';// jsdom doesn't implement <dialog> open/close or pointer capture; stub them.@@ -191,6 +191,35 @@ describe('BottomSheet', () => {expect(screen.getByText('Sheet content')).toBeInTheDocument();});+ it('forwards DOM props and refs to the visual panel, not the dialog host', () => {+ const panelRef = createRef<HTMLDivElement>();+ const onClick = vi.fn();+ render(+ <BottomSheet+ ref={panelRef}+ isOpen+ onOpenChange={() => {}}+ label="Filters"+ data-testid="filters-panel"+ data-sheet-owner="search"+ className="custom-panel"+ onClick={onClick}>+ Content+ </BottomSheet>,+ );++ const panel = screen.getByTestId('filters-panel');+ const dialog = screen.getByRole('dialog');+ expect(panelRef.current).toBe(panel);+ expect(panel.tagName).toBe('DIV');+ expect(panel).toHaveClass('astryx-bottom-sheet', 'custom-panel');+ expect(panel).toHaveAttribute('data-sheet-owner', 'search');+ expect(dialog).not.toHaveAttribute('data-testid');++ fireEvent.click(panel);+ expect(onClick).toHaveBeenCalledTimes(1);+ });+it('keeps consumer content as the last scroll-body child', () => {render(<BottomSheet isOpen onOpenChange={() => {}} label="Filters">@@ -904,21 +933,15 @@ describe('BottomSheet', () => {);}- it('restores focus to the opener after close', async () => {- vi.useFakeTimers();- try {- render(<Harness />);- const opener = screen.getByRole('button', {name: 'Open sheet'});- opener.focus();- fireEvent.click(opener);- fireEvent.click(screen.getByRole('button', {name: 'Done'}));- await act(async () => {- vi.runAllTimers();- });- expect(document.activeElement).toBe(opener);- } finally {- vi.useRealTimers();- }+ it('restores focus to the opener after close', () => {+ render(<Harness />);+ const opener = screen.getByRole('button', {name: 'Open sheet'});+ opener.focus();+ fireEvent.click(opener);+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ finishSheetExit();++ expect(document.activeElement).toBe(opener);});});diff --git a/packages/lab/src/BottomSheet/BottomSheet.tsx b/packages/lab/src/BottomSheet/BottomSheet.tsxindex ded849e47a..738cf821b9 100644--- a/packages/lab/src/BottomSheet/BottomSheet.tsx+++ b/packages/lab/src/BottomSheet/BottomSheet.tsx@@ -4,47 +4,30 @@/*** @file BottomSheet.tsx- * @input Uses React, StyleX, theme tokens, core hooks (useScrollLock), utils, useMobileKeyboard, useSheetGestures+ * @input Uses React, StyleX, core hooks/utils, BottomSheetPanel, BottomSheetSwitcherContext* @output Exports BottomSheet component and BottomSheetProps- * @position Lab implementation; consumed by index.ts, tested by BottomSheet.test.tsx, demonstrated in Storybook+ * @position Public BottomSheet router plus private standalone/switcher hosts*- * A mobile touch surface that rises from the bottom edge: grab handle, snap- * points, and swipe-to-dismiss. It owns a native `<dialog>` directly and- * composes core primitives (`useScrollLock`, `<dialog>.showModal()` for the- * top layer + focus trap, a `::backdrop` scrim) rather than delegating to a- * heavier overlay component — so it controls its own sizing and can render a- * full-height transparent shell with the visible sheet bottom-anchored inside.- * That shell is what lets the sheet translate freely (including a little past- * fully-open) without clipping against a fixed dialog edge.- *- * Form controls stay usable above mobile on-screen keyboards: the outer sheet- * keeps its measured height while visual-viewport overlap extends the internal- * scroll range and focused controls scroll into view. Short sheets lift only- * far enough to expose a usable focus area. Starting sheet travel or closing- * the sheet blurs the field to dismiss the keyboard.- *- * `hasScrim` picks the presentation: `true` (default) uses `showModal()` (top- * layer, focus trap, scrim, scroll lock, background inert); `false` uses- * `show()` for a non-modal sheet with no scrim, leaving the page behind- * interactive and scrollable (the transparent shell is pointer-events:none so- * taps pass through). Both modes keep the native dialog presented but inert- * until the slide-out transition ends.- *- * The drag/snap/dismiss machinery lives in `useSheetGestures`; the offset- * geometry lives in the pure, tested `snapOffsets` module. Both are internal- * to BottomSheet and not exported from the lab entry point.+ * BottomSheet selects one of two focused hosts. A standalone host owns its+ * native dialog lifecycle; a switcher item participates in the parent's shared+ * dialog and transition state machine. Both render the same BottomSheetPanel,+ * which owns sheet presentation, gestures, mobile-keyboard accommodation, and+ * motion completion.** SYNC: When modified, update these files to stay in sync:- * - /packages/lab/src/BottomSheet/BottomSheet.doc.mjs (props table, features, usage)- * - /packages/lab/src/BottomSheet/BottomSheet.test.tsx (tests for new/changed behavior)- * - /packages/lab/src/BottomSheet/index.ts (exports if types change)- * - /apps/storybook/stories/BottomSheet.stories.tsx (examples and visual coverage)+ * - /packages/lab/src/BottomSheet/BottomSheetPanel.tsx+ * - /packages/lab/src/BottomSheet/BottomSheet.doc.mjs+ * - /packages/lab/src/BottomSheet/BottomSheet.test.tsx+ * - /packages/lab/src/BottomSheet/BottomSheetSwitcher.tsx+ * - /packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx+ * - /apps/storybook/stories/BottomSheet.stories.tsx*/import {useCallback,+ useContext,useEffect,- useMemo,+ useLayoutEffect,useRef,useState,type ReactNode,@@ -55,76 +38,23 @@ import {colorVars,durationVars,easeVars,- radiusVars,- shadowVars,- sizeVars,- spacingVars,} from '@astryxdesign/core/theme/tokens.stylex';import {useDevWarning, useScrollLock} from '@astryxdesign/core/hooks';-import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';-import {useMobileKeyboard} from './useMobileKeyboard';-import {useSheetGestures} from './useSheetGestures';--// A non-modal sheet (hasScrim={false}) uses show() instead of showModal(), so-// it isn't in the native top layer and needs an explicit z-index to sit above-// page content. No z-index token exists in the theme; 1000 matches the Drawer-// / app-level overlay convention.-const NON_MODAL_Z = 1000;--// Detent fractions of the viewport, ascending (peek / mid / full). Detents-// that land within DETENT_DEDUP_PX of each other (e.g. a hug height next to a-// snap) are de-duped in the gesture hook, and any taller than the sheet are-// dropped, so a full set is safe to offer. The shortest is a glance "peek";-// the scrim hides as the sheet collapses onto it (see onScrimOpacity).-const SNAP_FRACTIONS = [0.14, 0.5, 0.92];--/**- * Height budget for each named size, as a fraction of the viewport:- * - `hug` — fits its content, never taller than 92%.- * - `capped` — a scrolling mid-height panel (62%).- * - `tall` — a pinned near-full panel (92%); use when content streams in so- * the sheet doesn't resize under the user.- */-const HEIGHT_BUDGETS = {- hug: '92dvh', // upper bound only; the sheet hugs its content beneath it- capped: '62dvh',- tall: '92dvh',-} as const;--export type BottomSheetHeight = keyof typeof HEIGHT_BUDGETS;--// px the sheet extends below its budget as reserved padding, revealed by an-// upward overdrag rather than showing a gap.-// SYNC: must match OVERSCROLL_MAX in useSheetGestures.ts (the drag cap).-const OVERSCROLL_PADDING = 48;--// Chrome Android needs trailing room after the final input when its suggestion-// UI appears. This single value controls both the CSS scroll padding and the-// hook's viewport calculations.-const MOBILE_KEYBOARD_BOTTOM_CLEARANCE = 48;+import {+ BottomSheetPanel,+ type BottomSheetPanelMotion,+ type BottomSheetPanelState,+} from './BottomSheetPanel';+import {+ BottomSheetSwitcherContext,+ type BottomSheetSwitcherContextValue,+ type BottomSheetSwitcherPhase,+} from './BottomSheetSwitcherContext';-/**- * Default snap detents in px, resolved against the *visual* viewport (like iOS- * detents), so a mid rest point is ~half the screen regardless of the sheet's- * own height budget. Read lazily at drag start (no persistent listener) so it- * reflects the live viewport after a rotation or the virtual keyboard opening.- * SSR-safe: returns `[]` off the client.- */-function defaultSnapHeights(): number[] {- if (typeof window === 'undefined') {- return [];- }- const vh = window.visualViewport?.height ?? window.innerHeight;- return SNAP_FRACTIONS.map(f => f * vh);-}+export type {BottomSheetHeight} from './BottomSheetPanel';+import type {BottomSheetHeight} from './BottomSheetPanel';const styles = stylex.create({- // A full-viewport transparent shell: it supplies the top layer, focus trap,- // and ::backdrop scrim but paints nothing and doesn't clip, so the sheet can- // translate past fully-open without hitting a fixed dialog edge. It stays- // hit-testable (no pointer-events:none) so taps on the transparent area- // reach onClick and dismiss the sheet — the positioner below passes those- // taps through to here, while the sheet itself re-enables pointer events.dialog: {position: 'fixed',inset: 0,@@ -143,33 +73,12 @@ const styles = stylex.create({dialogOpen: {display: 'block',},- // Non-modal (hasScrim={false}) shell: the full-viewport dialog must NOT- // intercept taps, or it would swallow every click meant for the interactive- // page behind it. Pointer events pass straight through the transparent shell- // (and the positioner, which is already none) to the page; the sheet surface- // re-enables them (styles.sheet -> pointerEvents:auto). This also inherently- // removes tap-outside-to-dismiss, which is correct when there's no scrim.- // show() doesn't use the native top layer, so an explicit z-index keeps the- // sheet above page content.- //- // Size to 100% (of the positioning context) rather than the base 100dvw/dvh:- // a modal sheet is in the top layer so its `fixed` box is always the viewport,- // but a non-modal `show()` dialog is a normal `fixed` element, so if any- // ancestor establishes a containing block (transform / filter / contain —- // e.g. Storybook's Docs preview wrapper), viewport units measured from that- // shifted origin overflow and mis-anchor the sheet. `inset:0 + 100%` fills- // whatever the containing block is, so the sheet stays correctly anchored.dialogNonModal: {pointerEvents: 'none',- zIndex: NON_MODAL_Z,+ zIndex: 1000,width: '100%',height: '100%',},- // Opacity is a var the drag handler lowers toward dismissal;- // @starting-style animates the entrance fade-in.- // Plain dim, no backdrop blur: bottom sheets on both Material and iOS dim- // without blurring, so this intentionally diverges from the other overlays- // (Drawer/Dialog/MobileNav/Lightbox, which share a blur(2px) scrim).scrim: {'::backdrop': {backgroundColor: colorVars['--color-overlay'],@@ -193,195 +102,81 @@ const styles = stylex.create({display: 'flex',justifyContent: 'center',pointerEvents: 'none',- // SYNC: custom property is set by useMobileKeyboard.ts. Applying the- // keyboard-only lift outside the measured sheet keeps hug height and drag- // detents stable.transform: 'translateY(calc(0px - var(--_sheet-keyboard-lift, 0px)))',},- sheet: {- pointerEvents: 'auto',- boxSizing: 'border-box',- display: 'flex',- flexDirection: 'column',- minHeight: 0,- width: '100%',- maxWidth: 640,- backgroundColor: colorVars['--color-background-surface'],- borderStartStartRadius: radiusVars['--radius-container'],- borderStartEndRadius: radiusVars['--radius-container'],- boxShadow: shadowVars['--shadow-high'],- // tabIndex=-1 makes this the initial focus target; it's a programmatic- // landing spot, not an interactive control, so suppress the focus ring.- outline: 'none',- overflow: 'hidden',- // Reserved overdrag zone: extra bottom padding (surface bg + home-indicator- // clearance) that a small upward drag reveals, negated by an equal negative- // margin so at rest it sits BELOW the fold — the true sheet stays pinned to- // the bottom edge. Budget heights add the same amount back (see `budget` /- // `hugHeight`) so the visible height is unchanged.- paddingBlockEnd: `calc(env(safe-area-inset-bottom, 0px) + ${OVERSCROLL_PADDING}px)`,- marginBlockEnd: `${-OVERSCROLL_PADDING}px`,- transform: {- default: 'translateY(0)',- '@starting-style': 'translateY(100%)',- },- transitionProperty: 'transform',- transitionDuration: durationVars['--duration-medium'],- transitionTimingFunction: easeVars['--ease-standard'],- willChange: 'transform',- '@media (prefers-reduced-motion: reduce)': {- transitionDuration: '0.01s',- },- },- sheetClosing: {- transform: 'translateY(100%)',- },- sheetExiting: {- pointerEvents: 'none',- },- handleBar: {- flexShrink: 0,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- // The whole strip is the drag target: 48px (top of the spacing scale,- // above Apple's 44px / WCAG 2.5.8's 24px), no overlap tricks.- height: spacingVars['--spacing-12'],- touchAction: 'none',- cursor: 'grab',- },- handlePill: {- width: sizeVars['--size-element-lg'],- height: spacingVars['--spacing-1'],- borderRadius: radiusVars['--radius-full'],- backgroundColor: colorVars['--color-border'],- },- body: {- flexGrow: 1,- minHeight: 0,- overflowY: 'auto',- // Set from visualViewport while the on-screen keyboard/browser chrome- // covers the stable sheet. The generated tail below extends the internal- // scroll range; the outer sheet and this flex item's box stay unchanged.- scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,- // No overscroll bounce inside the sheet — a pull-down at the top edge is- // handed off to the sheet drag (see useSheetGestures' touch handling)- // rather than rubber-banding the content.- overscrollBehavior: 'none',- // Allow native vertical scrolling of the content; the at-top pull-down is- // intercepted via a non-passive touchmove listener, not by blocking- // touch-action (which would suppress scrolling entirely).- touchAction: 'pan-y',- // Extend the scroll range without inserting an element after public- // children. Direct children must retain their :last-child semantics for- // Astryx container edge compensation and consumer-authored selectors.- '::after': {- content: '""',- display: 'block',- // SYNC: custom property is set by useMobileKeyboard.ts.- blockSize: 'var(--_sheet-keyboard-inset, 0px)',- pointerEvents: 'none',- },- },- // Both budgets add the overdrag padding back to the height so the visible- // height (minus the off-screen padding) matches the intended budget.- budget: {- height: `calc(var(--_sheet-budget) + ${OVERSCROLL_PADDING}px)`,+ positionerHidden: {+ display: 'none',},- hugHeight: {- height: 'fit-content',- maxHeight: `calc(${HEIGHT_BUDGETS.hug} + ${OVERSCROLL_PADDING}px)`,+ positionerTop: {+ zIndex: 1,},});-export interface BottomSheetProps extends BaseProps<HTMLDialogElement> {- /** Ref forwarded to the underlying <dialog> element. */- ref?: React.Ref<HTMLDialogElement>;-- /** Whether the sheet is open. Fully controlled — pair with `onOpenChange`. */- isOpen: boolean;-- /**- * Called when the sheet opens or closes. The boolean is the requested next- * state (`false` on Escape, scrim click, or a swipe past the dismiss- * threshold). The caller owns the open state.- */- onOpenChange: (isOpen: boolean) => void;+interface BottomSheetSharedProps extends BaseProps<HTMLDivElement> {+ /** Ref forwarded to the visual sheet panel <div>. */+ ref?: React.Ref<HTMLDivElement>;- /**- * Accessible label for the sheet (required — the sheet has no built-in- * heading to derive a name from).- */+ /** Accessible label for the sheet. */label: string;- /**- * Sheet content, rendered below the grab handle in a scrollable,- * mobile-keyboard-aware area.- */+ /** Sheet content, rendered below the grab handle in a scrollable area. */children: ReactNode;- /**- * How tall the sheet is. A named budget, or any explicit height:- * - `'hug'` — fits its content, never taller than 92% of the viewport.- * - `'capped'` — a scrolling mid-height panel (~62%).- * - `'tall'` — a pinned near-full panel (~92%); use when content streams in- * so the sheet doesn't resize under the user.- * - a `number` (px) or CSS length string (e.g. `'70dvh'`, `480`) for a- * custom budget.- *- * The user can still drag between snap points regardless of the starting- * height. On viewports shorter than the budget the sheet fills the- * available height.- * @default 'capped'- */+ /** Height budget or custom CSS length. @default 'capped' */height?: BottomSheetHeight | number | string;+}- /**- * Whether to render a modal scrim behind the sheet.- * - `true` (default) — `showModal()`: renders in the top layer with a focus- * trap, a `::backdrop` scrim, body scroll lock, and tap-scrim-to-dismiss.- * The background is inert. Use for focused tasks (filters, forms).- * - `false`: `show()` renders a viewport-anchored overlay with **no scrim**. It is- * still layered above the page, not rendered inline, but the page behind- * stays interactive and scrollable (like Material's *standard* bottom- * sheet or an iOS undimmed detent). Escape still closes while focus is- * inside the sheet, and drag/flick-to-dismiss still work. Use for a peek- * surface that coexists with the page (e.g. a panel over a live map).- * @default true- */+interface StandaloneBottomSheetProps extends BottomSheetSharedProps {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;hasScrim?: boolean;+ sheetId?: never;+}- /** Test ID for the root element. */- 'data-testid'?: string;+interface SwitcherBottomSheetProps extends BottomSheetSharedProps {+ sheetId: string;+ isOpen?: never;+ onOpenChange?: never;+ hasScrim?: never;}-/**- * A mobile touch sheet that rises from the bottom edge, with a grab handle,- * drag-to-resize snap points, and swipe-to-dismiss. It owns a native- * `<dialog>` and, by default (`hasScrim`), enters the top layer with a focus- * trap + `::backdrop` scrim and locks body scroll; a slow drag settles to the- * nearest snap point, a flick down dismisses, and Escape closes — so the swipe- * always has a keyboard equivalent.- *- * With `hasScrim={false}` it opens non-modally (`show()`, no scrim), leaving- * the page behind interactive and scrollable.- *- * Focused form controls scroll above the mobile on-screen keyboard without- * resizing the sheet. A short sheet temporarily lifts when it has no usable- * area above the keyboard. Moving the sheet dismisses the keyboard.- *- * @example- * ```- * const [isOpen, setIsOpen] = useState(false);- * <BottomSheet- * isOpen={isOpen}- * onOpenChange={setIsOpen}- * label="Filters">- * <FilterControls />- * </BottomSheet>- * ```- */-export function BottomSheet({+export type BottomSheetProps =+ StandaloneBottomSheetProps | SwitcherBottomSheetProps;++function panelStateForSwitcherPhase(+ phase: BottomSheetSwitcherPhase,+ alignmentOffset: number,+): BottomSheetPanelState {+ switch (phase) {+ case 'active':+ return {kind: 'open', entering: false};+ case 'entering':+ return {kind: 'open', entering: true};+ case 'covered':+ case 'aligning':+ case 'fading':+ return {kind: 'retained', motion: phase, alignmentOffset};+ case 'exiting':+ return {kind: 'exiting'};+ case 'hidden':+ return {kind: 'hidden'};+ }+}++function focusPanel(panel: HTMLElement | null, isModal: boolean): void {+ const activeElement = document.activeElement;+ if (activeElement != null && panel?.contains(activeElement)) {+ return;+ }+ const autofocus = panel?.querySelector<HTMLElement>('[data-autofocus]');+ if (autofocus != null) {+ autofocus.focus();+ } else if (isModal) {+ panel?.focus();+ }+}++function StandaloneBottomSheet({ref,isOpen,onOpenChange,@@ -391,18 +186,26 @@ export function BottomSheet({hasScrim = true,xstyle,...props-}: BottomSheetProps) {- const [isPresented, setIsPresented] = useState(isOpen);- const isExiting = !isOpen && isPresented;+}: StandaloneBottomSheetProps) {const dialogRef = useRef<HTMLDialogElement | null>(null);+ const positionerRef = useRef<HTMLDivElement | null>(null);+ const panelRef = useRef<HTMLDivElement | null>(null);const triggerRef = useRef<HTMLElement | null>(null);- const positionerNodeRef = useRef<HTMLDivElement | null>(null);- const sheetNodeRef = useRef<HTMLDivElement | null>(null);- const bodyNodeRef = useRef<HTMLDivElement | null>(null);- const close = useCallback(() => onOpenChange(false), [onOpenChange]);+ const [isPresented, setIsPresented] = useState(isOpen);+ const shouldPresent = isOpen || isPresented;+ const panelState: BottomSheetPanelState = isOpen+ ? {kind: 'open', entering: false}+ : isPresented+ ? {kind: 'exiting'}+ : {kind: 'hidden'};- // Set imperatively (not via state) so a 60fps drag doesn't re-render. The- // hook reports the scrim opacity for the current detent (a faint floor at the peek).+ const close = useCallback(() => onOpenChange(false), [onOpenChange]);+ const handlePanelElementChange = useCallback(+ (element: HTMLDivElement | null) => {+ panelRef.current = element;+ },+ [],+ );const handleScrimOpacity = useCallback((opacity: number) => {dialogRef.current?.style.setProperty('--_sheet-scrim-opacity',@@ -410,110 +213,49 @@ export function BottomSheet({);}, []);- const {- contentProps,- handleProps,- bodyProps,- sheetRef,- dragOffset,- settledOffset,- isDragging,- } = useSheetGestures({- isOpen,- onDismiss: close,- snapHeights: defaultSnapHeights,- onScrimOpacity: handleScrimOpacity,- });- const isSheetTraveling = isDragging && dragOffset !== settledOffset;- const mergedBodyRef = useMemo(- () => mergeRefs(bodyProps.ref, bodyNodeRef),- [bodyProps.ref],- );- useMobileKeyboard({- bodyRef: bodyNodeRef,- bottomClearance: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,- isSheetTraveling,- isOpen,- positionerRef: positionerNodeRef,- preserveSheetHeight: height === 'hug',- sheetRef: sheetNodeRef,- });-- // Modal: showModal() enters the top layer with a focus trap + ::backdrop and- // we restore focus to the opener on close. Standard: show() is non-modal, so- // we neither trap nor steal focus (the background stays interactive) — we- // only honor an explicit data-autofocus.useEffect(() => {const dialog = dialogRef.current;- if (!dialog) {+ if (dialog == null || !isOpen) {return;}- if (isOpen) {- setIsPresented(true);- dialog.style.setProperty('--_sheet-scrim-opacity', '1');- if (!dialog.open) {- // Only remember/restore focus for modal sheets; a non-modal sheet must- // not yank focus back from whatever the user does in the live page.- if (hasScrim) {- triggerRef.current = document.activeElement as HTMLElement | null;- dialog.showModal();- } else {- dialog.show();- }- // Land on the panel (so AT reads from the label) for modal sheets;- // otherwise only honor a descendant data-autofocus.- const autofocus = dialog.querySelector<HTMLElement>('[data-autofocus]');- if (autofocus) {- autofocus.focus({preventScroll: true});- } else if (hasScrim) {- sheetNodeRef.current?.focus({preventScroll: true});- }- }- } else if (dialog.open) {++ setIsPresented(true);+ dialog.style.setProperty('--_sheet-scrim-opacity', '1');+ const wasOpen = dialog.open;+ if (!wasOpen) {if (hasScrim) {- dialog.style.setProperty('--_sheet-scrim-opacity', '0');+ triggerRef.current = document.activeElement as HTMLElement | null;+ dialog.showModal();+ } else {+ dialog.show();}- // Wait for the slide-out (sheetClosing, applied this render) before- // close() releases the top layer. Timeout backstops a missing- // transitionend (reduced motion, hidden tab).- const sheet = sheetNodeRef.current;- let done = false;- const finish = () => {- if (done) {- return;- }- done = true;- clearTimeout(timer);- sheet?.removeEventListener('transitionend', onEnd);- if (dialog.open) {- dialog.close();- }- setIsPresented(false);- triggerRef.current?.focus();- triggerRef.current = null;- };- const onEnd = (event: TransitionEvent) => {- if (event.target === sheet && event.propertyName === 'transform') {- finish();- }- };- sheet?.addEventListener('transitionend', onEnd);- // Backstop above --duration-medium so transitionend normally fires- // first; this only covers environments that don't emit it.- const timer = setTimeout(finish, 450);- return () => {- clearTimeout(timer);- sheet?.removeEventListener('transitionend', onEnd);- };+ focusPanel(panelRef.current, hasScrim);+ }+ }, [hasScrim, isOpen]);++ useEffect(() => {+ if (!isOpen && isPresented && hasScrim) {+ handleScrimOpacity(0);}- }, [isOpen, hasScrim]);+ }, [handleScrimOpacity, hasScrim, isOpen, isPresented]);- // Only a modal sheet locks body scroll; a non-modal sheet leaves the page- // scrollable behind it.- useScrollLock(isPresented && hasScrim);+ const handleMotionComplete = useCallback(+ (motion: BottomSheetPanelMotion) => {+ if (motion !== 'exiting' || isOpen) {+ return;+ }+ const dialog = dialogRef.current;+ if (dialog?.open) {+ dialog.close();+ }+ setIsPresented(false);+ triggerRef.current?.focus();+ triggerRef.current = null;+ },+ [isOpen],+ );- // Enforce an accessible name: label is required by types, but a JS caller- // can still pass an empty string, leaving the sheet unnamed.+ useScrollLock(shouldPresent && hasScrim);useDevWarning('BottomSheet','requires a non-empty `label` for an accessible name; the open sheet ' +@@ -528,9 +270,6 @@ export function BottomSheet({},[close],);- // Explicit Escape handler in addition to the native `cancel` event, for- // environments that don't synthesize `cancel` (and the show() path, which- // never fires `cancel`). Only fires when focus is inside the sheet.const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLDialogElement>) => {if (event.key === 'Escape') {@@ -540,9 +279,6 @@ export function BottomSheet({},[close],);- // Tap-outside-to-dismiss only applies to modal sheets (the scrim). A non-modal- // sheet has no scrim and its transparent shell is pointer-events:none, so taps- // pass through to the page rather than dismissing.const handleClick = useCallback((event: React.MouseEvent<HTMLDialogElement>) => {if (hasScrim && event.target === event.currentTarget) {@@ -552,68 +288,225 @@ export function BottomSheet({[close, hasScrim],);- const isNamed = typeof height === 'string' && height in HEIGHT_BUDGETS;- const budget = isNamed- ? HEIGHT_BUDGETS[height as BottomSheetHeight]- : typeof height === 'number'- ? `${height}px`- : height;- const isHug = height === 'hug';-return (<dialog{...stylex.props(styles.dialog,- (isOpen || isPresented) && styles.dialogOpen,- // Modal: paint the ::backdrop scrim (top layer). Non-modal: no scrim,- // pass taps through to the page, and sit above content via z-index.+ shouldPresent && styles.dialogOpen,hasScrim && styles.scrim,!hasScrim && styles.dialogNonModal,)}- ref={mergeRefs(ref, dialogRef)}+ ref={dialogRef}aria-label={label}- aria-hidden={isExiting ? 'true' : undefined}+ aria-hidden={!isOpen && isPresented ? 'true' : undefined}aria-modal={hasScrim && isOpen ? 'true' : undefined}- inert={isExiting ? true : undefined}+ inert={!isOpen && isPresented ? true : undefined}onCancel={handleCancel}onClick={handleClick}- onKeyDown={handleKeyDown}- {...props}>- <div ref={positionerNodeRef} {...stylex.props(styles.positioner)}>- <div- ref={mergeRefs(sheetRef, sheetNodeRef)}- tabIndex={-1}- {...mergeProps(- themeProps('bottom-sheet'),- stylex.props(- styles.sheet,- isHug ? styles.hugHeight : styles.budget,- !isOpen && styles.sheetClosing,- isExiting && styles.sheetExiting,- xstyle,- ),- undefined,- {- ['--_sheet-budget' as string]: budget,- ...(isOpen ? contentProps.style : {}),- },- )}>- <div- {...stylex.props(styles.handleBar)}- {...handleProps}- aria-hidden="true">- <div {...stylex.props(styles.handlePill)} />- </div>- <div- {...stylex.props(styles.body)}- {...bodyProps}- ref={mergedBodyRef}>- {children}- </div>- </div>+ onKeyDown={handleKeyDown}>+ <div ref={positionerRef} {...stylex.props(styles.positioner)}>+ <BottomSheetPanel+ {...props}+ ref={ref}+ state={panelState}+ height={height}+ xstyle={xstyle}+ onDismiss={close}+ onScrimOpacity={handleScrimOpacity}+ positionerRef={positionerRef}+ onElementChange={handlePanelElementChange}+ onMotionComplete={handleMotionComplete}>+ {children}+ </BottomSheetPanel></div></dialog>);}+interface SwitcherBottomSheetItemProps extends SwitcherBottomSheetProps {+ switcher: BottomSheetSwitcherContextValue;+}++function SwitcherBottomSheetItem({+ switcher,+ ref,+ sheetId,+ label,+ children,+ height = 'capped',+ xstyle,+ ...props+}: SwitcherBottomSheetItemProps) {+ const {+ activeSheet,+ hasScrim,+ onActiveSheetChange,+ getSheetPhase,+ getSheetAlignmentOffset,+ registerSheetElement,+ registerSheetLabel,+ onSheetEnterStart,+ onSheetTransitionComplete,+ onSheetScrimOpacityChange,+ } = switcher;+ const hasValidSheetId = typeof sheetId === 'string' && sheetId.length > 0;+ const phase = hasValidSheetId ? getSheetPhase(sheetId) : 'hidden';+ const alignmentOffset = hasValidSheetId+ ? getSheetAlignmentOffset(sheetId)+ : 0;+ const panelState = panelStateForSwitcherPhase(phase, alignmentOffset);+ const isInteractive = phase === 'active' || phase === 'entering';+ const isInactive =+ phase === 'covered' ||+ phase === 'aligning' ||+ phase === 'fading' ||+ phase === 'exiting';+ const isPresented = phase !== 'hidden';+ const isTopSheet = phase === 'active' || phase === 'entering';+ const positionerRef = useRef<HTMLDivElement | null>(null);+ const panelRef = useRef<HTMLDivElement | null>(null);+ const previousPhaseRef = useRef(phase);+ const previousPhase = previousPhaseRef.current;+ const hasPresentedRef = useRef(false);++ useLayoutEffect(() => {+ previousPhaseRef.current = phase;+ }, [phase]);++ const close = useCallback(() => {+ if (hasValidSheetId && activeSheet === sheetId) {+ onActiveSheetChange(null);+ }+ }, [activeSheet, hasValidSheetId, onActiveSheetChange, sheetId]);+ const handlePanelElementChange = useCallback(+ (element: HTMLDivElement | null) => {+ panelRef.current = element;+ if (hasValidSheetId) {+ registerSheetElement(sheetId, element);+ }+ },+ [hasValidSheetId, registerSheetElement, sheetId],+ );+ const handleMotionStart = useCallback(+ (motion: BottomSheetPanelMotion) => {+ if (motion === 'entering' && hasValidSheetId) {+ onSheetEnterStart(sheetId);+ }+ },+ [hasValidSheetId, onSheetEnterStart, sheetId],+ );+ const handleMotionComplete = useCallback(+ (motion: BottomSheetPanelMotion) => {+ if (hasValidSheetId) {+ onSheetTransitionComplete({sheetId, phase: motion});+ }+ },+ [hasValidSheetId, onSheetTransitionComplete, sheetId],+ );+ const handleScrimOpacity = useCallback(+ (opacity: number) => {+ if (hasValidSheetId) {+ onSheetScrimOpacityChange(sheetId, opacity);+ }+ },+ [hasValidSheetId, onSheetScrimOpacityChange, sheetId],+ );++ useLayoutEffect(() => {+ if (!hasValidSheetId) {+ return;+ }+ registerSheetLabel(sheetId, label);+ return () => registerSheetLabel(sheetId, null);+ }, [hasValidSheetId, label, registerSheetLabel, sheetId]);++ useEffect(() => {+ if (isInteractive) {+ const wasInteractive =+ previousPhase === 'active' || previousPhase === 'entering';+ if (!hasPresentedRef.current || !wasInteractive) {+ focusPanel(panelRef.current, hasScrim);+ }+ hasPresentedRef.current = true;+ } else if (phase === 'hidden') {+ hasPresentedRef.current = false;+ }+ }, [hasScrim, isInteractive, phase, previousPhase]);++ useDevWarning(+ 'BottomSheet',+ 'requires a non-empty `label` for an accessible name; the open sheet ' ++ 'has no built-in heading to derive one from.',+ isInteractive && !label,+ );++ return (+ <div+ ref={positionerRef}+ {...stylex.props(+ styles.positioner,+ !isPresented && styles.positionerHidden,+ isTopSheet && styles.positionerTop,+ )}+ hidden={!isPresented}+ aria-hidden={isInactive ? 'true' : undefined}+ inert={isInactive ? true : undefined}>+ <BottomSheetPanel+ {...props}+ ref={ref}+ state={panelState}+ height={height}+ xstyle={xstyle}+ onDismiss={close}+ onScrimOpacity={handleScrimOpacity}+ positionerRef={positionerRef}+ onElementChange={handlePanelElementChange}+ onMotionStart={handleMotionStart}+ onMotionComplete={handleMotionComplete}>+ {/* A switcher item consumes its parent controller. Its content starts a+ fresh ownership scope so a nested BottomSheet is standalone unless+ it establishes a nested BottomSheetSwitcher of its own. */}+ <BottomSheetSwitcherContext.Provider value={null}>+ {children}+ </BottomSheetSwitcherContext.Provider>+ </BottomSheetPanel>+ </div>+ );+}++/**+ * A mobile touch sheet that either owns a native dialog or participates in a+ * BottomSheetSwitcher shared dialog when given a sheetId inside that context.+ */+export function BottomSheet(props: BottomSheetProps) {+ const switcher = useContext(BottomSheetSwitcherContext);+ const runtimeSheetId = (props as {sheetId?: string}).sheetId;+ const hasValidSheetId =+ typeof runtimeSheetId === 'string' && runtimeSheetId.length > 0;++ useDevWarning(+ 'BottomSheet',+ 'requires a non-empty `sheetId` when nested in ' ++ 'BottomSheetSwitcher; standalone `isOpen` / `onOpenChange` props are ' ++ 'ignored there.',+ switcher != null && !hasValidSheetId,+ );+ useDevWarning(+ 'BottomSheet',+ '`sheetId` only works inside BottomSheetSwitcher. Use `isOpen` and ' ++ '`onOpenChange` for a standalone sheet.',+ switcher == null && runtimeSheetId != null,+ );++ if (switcher != null) {+ return (+ <SwitcherBottomSheetItem+ {...(props as SwitcherBottomSheetProps)}+ switcher={switcher}+ />+ );+ }+ return <StandaloneBottomSheet {...(props as StandaloneBottomSheetProps)} />;+}+BottomSheet.displayName = 'BottomSheet';diff --git a/packages/lab/src/BottomSheet/BottomSheetPanel.test.tsx b/packages/lab/src/BottomSheet/BottomSheetPanel.test.tsxnew file mode 100644index 0000000000..8888400d67--- /dev/null+++ b/packages/lab/src/BottomSheet/BottomSheetPanel.test.tsx@@ -0,0 +1,240 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetPanel.test.tsx+ * @input Uses vitest, Testing Library, BottomSheetPanel+ * @output Tests the shared sheet surface motion contract+ * @position Internal presentation tests shared by standalone and switcher modes+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ BottomSheetPanel,+ type BottomSheetPanelMotion,+ type BottomSheetPanelState,+} from './BottomSheetPanel';++const panelTransitionStyle = {+ transitionProperty: 'transform, opacity',+ transitionDuration: '410ms',+ transitionDelay: '0ms',+};++beforeEach(() => {+ 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();+});++function renderPanel(+ state: BottomSheetPanelState,+ callbacks: {+ onMotionStart?: (motion: BottomSheetPanelMotion) => void;+ onMotionComplete?: (motion: BottomSheetPanelMotion) => void;+ } = {},+) {+ return render(+ <BottomSheetPanel+ state={state}+ height="hug"+ style={panelTransitionStyle}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}+ onMotionStart={callbacks.onMotionStart}+ onMotionComplete={callbacks.onMotionComplete}>+ Panel content+ </BottomSheetPanel>,+ );+}++function getPanel(): HTMLElement {+ const panel = screen+ .getByText('Panel content')+ .closest<HTMLElement>('.astryx-bottom-sheet');+ if (panel == null) {+ throw new Error('BottomSheetPanel surface not found');+ }+ return panel;+}++describe('BottomSheetPanel', () => {+ it('reports entrance completion only for the surface transform', () => {+ const onMotionStart = vi.fn();+ const onMotionComplete = vi.fn();+ renderPanel(+ {kind: 'open', entering: true},+ {onMotionStart, onMotionComplete},+ );++ expect(onMotionStart).toHaveBeenCalledWith('entering');+ fireEvent.transitionEnd(getPanel(), {propertyName: 'opacity'});+ expect(onMotionComplete).not.toHaveBeenCalled();+ fireEvent.transitionEnd(getPanel(), {propertyName: 'transform'});+ expect(onMotionComplete).toHaveBeenCalledWith('entering');+ });++ it('completes a retained-sheet reactivation without waiting for a new entrance', () => {+ const onMotionComplete = vi.fn();+ const {rerender} = render(+ <BottomSheetPanel+ state={{kind: 'retained', motion: 'covered', alignmentOffset: 0}}+ height="hug"+ style={panelTransitionStyle}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}+ onMotionComplete={onMotionComplete}>+ Panel content+ </BottomSheetPanel>,+ );++ rerender(+ <BottomSheetPanel+ state={{kind: 'open', entering: true}}+ height="hug"+ style={panelTransitionStyle}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}+ onMotionComplete={onMotionComplete}>+ Panel content+ </BottomSheetPanel>,+ );++ expect(onMotionComplete).toHaveBeenCalledWith('entering');+ });++ it('applies the switcher alignment offset to a retained surface', () => {+ renderPanel({+ kind: 'retained',+ motion: 'aligning',+ alignmentOffset: 120,+ });++ expect(getPanel()).toHaveStyle({transform: 'translateY(120px)'});+ });++ it('maps exit and fade completion to their respective CSS properties', () => {+ const onMotionComplete = vi.fn();+ const {rerender} = renderPanel(+ {kind: 'retained', motion: 'fading', alignmentOffset: 0},+ {onMotionComplete},+ );++ fireEvent.transitionEnd(getPanel(), {propertyName: 'opacity'});+ expect(onMotionComplete).toHaveBeenLastCalledWith('fading');++ rerender(+ <BottomSheetPanel+ state={{kind: 'exiting'}}+ height="hug"+ style={panelTransitionStyle}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}+ onMotionComplete={onMotionComplete}>+ Panel content+ </BottomSheetPanel>,+ );+ fireEvent.transitionEnd(getPanel(), {propertyName: 'transform'});+ expect(onMotionComplete).toHaveBeenLastCalledWith('exiting');+ });++ it('completes immediately when the rendered transition is disabled', () => {+ vi.mocked(matchMedia).mockReturnValue({+ matches: true,+ media: '(prefers-reduced-motion: reduce)',+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ });+ const onMotionComplete = vi.fn();+ render(+ <BottomSheetPanel+ state={{kind: 'open', entering: true}}+ height="hug"+ onDismiss={() => {}}+ onScrimOpacity={() => {}}+ onMotionComplete={onMotionComplete}>+ Panel content+ </BottomSheetPanel>,+ );++ expect(onMotionComplete).toHaveBeenCalledWith('entering');+ });++ it('derives its transition backstop from the rendered timing', () => {+ vi.useFakeTimers();+ try {+ const onMotionComplete = vi.fn();+ render(+ <BottomSheetPanel+ state={{kind: 'open', entering: true}}+ height="hug"+ style={{+ transitionProperty: 'transform, opacity',+ transitionDuration: '0.5s, 200ms',+ transitionDelay: '100ms, 0ms',+ }}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}+ onMotionComplete={onMotionComplete}>+ Panel content+ </BottomSheetPanel>,+ );++ act(() => vi.advanceTimersByTime(649));+ expect(onMotionComplete).not.toHaveBeenCalled();+ act(() => vi.advanceTimersByTime(1));+ expect(onMotionComplete).toHaveBeenCalledWith('entering');+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not detach a stable public ref during an ordinary rerender', () => {+ const panelRef = vi.fn();+ const {rerender, unmount} = render(+ <BottomSheetPanel+ ref={panelRef}+ state={{kind: 'open', entering: false}}+ height="hug"+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ First render+ </BottomSheetPanel>,+ );++ expect(panelRef).toHaveBeenCalledTimes(1);+ rerender(+ <BottomSheetPanel+ ref={panelRef}+ state={{kind: 'open', entering: false}}+ height="hug"+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ Second render+ </BottomSheetPanel>,+ );+ expect(panelRef).toHaveBeenCalledTimes(1);++ unmount();+ expect(panelRef).toHaveBeenLastCalledWith(null);+ expect(panelRef).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/lab/src/BottomSheet/BottomSheetPanel.tsx b/packages/lab/src/BottomSheet/BottomSheetPanel.tsxnew file mode 100644index 0000000000..c0a8534928--- /dev/null+++ b/packages/lab/src/BottomSheet/BottomSheetPanel.tsx@@ -0,0 +1,472 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file BottomSheetPanel.tsx+ * @input Uses React, StyleX, theme tokens, useSheetGestures+ * @output Internal BottomSheetPanel surface and motion-state types+ * @position Shared presentation layer for standalone and switcher BottomSheets+ *+ * This component owns everything intrinsic to a sheet surface: height budgets,+ * drag and snap gestures, the handle and scrolling body, motion styles, and+ * transition completion. It deliberately does not own a dialog, focus, inert+ * state, or switcher registration; those belong to the hosting controller.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/BottomSheet/BottomSheet.tsx+ * - /packages/lab/src/BottomSheet/BottomSheetPanel.test.tsx+ * - /packages/lab/src/BottomSheet/useSheetGestures.ts+ */++import {+ useCallback,+ useEffect,+ useImperativeHandle,+ useLayoutEffect,+ useRef,+ type RefObject,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '@astryxdesign/core';+import {+ colorVars,+ durationVars,+ easeVars,+ radiusVars,+ shadowVars,+ sizeVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import {mergeProps, themeProps} from '@astryxdesign/core/utils';+import {useMobileKeyboard} from './useMobileKeyboard';+import {useSheetGestures} from './useSheetGestures';++const SNAP_FRACTIONS = [0.14, 0.5, 0.92];++const HEIGHT_BUDGETS = {+ hug: '92dvh',+ capped: '62dvh',+ tall: '92dvh',+} as const;++export type BottomSheetHeight = keyof typeof HEIGHT_BUDGETS;++// SYNC: must match OVERSCROLL_MAX in useSheetGestures.ts.+const OVERSCROLL_PADDING = 48;+const MOBILE_KEYBOARD_BOTTOM_CLEARANCE = 48;+const TRANSITION_BACKSTOP_BUFFER_MS = 50;++function defaultSnapHeights(): number[] {+ if (typeof window === 'undefined') {+ return [];+ }+ const viewportHeight = window.visualViewport?.height ?? window.innerHeight;+ return SNAP_FRACTIONS.map(fraction => fraction * viewportHeight);+}++const styles = stylex.create({+ sheet: {+ pointerEvents: 'auto',+ boxSizing: 'border-box',+ display: 'flex',+ flexDirection: 'column',+ minHeight: 0,+ width: '100%',+ maxWidth: 640,+ backgroundColor: colorVars['--color-background-surface'],+ borderStartStartRadius: radiusVars['--radius-container'],+ borderStartEndRadius: radiusVars['--radius-container'],+ boxShadow: shadowVars['--shadow-high'],+ outline: 'none',+ overflow: 'hidden',+ paddingBlockEnd: `calc(env(safe-area-inset-bottom, 0px) + ${OVERSCROLL_PADDING}px)`,+ marginBlockEnd: `${-OVERSCROLL_PADDING}px`,+ transform: {+ default: 'translateY(0)',+ '@starting-style': 'translateY(100%)',+ },+ opacity: 1,+ transitionProperty: 'transform, opacity',+ transitionDuration: durationVars['--duration-medium'],+ transitionTimingFunction: easeVars['--ease-standard'],+ willChange: 'transform, opacity',+ '@media (prefers-reduced-motion: reduce)': {+ transitionDuration: '0.01s',+ },+ },+ sheetClosing: {+ transform: 'translateY(100%)',+ },+ sheetFading: {+ opacity: 0,+ },+ sheetInactive: {+ pointerEvents: 'none',+ },+ handleBar: {+ flexShrink: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ height: spacingVars['--spacing-12'],+ touchAction: 'none',+ cursor: 'grab',+ },+ handlePill: {+ width: sizeVars['--size-element-lg'],+ height: spacingVars['--spacing-1'],+ borderRadius: radiusVars['--radius-full'],+ backgroundColor: colorVars['--color-border'],+ },+ body: {+ flexGrow: 1,+ minHeight: 0,+ overflowY: 'auto',+ scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,+ overscrollBehavior: 'none',+ touchAction: 'pan-y',+ '::after': {+ content: '""',+ display: 'block',+ blockSize: 'var(--_sheet-keyboard-inset, 0px)',+ pointerEvents: 'none',+ },+ },+ budget: {+ height: `calc(var(--_sheet-budget) + ${OVERSCROLL_PADDING}px)`,+ },+ hugHeight: {+ height: 'fit-content',+ maxHeight: `calc(${HEIGHT_BUDGETS.hug} + ${OVERSCROLL_PADDING}px)`,+ },+});++export type BottomSheetPanelMotion =+ 'entering' | 'aligning' | 'fading' | 'exiting';++export type BottomSheetPanelState =+ | {kind: 'hidden'}+ | {kind: 'open'; entering: boolean}+ | {+ kind: 'retained';+ motion: 'covered' | 'aligning' | 'fading';+ alignmentOffset: number;+ }+ | {kind: 'exiting'};++interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {+ /** Ref forwarded to the visual sheet panel. */+ ref?: React.Ref<HTMLDivElement>;+ state: BottomSheetPanelState;+ height: BottomSheetHeight | number | string;+ children: ReactNode;+ onDismiss: () => void;+ onScrimOpacity: (opacity: number) => void;+ positionerRef?: RefObject<HTMLDivElement | null>;+ onElementChange?: (element: HTMLDivElement | null) => void;+ onMotionStart?: (motion: BottomSheetPanelMotion) => void;+ onMotionComplete?: (motion: BottomSheetPanelMotion) => void;+}++function motionForState(+ state: BottomSheetPanelState,+): BottomSheetPanelMotion | null {+ if (state.kind === 'open') {+ return state.entering ? 'entering' : null;+ }+ if (state.kind === 'retained') {+ return state.motion === 'covered' ? null : state.motion;+ }+ return state.kind === 'exiting' ? 'exiting' : null;+}++function waitForTransition(+ element: HTMLElement | null,+ propertyName: 'transform' | 'opacity',+ complete: () => void,+): () => void {+ if (element == null) {+ complete();+ return () => {};+ }++ let done = false;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const finish = () => {+ if (done) {+ return;+ }+ done = true;+ if (timer != null) {+ clearTimeout(timer);+ }+ element.removeEventListener('transitionend', handleTransitionEnd);+ element.removeEventListener('transitioncancel', handleTransitionEnd);+ complete();+ };+ const handleTransitionEnd = (event: TransitionEvent) => {+ if (event.target === element && event.propertyName === propertyName) {+ finish();+ }+ };+ element.addEventListener('transitionend', handleTransitionEnd);+ element.addEventListener('transitioncancel', handleTransitionEnd);++ const computedStyle = getComputedStyle(element);+ if (+ element.style.transition.trim() === 'none' ||+ computedStyle.transition.trim() === 'none'+ ) {+ finish();+ return () => {};+ }+ const properties = computedStyle.transitionProperty+ .split(',')+ .map(value => value.trim());+ const durations = computedStyle.transitionDuration+ .split(',')+ .map(parseTransitionTime);+ const delays = computedStyle.transitionDelay+ .split(',')+ .map(parseTransitionTime);+ let hasUnresolvedTiming = false;+ const transitionMs = properties.reduce((longest, property, index) => {+ if (property !== propertyName && property !== 'all') {+ return longest;+ }+ const duration = durations[index % durations.length];+ const delay = delays[index % delays.length];+ if (duration == null || delay == null) {+ hasUnresolvedTiming = true;+ return longest;+ }+ return Math.max(longest, duration + delay);+ }, 0);++ if (hasUnresolvedTiming) {+ // JSDOM can leave CSS variables unresolved. In that case the native event+ // remains authoritative; choosing a fixed timeout here would make an+ // assumption about the consumer's theme.+ return () => {+ element.removeEventListener('transitionend', handleTransitionEnd);+ element.removeEventListener('transitioncancel', handleTransitionEnd);+ };+ }++ if (transitionMs <= 0) {+ finish();+ return () => {};+ }++ timer = setTimeout(finish, transitionMs + TRANSITION_BACKSTOP_BUFFER_MS);+ return () => {+ if (timer != null) {+ clearTimeout(timer);+ }+ element.removeEventListener('transitionend', handleTransitionEnd);+ element.removeEventListener('transitioncancel', handleTransitionEnd);+ };+}++function parseTransitionTime(value: string): number | null {+ const normalizedValue = value.trim();+ if (!/^-?(?:\d+|\d*\.\d+)(?:ms|s)$/.test(normalizedValue)) {+ return null;+ }+ const time = Number.parseFloat(value);+ return normalizedValue.endsWith('ms') ? time : time * 1000;+}++/** Internal visual and gesture surface shared by every BottomSheet host. */+export function BottomSheetPanel({+ ref,+ state,+ height,+ children,+ className,+ style,+ tabIndex,+ xstyle,+ onDismiss,+ onScrimOpacity,+ positionerRef,+ onElementChange,+ onMotionStart,+ onMotionComplete,+ ...props+}: BottomSheetPanelProps) {+ const elementRef = useRef<HTMLDivElement | null>(null);+ const bodyElementRef = useRef<HTMLDivElement | null>(null);+ const fallbackPositionerRef = useRef<HTMLDivElement | null>(null);+ const previousStateRef = useRef(state);+ const reactivatedEntranceRef = useRef(false);+ const onMotionStartRef = useRef(onMotionStart);+ const onMotionCompleteRef = useRef(onMotionComplete);+ const startedMotionRef = useRef<BottomSheetPanelMotion | null>(null);+ const pendingMotionCompleteRef = useRef<BottomSheetPanelMotion | null>(null);++ const isEntering = state.kind === 'open' && state.entering;+ const previousState = previousStateRef.current;+ const wasEntering = previousState.kind === 'open' && previousState.entering;+ if (isEntering && !wasEntering) {+ reactivatedEntranceRef.current = previousState.kind === 'retained';+ } else if (!isEntering) {+ reactivatedEntranceRef.current = false;+ }++ useLayoutEffect(() => {+ previousStateRef.current = state;+ onMotionStartRef.current = onMotionStart;+ onMotionCompleteRef.current = onMotionComplete;+ }, [onMotionComplete, onMotionStart, state]);++ const isInteractive = state.kind === 'open';+ const isRetained = state.kind === 'retained';+ const isInactive = isRetained || state.kind === 'exiting';+ const isClosing = state.kind === 'exiting';+ const isFading = isRetained && state.motion === 'fading';+ const alignmentOffset = isRetained ? state.alignmentOffset : 0;++ const {+ contentProps,+ handleProps,+ bodyProps,+ sheetRef,+ dragOffset,+ settledOffset,+ isDragging,+ } = useSheetGestures({+ isOpen: isInteractive,+ onDismiss,+ snapHeights: defaultSnapHeights,+ onScrimOpacity,+ });++ const setElement = useCallback(+ (element: HTMLDivElement | null) => {+ sheetRef(element);+ elementRef.current = element;+ onElementChange?.(element);+ },+ [onElementChange, sheetRef],+ );+ const setBodyElement = useCallback(+ (element: HTMLDivElement | null) => {+ bodyProps.ref(element);+ bodyElementRef.current = element;+ },+ [bodyProps.ref],+ );+ useMobileKeyboard({+ bodyRef: bodyElementRef,+ bottomClearance: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,+ isSheetTraveling: isDragging && dragOffset !== settledOffset,+ isOpen: isInteractive,+ positionerRef: positionerRef ?? fallbackPositionerRef,+ preserveSheetHeight: height === 'hug',+ sheetRef: elementRef,+ });+ // Keep controller registration attached to one stable host ref. React+ // detaches an old callback ref when a consumer supplies a new identity; if+ // that public ref were merged with setElement, an ordinary parent rerender+ // could be mistaken for the panel unmounting and cancel a sheet handoff.+ useImperativeHandle(ref, () => elementRef.current as HTMLDivElement, []);++ const motion = motionForState(state);+ useLayoutEffect(() => {+ if (motion == null) {+ return;+ }+ startedMotionRef.current = null;+ pendingMotionCompleteRef.current = null;+ if (motion === 'entering' && reactivatedEntranceRef.current) {+ pendingMotionCompleteRef.current = motion;+ return;+ }+ return waitForTransition(+ elementRef.current,+ motion === 'fading' ? 'opacity' : 'transform',+ () => {+ if (startedMotionRef.current === motion) {+ onMotionCompleteRef.current?.(motion);+ } else {+ pendingMotionCompleteRef.current = motion;+ }+ },+ );+ }, [motion]);+ useEffect(() => {+ if (motion == null) {+ return;+ }+ onMotionStartRef.current?.(motion);+ startedMotionRef.current = motion;+ if (pendingMotionCompleteRef.current === motion) {+ pendingMotionCompleteRef.current = null;+ onMotionCompleteRef.current?.(motion);+ }+ return () => {+ if (startedMotionRef.current === motion) {+ startedMotionRef.current = null;+ }+ if (pendingMotionCompleteRef.current === motion) {+ pendingMotionCompleteRef.current = null;+ }+ };+ }, [motion]);++ const isNamedHeight = typeof height === 'string' && height in HEIGHT_BUDGETS;+ const budget = isNamedHeight+ ? HEIGHT_BUDGETS[height as BottomSheetHeight]+ : typeof height === 'number'+ ? `${height}px`+ : height;+ const retainedTransform =+ alignmentOffset > 0+ ? [contentProps.style.transform, `translateY(${alignmentOffset}px)`]+ .filter(Boolean)+ .join(' ')+ : contentProps.style.transform;++ return (+ <div+ {...props}+ ref={setElement}+ tabIndex={tabIndex ?? -1}+ {...mergeProps(+ themeProps('bottom-sheet'),+ stylex.props(+ styles.sheet,+ height === 'hug' ? styles.hugHeight : styles.budget,+ isClosing && styles.sheetClosing,+ isFading && styles.sheetFading,+ isInactive && styles.sheetInactive,+ xstyle,+ ),+ className,+ {+ ['--_sheet-budget' as string]: budget,+ ...(isInteractive+ ? contentProps.style+ : isRetained+ ? {transform: retainedTransform}+ : {}),+ ...style,+ },+ )}>+ <div+ {...stylex.props(styles.handleBar)}+ {...handleProps}+ aria-hidden="true">+ <div {...stylex.props(styles.handlePill)} />+ </div>+ <div {...stylex.props(styles.body)} {...bodyProps} ref={setBodyElement}>+ {children}+ </div>+ </div>+ );+}++BottomSheetPanel.displayName = 'BottomSheetPanel';diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjs b/packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjsnew file mode 100644index 0000000000..bc133d4c68--- /dev/null+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjs@@ -0,0 +1,140 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'BottomSheetSwitcher',+ displayName: 'BottomSheetSwitcher',+ group: 'BottomSheet',+ category: 'Overlay',+ keywords: ['bottom sheet', 'switcher', 'multi-step', 'flow', 'wizard'],+ theming: {+ targets: [+ {+ className: 'astryx-bottom-sheet-switcher-scrim',+ visualProps: [],+ },+ ],+ },+ description:+ 'Coordinates multiple BottomSheets as a mutually exclusive flow. One activeSheet ID selects the only interactive sheet; during a handoff, the new sheet enters above the inert previous sheet. If the new sheet is shorter, the previous sheet simultaneously moves down until their top edges align, then fades after both transforms complete. The switcher owns one shared native <dialog>: modal flows call showModal() once for one top-layer boundary and one ::backdrop across the whole flow, while no-scrim flows use a non-modal show() shell.',+ props: [+ {+ name: 'activeSheet',+ type: 'string | null',+ description:+ "ID of the interactive BottomSheet, or null when the flow should close. Match a nested BottomSheet's unique sheetId; the previous sheet may remain visually present and inert while the new sheet enters, simultaneously align downward behind a shorter step, then fade away.",+ required: true,+ },+ {+ name: 'onActiveSheetChange',+ type: '(sheetId: string | null) => void',+ description:+ 'Called with null when the active sheet dismisses. The same state setter can be used by flow controls to switch to another sheet ID.',+ required: true,+ },+ {+ name: 'hasScrim',+ type: 'boolean',+ description:+ 'Whether the shared dialog is modal. true uses showModal() once for one native ::backdrop, focus trap, scroll lock, and click-to-dismiss across the whole flow. false uses show() with no backdrop and leaves the page interactive; avoid transformed, contained, or clipping ancestors because the non-modal dialog remains in its containing context.',+ default: 'true',+ },+ {+ name: 'children',+ type: 'ReactNode',+ description: 'BottomSheets identified by unique sheetId values.',+ required: true,+ },+ ],+ usage: {+ description:+ 'Use one activeSheet value as the source of truth for a multi-step bottom-sheet flow. Set it to a child sheetId to open or switch steps, and set it to null to close. On a handoff, the previous sheet becomes inert immediately while the new active sheet enters above it. A taller previous sheet simultaneously moves down until its top edge aligns with the shorter new sheet; it fades only after both transforms complete. Equal-height or shorter previous sheets stay stationary and fade after the entrance. The switcher keeps one shared dialog open across the transition, with one modal boundary, native backdrop, focus trap, and body scroll lock when hasScrim is true, and restores focus to the trigger that started the flow after the final exit finishes.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Give every nested BottomSheet a stable, unique sheetId and model the flow as one activeSheet value.',+ },+ {+ guidance: true,+ description:+ 'Keep state local to the sheet that owns it; lift only data that another sheet needs.',+ },+ {+ guidance: true,+ description:+ "Treat each switcher sheet's content as a new ownership scope. A BottomSheet opened from that content is standalone; wrap it in a nested BottomSheetSwitcher when it starts another multi-step flow.",+ },+ {+ guidance: true,+ description:+ 'Configure hasScrim on BottomSheetSwitcher, not its individual BottomSheet children, so the modal layer remains stable across handoffs.',+ },+ {+ guidance: true,+ description:+ 'When hasScrim is false, keep the switcher outside transformed, contained, and overflow-clipping ancestors so its non-modal dialog can remain viewport-aligned.',+ },+ {+ guidance: true,+ description:+ 'Treat activeSheet as the interaction state: a previous sheet can remain visually present and move beneath the entering sheet, but it is inert and hidden from assistive technology.',+ },+ {+ guidance: false,+ description:+ 'Use separate isOpen booleans for sheets in the same flow; they can drift and request overlapping dialogs.',+ },+ ],+ },+ examples: [+ {+ label: 'Two-step flow',+ code: `const [activeSheet, setActiveSheet] = useState(null);++<>+ <Button label="Start" onClick={() => setActiveSheet('details')} />+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}>+ <BottomSheet sheetId="details" label="Details">+ <Button label="Continue" onClick={() => setActiveSheet('confirm')} />+ </BottomSheet>+ <BottomSheet sheetId="confirm" label="Confirm">+ <Button label="Back" onClick={() => setActiveSheet('details')} />+ <Button label="Done" onClick={() => setActiveSheet(null)} />+ </BottomSheet>+ </BottomSheetSwitcher>+</>`,+ },+ ],+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsDense = {+ description:+ 'controller with one shared native dialog for mutually exclusive multi-step BottomSheets',+ usage: {+ description:+ 'One activeSheet ID makes one nested sheet interactive in one shared dialog. Change IDs to enter a new top sheet while simultaneously aligning a taller previous sheet behind a shorter one, then fade it; null closes the flow.',+ bestPractices: [+ {+ guidance: true,+ description: 'Use stable, unique sheetId values for every child.',+ },+ {+ guidance: true,+ description: "Let the switcher own the flow's one shared scrim.",+ },+ {+ guidance: true,+ description:+ 'Nested sheets start a new standalone or nested-switcher scope.',+ },+ {+ guidance: false,+ description: 'Coordinate a single flow with separate open booleans.',+ },+ ],+ },+};diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx b/packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsxnew file mode 100644index 0000000000..5ce5013b26--- /dev/null+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx@@ -0,0 +1,749 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetSwitcher.test.tsx+ * @input Uses vitest, Testing Library, BottomSheet, BottomSheetSwitcher+ * @output Tests mutually exclusive sheet selection, dismissal, and focus handoff+ * @position Lab tests for BottomSheetSwitcher+ *+ * SYNC: When BottomSheetSwitcher.tsx or its BottomSheet integration changes,+ * update these tests to match the public behavior.+ */++import {fireEvent, render, screen} from '@testing-library/react';+import {createRef, useState} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {useFocusTrap} from '@astryxdesign/core/hooks';+import {BottomSheet} from './BottomSheet';+import {BottomSheetSwitcher} from './BottomSheetSwitcher';++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');+ });+ window.scrollTo = vi.fn();+ 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();+});++function Flow() {+ const [activeSheet, setActiveSheet] = useState<string | null>(null);+ return (+ <>+ <button type="button" onClick={() => setActiveSheet('details')}>+ Start flow+ </button>+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}>+ <BottomSheet+ sheetId="details"+ label="Details"+ data-testid="details-sheet">+ <button type="button" onClick={() => setActiveSheet('confirm')}>+ Continue+ </button>+ </BottomSheet>+ <BottomSheet+ sheetId="confirm"+ label="Confirm"+ data-testid="confirm-sheet">+ <button type="button" onClick={() => setActiveSheet('details')}>+ Back+ </button>+ </BottomSheet>+ </BottomSheetSwitcher>+ </>+ );+}++function ConditionalFlow() {+ const [activeSheet, setActiveSheet] = useState<string | null>(null);+ return (+ <>+ <button type="button" onClick={() => setActiveSheet('details')}>+ Start conditional flow+ </button>+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}>+ {activeSheet != null && (+ <BottomSheet sheetId={activeSheet} label="Conditional details">+ Content+ </BottomSheet>+ )}+ </BottomSheetSwitcher>+ </>+ );+}++function NestedStandaloneSheetFlow() {+ const [isNestedOpen, setIsNestedOpen] = useState(false);+ return (+ <BottomSheetSwitcher activeSheet="details" onActiveSheetChange={() => {}}>+ <BottomSheet sheetId="details" label="Details">+ <button type="button" onClick={() => setIsNestedOpen(true)}>+ Open nested sheet+ </button>+ <BottomSheet+ isOpen={isNestedOpen}+ onOpenChange={setIsNestedOpen}+ label="Nested standalone sheet">+ Nested content+ </BottomSheet>+ </BottomSheet>+ </BottomSheetSwitcher>+ );+}++function NestedEscapeTrap({onEscape}: {onEscape: () => void}) {+ const {containerRef} = useFocusTrap<HTMLDivElement>({+ isActive: true,+ onEscape,+ });+ return (+ <div ref={containerRef} data-testid="nested-escape-trap">+ Nested layer+ </div>+ );+}++const panelRefA = (_element: HTMLDivElement | null) => {};+const panelRefB = (_element: HTMLDivElement | null) => {};++function CallbackRefFlow() {+ const [activeSheet, setActiveSheet] = useState<string | null>('details');+ const [useAlternateRef, setUseAlternateRef] = useState(false);+ return (+ <>+ <button+ type="button"+ onClick={() => setUseAlternateRef(current => !current)}>+ Rerender parent+ </button>+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}>+ <BottomSheet+ ref={useAlternateRef ? panelRefB : panelRefA}+ sheetId="details"+ label="Details"+ data-testid="callback-details-sheet">+ <button type="button" onClick={() => setActiveSheet('confirm')}>+ Continue with callback ref+ </button>+ </BottomSheet>+ <BottomSheet+ sheetId="confirm"+ label="Confirm"+ data-testid="callback-confirm-sheet">+ Confirmation+ </BottomSheet>+ </BottomSheetSwitcher>+ </>+ );+}++function ModeSwitchFlow() {+ const [activeSheet, setActiveSheet] = useState<string | null>(null);+ const [hasScrim, setHasScrim] = useState(true);+ return (+ <>+ <button type="button" onClick={() => setActiveSheet('details')}>+ Open first modal+ </button>+ <button+ type="button"+ onClick={() => {+ setHasScrim(true);+ setActiveSheet('details');+ }}>+ Open second modal+ </button>+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={setActiveSheet}+ hasScrim={hasScrim}>+ <BottomSheet+ sheetId="details"+ label="Details"+ data-testid="mode-details-sheet">+ <button type="button" onClick={() => setHasScrim(false)}>+ Make non-modal+ </button>+ <button type="button" onClick={() => setActiveSheet(null)}>+ Close flow+ </button>+ </BottomSheet>+ </BottomSheetSwitcher>+ </>+ );+}++function getSharedDialog(): HTMLDialogElement {+ const dialog = document.querySelector<HTMLDialogElement>(+ '.astryx-bottom-sheet-switcher-scrim',+ );+ if (!dialog) {+ throw new Error('shared switcher dialog not found');+ }+ return dialog;+}++function finishSheetTransition(+ element: HTMLElement,+ propertyName: 'transform' | 'opacity',+) {+ const sheet = getSheetPanel(element);+ fireEvent.transitionEnd(sheet, {propertyName});+}++function getSheetPanel(element: HTMLElement): HTMLElement {+ if (element.classList.contains('astryx-bottom-sheet')) {+ return element;+ }+ const sheet = element.querySelector<HTMLElement>('.astryx-bottom-sheet');+ if (!sheet) {+ throw new Error('sheet panel not found');+ }+ return sheet;+}++function getSheetLayer(testId: string): HTMLElement {+ const panel = screen.getByTestId(testId);+ const layer = panel.parentElement;+ if (layer == null) {+ throw new Error('sheet layer not found');+ }+ return layer;+}++function mockSheetTop(sheet: HTMLElement, top: number) {+ const rect = {+ x: 0,+ y: top,+ top,+ right: 640,+ bottom: 800,+ left: 0,+ width: 640,+ height: 800 - top,+ toJSON: () => {},+ };+ vi.spyOn(sheet, 'getBoundingClientRect').mockReturnValue(rect);+ if (sheet.parentElement) {+ vi.spyOn(sheet.parentElement, 'getBoundingClientRect').mockReturnValue(+ rect,+ );+ }+}++describe('BottomSheetSwitcher', () => {+ it('opens only the sheet selected by activeSheet', () => {+ render(<Flow />);++ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));++ expect(getSheetLayer('details-sheet')).not.toHaveAttribute('hidden');+ expect(getSheetLayer('confirm-sheet')).toHaveAttribute('hidden');+ expect(getSheetLayer('confirm-sheet')).toHaveStyle({display: 'none'});+ expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);+ expect(+ document.querySelectorAll('.astryx-bottom-sheet-switcher-scrim'),+ ).toHaveLength(1);+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);+ expect(HTMLDialogElement.prototype.show).not.toHaveBeenCalled();+ expect(getSharedDialog()).toHaveAttribute('aria-modal', 'true');+ expect(getSharedDialog()).toHaveAccessibleName('Details');+ });++ it('forwards sheet DOM props and refs to its panel in the shared dialog', () => {+ const panelRef = createRef<HTMLDivElement>();++ render(+ <BottomSheetSwitcher activeSheet="details" onActiveSheetChange={() => {}}>+ <BottomSheet+ ref={panelRef}+ sheetId="details"+ label="Details"+ data-testid="details-layer"+ data-sheet-owner="settings">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>,+ );++ const panel = screen.getByTestId('details-layer');+ expect(panelRef.current).toBe(panel);+ expect(panel).toHaveClass('astryx-bottom-sheet');+ expect(panel).toHaveAttribute('data-sheet-owner', 'settings');+ expect(getSharedDialog()).toContainElement(panel);+ });++ it('forwards switcher DOM props, events, styles, and refs to the shared dialog', () => {+ const dialogRef = createRef<HTMLDialogElement>();+ const onClick = vi.fn();+ const onActiveSheetChange = vi.fn();++ render(+ <BottomSheetSwitcher+ ref={dialogRef}+ activeSheet="details"+ onActiveSheetChange={onActiveSheetChange}+ aria-label="Notification setup"+ data-flow-owner="settings"+ className="consumer-switcher"+ style={{insetInlineStart: 12}}+ onClick={onClick}>+ <BottomSheet sheetId="details" label="Details">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>,+ );++ const dialog = getSharedDialog();+ expect(dialogRef.current).toBe(dialog);+ expect(dialog).toHaveAccessibleName('Notification setup');+ expect(dialog).toHaveAttribute('data-flow-owner', 'settings');+ expect(dialog).toHaveClass('consumer-switcher');+ expect(dialog).toHaveStyle({insetInlineStart: '12px'});++ fireEvent.click(dialog);+ expect(onClick).toHaveBeenCalledTimes(1);+ expect(onActiveSheetChange).toHaveBeenCalledWith(null);+ });++ it('resets switcher context for a sheet nested inside item content', () => {+ render(<NestedStandaloneSheetFlow />);+ const opener = screen.getByRole('button', {name: 'Open nested sheet'});+ opener.focus();+ fireEvent.click(opener);++ const nestedDialog = screen.getByRole('dialog', {+ name: 'Nested standalone sheet',+ });+ expect(nestedDialog).toHaveAttribute('open');+ expect(getSheetPanel(nestedDialog)).toHaveFocus();+ expect(document.querySelectorAll('dialog[open]')).toHaveLength(2);+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(2);++ fireEvent.keyDown(nestedDialog, {key: 'Escape'});+ finishSheetTransition(nestedDialog, 'transform');++ expect(nestedDialog).not.toHaveAttribute('open');+ expect(getSharedDialog()).toHaveAttribute('open');+ expect(opener).toHaveFocus();+ });++ it('keeps the previous sheet stationary until the new entrance finishes, then fades it', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ const sharedDialog = getSharedDialog();+ const detailsSheet = getSheetLayer('details-sheet');+ const confirmSheet = getSheetLayer('confirm-sheet');++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));++ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(detailsSheet).toHaveAttribute('inert');+ expect(detailsSheet).toHaveAttribute('aria-hidden', 'true');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ expect(confirmSheet).not.toHaveAttribute('inert');+ expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);+ expect(getSharedDialog()).toBe(sharedDialog);+ expect(sharedDialog).toHaveAccessibleName('Confirm');++ // The previous sheet is covered, not exiting: neither transform nor+ // opacity completion may release it before the new entrance completes.+ finishSheetTransition(detailsSheet, 'transform');+ finishSheetTransition(detailsSheet, 'opacity');+ expect(detailsSheet).not.toHaveAttribute('hidden');++ finishSheetTransition(confirmSheet, 'transform');+ expect(detailsSheet).not.toHaveAttribute('hidden');++ finishSheetTransition(detailsSheet, 'opacity');++ expect(detailsSheet).toHaveAttribute('hidden');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);+ expect(getSharedDialog()).toBe(sharedDialog);++ fireEvent.click(screen.getByRole('button', {name: 'Back'}));++ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ expect(confirmSheet).toHaveAttribute('inert');+ finishSheetTransition(detailsSheet, 'transform');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ finishSheetTransition(confirmSheet, 'opacity');++ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(confirmSheet).toHaveAttribute('hidden');+ expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);+ expect(getSharedDialog()).toBe(sharedDialog);+ });++ it('moves a taller previous sheet down while the shorter new sheet enters, then waits for both', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ const detailsSheet = getSheetLayer('details-sheet');+ const confirmSheet = getSheetLayer('confirm-sheet');+ const detailsPanel = getSheetPanel(detailsSheet);+ const confirmPanel = getSheetPanel(confirmSheet);+ mockSheetTop(detailsPanel, 100);+ mockSheetTop(confirmPanel, 300);++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));++ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(detailsPanel).toHaveStyle({transform: 'translateY(200px)'});++ // The incoming entrance may finish first, but opacity cannot hide the+ // retained sheet until its concurrent alignment also completes.+ finishSheetTransition(confirmSheet, 'transform');+ finishSheetTransition(detailsSheet, 'opacity');+ expect(detailsSheet).not.toHaveAttribute('hidden');+ finishSheetTransition(detailsSheet, 'transform');+ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(detailsPanel).toHaveStyle({transform: 'translateY(200px)'});+ finishSheetTransition(detailsSheet, 'opacity');++ expect(detailsSheet).toHaveAttribute('hidden');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ });++ it('waits for the incoming entrance when top-edge alignment finishes first', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ const detailsSheet = getSheetLayer('details-sheet');+ const confirmSheet = getSheetLayer('confirm-sheet');+ const detailsPanel = getSheetPanel(detailsSheet);+ mockSheetTop(detailsPanel, 100);+ mockSheetTop(getSheetPanel(confirmSheet), 300);++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ expect(detailsPanel).toHaveStyle({transform: 'translateY(200px)'});++ finishSheetTransition(detailsSheet, 'transform');+ finishSheetTransition(detailsSheet, 'opacity');+ expect(detailsSheet).not.toHaveAttribute('hidden');+ finishSheetTransition(confirmSheet, 'transform');+ finishSheetTransition(detailsSheet, 'opacity');++ expect(detailsSheet).toHaveAttribute('hidden');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ });++ it('replaces an unfinished outgoing sheet during rapid navigation', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ const detailsSheet = getSheetLayer('details-sheet');+ const confirmSheet = getSheetLayer('confirm-sheet');++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ fireEvent.click(screen.getByRole('button', {name: 'Back'}));++ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(detailsSheet).not.toHaveAttribute('inert');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ expect(confirmSheet).toHaveAttribute('inert');+ expect(document.querySelectorAll('dialog[open]')).toHaveLength(1);++ finishSheetTransition(confirmSheet, 'opacity');+ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(confirmSheet).toHaveAttribute('hidden');+ });++ it('ignores late scrim updates from an outgoing sheet gesture', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));++ const detailsPanel = getSheetPanel(getSheetLayer('details-sheet'));+ mockSheetTop(detailsPanel, 100);+ const handle = detailsPanel.firstElementChild;+ if (!(handle instanceof HTMLElement)) {+ throw new Error('sheet handle not found');+ }++ fireEvent.pointerDown(handle, {+ pointerId: 1,+ clientY: 100,+ timeStamp: 0,+ });+ fireEvent.pointerMove(handle, {+ pointerId: 1,+ clientY: 600,+ timeStamp: 16,+ });+ expect(+ getSharedDialog().style.getPropertyValue('--_sheet-scrim-opacity'),+ ).not.toBe('1');++ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));+ expect(getSharedDialog()).toHaveStyle({'--_sheet-scrim-opacity': '1'});++ fireEvent.pointerMove(handle, {+ pointerId: 1,+ clientY: 680,+ timeStamp: 32,+ });+ expect(getSharedDialog()).toHaveStyle({'--_sheet-scrim-opacity': '1'});+ });++ it('keeps an active handoff when a consumer callback ref changes', () => {+ render(<CallbackRefFlow />);+ const detailsSheet = getSheetLayer('callback-details-sheet');+ const confirmSheet = getSheetLayer('callback-confirm-sheet');++ fireEvent.click(+ screen.getByRole('button', {name: 'Continue with callback ref'}),+ );+ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(detailsSheet).toHaveAttribute('inert');+ expect(confirmSheet).not.toHaveAttribute('hidden');++ fireEvent.click(screen.getByRole('button', {name: 'Rerender parent'}));++ expect(detailsSheet).not.toHaveAttribute('hidden');+ expect(detailsSheet).toHaveAttribute('inert');+ expect(confirmSheet).not.toHaveAttribute('hidden');+ });++ it('dismisses the flow from the one shared scrim', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));++ fireEvent.click(getSharedDialog());++ const outgoingSheet = getSheetLayer('details-sheet');+ expect(outgoingSheet).not.toHaveAttribute('hidden');+ expect(outgoingSheet).toHaveAttribute('inert');+ expect(getSharedDialog()).toHaveStyle({'--_sheet-scrim-opacity': '0'});+ expect(document.body.style.position).toBe('fixed');++ finishSheetTransition(outgoingSheet, 'transform');++ expect(getSharedDialog()).not.toHaveAttribute('open');+ expect(document.body.style.position).not.toBe('fixed');+ });++ it('releases the shared modal layer when the closing sheet unmounts immediately', () => {+ render(<ConditionalFlow />);+ fireEvent.click(+ screen.getByRole('button', {name: 'Start conditional flow'}),+ );++ fireEvent.keyDown(+ screen.getByRole('dialog', {name: 'Conditional details'}),+ {key: 'Escape'},+ );++ expect(getSharedDialog()).not.toHaveAttribute('open');+ expect(document.body.style.position).not.toBe('fixed');+ });++ it('keeps the shared dialog inline and opens it modally', () => {+ render(+ <div+ data-testid="clipping-ancestor"+ style={{overflow: 'hidden', transform: 'translateY(100px)'}}>+ <BottomSheetSwitcher+ activeSheet="details"+ onActiveSheetChange={() => {}}>+ <BottomSheet sheetId="details" label="Inline modal details">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>+ </div>,+ );++ const clippingAncestor = screen.getByTestId('clipping-ancestor');+ const dialog = screen.getByRole('dialog', {name: 'Inline modal details'});+ expect(clippingAncestor).toContainElement(dialog);+ expect(dialog).toHaveAttribute('open');+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalledTimes(1);+ });++ it('keeps focus in a modal sheet that has no tabbable controls', () => {+ render(+ <>+ <button type="button">Background action</button>+ <BottomSheetSwitcher+ activeSheet="details"+ onActiveSheetChange={() => {}}>+ <BottomSheet sheetId="details" label="Read-only details">+ Read-only content+ </BottomSheet>+ </BottomSheetSwitcher>+ </>,+ );++ const dialog = screen.getByRole('dialog', {name: 'Read-only details'});+ const panel = getSheetPanel(dialog);+ expect(panel).toHaveFocus();+ expect(fireEvent.keyDown(panel, {key: 'Tab'})).toBe(false);+ expect(panel).toHaveFocus();+ expect(+ screen.getByRole('button', {name: 'Background action'}),+ ).not.toHaveFocus();+ });++ it('can coordinate a non-modal flow without rendering a scrim', () => {+ render(+ <BottomSheetSwitcher+ activeSheet="details"+ onActiveSheetChange={() => {}}+ hasScrim={false}>+ <BottomSheet sheetId="details" label="Details">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>,+ );++ expect(+ document.querySelector('.astryx-bottom-sheet-switcher-scrim'),+ ).not.toBeInTheDocument();+ const dialog = screen.getByRole('dialog', {name: 'Details'});+ expect(dialog).not.toHaveAttribute('aria-modal');+ expect(dialog).toHaveAttribute('open');+ expect(HTMLDialogElement.prototype.show).toHaveBeenCalledTimes(1);+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();+ expect(document.body.style.position).not.toBe('fixed');+ });++ it('requests activeSheet=null when the active sheet dismisses', () => {+ const onActiveSheetChange = vi.fn();+ render(+ <BottomSheetSwitcher+ activeSheet="details"+ onActiveSheetChange={onActiveSheetChange}>+ <BottomSheet sheetId="details" label="Details">+ Content+ </BottomSheet>+ <BottomSheet sheetId="confirm" label="Confirm">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>,+ );++ fireEvent.keyDown(screen.getByRole('dialog', {name: 'Details'}), {+ key: 'Escape',+ });++ expect(onActiveSheetChange).toHaveBeenCalledWith(null);+ });++ it('ignores Escape while an IME composition is active', () => {+ const onActiveSheetChange = vi.fn();+ render(+ <BottomSheetSwitcher+ activeSheet="details"+ onActiveSheetChange={onActiveSheetChange}>+ <BottomSheet sheetId="details" label="Details">+ Content+ </BottomSheet>+ </BottomSheetSwitcher>,+ );++ const dialog = screen.getByRole('dialog', {name: 'Details'});+ fireEvent.keyDown(dialog, {key: 'Escape', isComposing: true});+ fireEvent.keyDown(dialog, {key: 'Escape', keyCode: 229});++ expect(onActiveSheetChange).not.toHaveBeenCalled();+ });++ it('lets a nested focus trap handle Escape before the switcher', () => {+ const onActiveSheetChange = vi.fn();+ const onNestedEscape = vi.fn();+ render(+ <BottomSheetSwitcher+ activeSheet="details"+ onActiveSheetChange={onActiveSheetChange}>+ <BottomSheet sheetId="details" label="Details">+ <NestedEscapeTrap onEscape={onNestedEscape} />+ </BottomSheet>+ </BottomSheetSwitcher>,+ );++ fireEvent.keyDown(screen.getByTestId('nested-escape-trap'), {+ key: 'Escape',+ });++ expect(onNestedEscape).toHaveBeenCalledTimes(1);+ expect(onActiveSheetChange).not.toHaveBeenCalled();+ });++ it('returns focus to the original opener after a multi-sheet flow ends', () => {+ render(<Flow />);+ const opener = screen.getByRole('button', {name: 'Start flow'});+ opener.focus();+ fireEvent.click(opener);+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));++ fireEvent.keyDown(screen.getByRole('dialog', {name: 'Confirm'}), {+ key: 'Escape',+ });+ expect(document.activeElement).not.toBe(opener);+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');++ expect(document.activeElement).toBe(opener);+ });++ it('captures a new focus trigger after switching through non-modal mode', () => {+ render(<ModeSwitchFlow />);+ const firstOpener = screen.getByRole('button', {name: 'Open first modal'});+ const secondOpener = screen.getByRole('button', {+ name: 'Open second modal',+ });++ firstOpener.focus();+ fireEvent.click(firstOpener);+ fireEvent.click(screen.getByRole('button', {name: 'Make non-modal'}));+ fireEvent.click(screen.getByRole('button', {name: 'Close flow'}));+ finishSheetTransition(getSheetLayer('mode-details-sheet'), 'transform');++ secondOpener.focus();+ fireEvent.click(secondOpener);+ fireEvent.click(screen.getByRole('button', {name: 'Close flow'}));+ finishSheetTransition(getSheetLayer('mode-details-sheet'), 'transform');++ expect(document.activeElement).toBe(secondOpener);+ });++ it('does not refocus the panel when an incoming transition completes', () => {+ render(<Flow />);+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));++ const confirmSheet = getSheetLayer('confirm-sheet');+ const backButton = screen.getByRole('button', {name: 'Back'});+ backButton.focus();+ finishSheetTransition(confirmSheet, 'transform');++ expect(backButton).toHaveFocus();+ });+});diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/lab/src/BottomSheet/BottomSheetSwitcher.tsxnew file mode 100644index 0000000000..386442e46e--- /dev/null+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcher.tsx@@ -0,0 +1,597 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file BottomSheetSwitcher.tsx+ * @input Uses React context, StyleX, theme tokens, focus/scroll-lock hooks, BottomSheetSwitcherContext+ * @output Exports BottomSheetSwitcher and BottomSheetSwitcherProps+ * @position Lab switcher for mutually exclusive BottomSheet flows+ *+ * The switcher turns a set of declaratively nested BottomSheets into a+ * controlled single-selection group: `activeSheet` names the one interactive+ * child, or is null when the flow is closed. During a handoff the new sheet+ * enters above the previous sheet. If it is shorter, the previous sheet moves+ * down at the same time until their top edges align; otherwise it stays+ * stationary. The previous sheet fades only after both motions complete.+ *+ * All child sheets render as panels inside one switcher-owned `<dialog>`. A+ * scrim flow calls showModal() once and keeps that native top-layer dialog open+ * across every handoff. A no-scrim flow calls show() on the same inline shell.+ * This keeps one modal boundary and one native ::backdrop without a portal.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/BottomSheet/BottomSheet.tsx+ * - /packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjs+ * - /packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx+ * - /packages/lab/src/BottomSheet/index.ts+ * - /apps/storybook/stories/BottomSheetSwitcher.stories.tsx+ */++import {+ useCallback,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+ type MouseEvent as ReactMouseEvent,+ type ReactNode,+ type SyntheticEvent,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '@astryxdesign/core';+import {+ colorVars,+ durationVars,+ easeVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import {+ hasActiveFocusTrapEscape,+ isImeKeyEvent,+ useFocusTrap,+ useScrollLock,+} from '@astryxdesign/core/hooks';+import {+ composeEventHandlers,+ mergeProps,+ mergeRefs,+ themeProps,+} from '@astryxdesign/core/utils';+import {+ BottomSheetSwitcherContext,+ type BottomSheetSwitcherContextValue,+ type BottomSheetSwitcherPhase,+ type BottomSheetSwitcherTransitionEvent,+} from './BottomSheetSwitcherContext';++const styles = stylex.create({+ dialog: {+ position: 'fixed',+ inset: 0,+ width: '100dvw',+ height: '100dvh',+ maxWidth: 'none',+ maxHeight: 'none',+ margin: 0,+ padding: 0,+ border: 'none',+ backgroundColor: 'transparent',+ overflow: 'visible',+ display: 'none',+ outline: 'none',+ },+ dialogOpen: {+ display: 'block',+ },+ // show() leaves a no-scrim flow in the normal rendering tree. The shell must+ // pass pointer input through to the live page; each sheet panel opts back in.+ // width/height 100% avoids overflowing a transformed containing block, but+ // consumers of this non-modal mode must still avoid clipping ancestors.+ dialogNonModal: {+ pointerEvents: 'none',+ zIndex: 1000,+ width: '100%',+ height: '100%',+ },+ scrim: {+ '::backdrop': {+ backgroundColor: colorVars['--color-overlay'],+ opacity: {+ default: 'var(--_sheet-scrim-opacity, 1)',+ '@starting-style': 0,+ },+ transitionProperty: 'opacity, display',+ transitionDuration: durationVars['--duration-medium'],+ transitionTimingFunction: easeVars['--ease-standard'],+ transitionBehavior: 'allow-discrete',+ '@media (prefers-reduced-motion: reduce)': {+ transitionDuration: '0.01s',+ },+ },+ },+});++type RetainedSheetPhase = 'covered' | 'aligning' | 'fading' | 'exiting';++interface SheetTransitionState {+ enteringSheet: string | null;+ retainedSheet: string | null;+ retainedPhase: RetainedSheetPhase | null;+ alignmentOffset: number;+ isAlignmentComplete: boolean;+}++const IDLE_TRANSITION: SheetTransitionState = {+ enteringSheet: null,+ retainedSheet: null,+ retainedPhase: null,+ alignmentOffset: 0,+ isAlignmentComplete: false,+};++const ALIGNMENT_THRESHOLD_PX = 1;++function transitionForActiveSheetChange(+ previousSheet: string | null,+ nextSheet: string | null,+): SheetTransitionState {+ if (previousSheet == null) {+ return IDLE_TRANSITION;+ }+ if (nextSheet == null) {+ return {+ enteringSheet: null,+ retainedSheet: previousSheet,+ retainedPhase: 'exiting',+ alignmentOffset: 0,+ isAlignmentComplete: false,+ };+ }+ return {+ enteringSheet: nextSheet,+ retainedSheet: previousSheet,+ retainedPhase: 'covered',+ alignmentOffset: 0,+ isAlignmentComplete: false,+ };+}++function alignmentOffsetForElements(+ enteringElement: HTMLElement | undefined,+ retainedElement: HTMLElement | undefined,+): number {+ if (enteringElement == null || retainedElement == null) {+ return 0;+ }+ const enteringPositioner = enteringElement.parentElement;+ const enteringTop =+ enteringPositioner?.getBoundingClientRect().top ??+ enteringElement.getBoundingClientRect().top;+ return Math.max(0, enteringTop - retainedElement.getBoundingClientRect().top);+}++export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {+ /** Ref forwarded to the shared native dialog. */+ ref?: React.Ref<HTMLDialogElement>;++ /** Called when the shared native dialog receives a cancel event. */+ onCancel?: (event: SyntheticEvent<HTMLDialogElement>) => void;++ /**+ * ID of the interactive BottomSheet, or null when the flow should close.+ * Must match a nested BottomSheet's `sheetId`. The previous sheet may remain+ * visually present and inert while the new sheet enters, moving downward at+ * the same time if the new sheet is shorter, then fade away.+ */+ activeSheet: string | null;++ /** Called with null when the active sheet requests dismissal. */+ onActiveSheetChange: (sheetId: string | null) => void;++ /**+ * Whether to open the shared dialog modally with its native ::backdrop.+ * Disable for an inline, non-modal flow over an interactive page.+ * @default true+ */+ hasScrim?: boolean;++ /** BottomSheets identified by unique `sheetId` values. */+ children: ReactNode;+}++/**+ * Coordinates a set of BottomSheets so zero or one is active at a time inside+ * one shared native dialog. During a handoff the previous panel stays visible+ * and inert beneath the entering panel, then fades after motion completes.+ */+export function BottomSheetSwitcher({+ activeSheet,+ onActiveSheetChange,+ hasScrim = true,+ children,+ ref,+ xstyle,+ className,+ style,+ onCancel,+ onClick,+ onKeyDown,+ ...props+}: BottomSheetSwitcherProps) {+ const dialogRef = useRef<HTMLDialogElement | null>(null);+ const dialogModeRef = useRef<'modal' | 'non-modal' | null>(null);+ const triggerRef = useRef<HTMLElement | null>(null);+ const sheetElementsRef = useRef(new Map<string, HTMLElement>());+ const committedActiveSheetRef = useRef(activeSheet);+ const [sheetLabels, setSheetLabels] = useState<ReadonlyMap<string, string>>(+ () => new Map(),+ );+ const [unmountedSheetIds, setUnmountedSheetIds] = useState<+ ReadonlySet<string>+ >(() => new Set());+ const [transition, setTransition] =+ useState<SheetTransitionState>(IDLE_TRANSITION);++ const activeSheetChanged = committedActiveSheetRef.current !== activeSheet;+ const visibleTransition = activeSheetChanged+ ? transitionForActiveSheetChange(+ committedActiveSheetRef.current,+ activeSheet,+ )+ : transition;+ const isFlowVisible =+ (activeSheet != null && !unmountedSheetIds.has(activeSheet)) ||+ (visibleTransition.retainedSheet != null &&+ !unmountedSheetIds.has(visibleTransition.retainedSheet));+ const isModal = hasScrim && isFlowVisible;++ useLayoutEffect(() => {+ const previousActiveSheet = committedActiveSheetRef.current;+ if (previousActiveSheet === activeSheet) {+ return;+ }+ committedActiveSheetRef.current = activeSheet;+ const nextTransition = transitionForActiveSheetChange(+ previousActiveSheet,+ activeSheet,+ );+ setTransition(+ nextTransition.retainedSheet != null &&+ !sheetElementsRef.current.has(nextTransition.retainedSheet)+ ? IDLE_TRANSITION+ : nextTransition,+ );+ }, [activeSheet]);++ const close = useCallback(+ () => onActiveSheetChange(null),+ [onActiveSheetChange],+ );+ const {containerRef} = useFocusTrap<HTMLDialogElement>({+ isActive: isModal,+ onEscape: close,+ });+ useScrollLock(isModal);++ // Open one shared shell for the complete flow. Modal flows enter the native+ // top layer once; handoffs only swap panels inside it. The final panel owns+ // the exit timing, so isFlowVisible becomes false only when it is safe to+ // close the dialog and restore focus.+ useLayoutEffect(() => {+ const dialog = dialogRef.current;+ if (dialog == null) {+ return;+ }++ if (isFlowVisible) {+ const nextMode = hasScrim ? 'modal' : 'non-modal';+ if (dialog.open && dialogModeRef.current !== nextMode) {+ dialog.close();+ }+ if (!dialog.open) {+ if (hasScrim && triggerRef.current == null) {+ triggerRef.current = document.activeElement as HTMLElement | null;+ }+ if (hasScrim) {+ dialog.showModal();+ } else {+ dialog.show();+ }+ }+ dialogModeRef.current = nextMode;+ return;+ }++ if (dialog.open) {+ dialog.close();+ }+ if (dialogModeRef.current === 'modal') {+ triggerRef.current?.focus();+ }+ triggerRef.current = null;+ dialogModeRef.current = null;+ }, [hasScrim, isFlowVisible]);++ const getSheetPhase = useCallback(+ (sheetId: string): BottomSheetSwitcherPhase => {+ if (sheetId === activeSheet) {+ return sheetId === visibleTransition.enteringSheet+ ? 'entering'+ : 'active';+ }+ if (sheetId === visibleTransition.retainedSheet) {+ return visibleTransition.retainedPhase ?? 'hidden';+ }+ return 'hidden';+ },+ [activeSheet, visibleTransition],+ );++ const getSheetAlignmentOffset = useCallback(+ (sheetId: string) =>+ visibleTransition.retainedSheet === sheetId+ ? visibleTransition.alignmentOffset+ : 0,+ [visibleTransition],+ );++ const registerSheetElement = useCallback(+ (sheetId: string, element: HTMLElement | null) => {+ if (element == null) {+ sheetElementsRef.current.delete(sheetId);+ setUnmountedSheetIds(current => {+ if (current.has(sheetId)) {+ return current;+ }+ const next = new Set(current);+ next.add(sheetId);+ return next;+ });+ setTransition(current =>+ current.retainedSheet === sheetId ? IDLE_TRANSITION : current,+ );+ } else {+ sheetElementsRef.current.set(sheetId, element);+ setUnmountedSheetIds(current => {+ if (!current.has(sheetId)) {+ return current;+ }+ const next = new Set(current);+ next.delete(sheetId);+ return next;+ });+ }+ },+ [],+ );++ const registerSheetLabel = useCallback(+ (sheetId: string, label: string | null) => {+ setSheetLabels(current => {+ if (label == null) {+ if (!current.has(sheetId)) {+ return current;+ }+ const next = new Map(current);+ next.delete(sheetId);+ return next;+ }+ if (current.get(sheetId) === label) {+ return current;+ }+ const next = new Map(current);+ next.set(sheetId, label);+ return next;+ });+ },+ [],+ );++ useLayoutEffect(() => {+ setTransition(current =>+ current.retainedSheet != null &&+ unmountedSheetIds.has(current.retainedSheet)+ ? IDLE_TRANSITION+ : current,+ );+ }, [unmountedSheetIds]);++ const onSheetEnterStart = useCallback((sheetId: string) => {+ setTransition(current => {+ if (+ current.enteringSheet !== sheetId ||+ current.retainedSheet == null ||+ current.retainedPhase !== 'covered'+ ) {+ return current;+ }+ const alignmentOffset = alignmentOffsetForElements(+ sheetElementsRef.current.get(sheetId),+ sheetElementsRef.current.get(current.retainedSheet),+ );+ if (alignmentOffset <= ALIGNMENT_THRESHOLD_PX) {+ return current;+ }+ return {+ ...current,+ retainedPhase: 'aligning',+ alignmentOffset,+ isAlignmentComplete: false,+ };+ });+ }, []);++ const onSheetTransitionComplete = useCallback(+ ({sheetId, phase}: BottomSheetSwitcherTransitionEvent) => {+ setTransition(current => {+ if (phase === 'entering') {+ if (current.enteringSheet !== sheetId) {+ return current;+ }+ if (current.retainedSheet == null) {+ return IDLE_TRANSITION;+ }+ if (+ current.retainedPhase === 'aligning' &&+ !current.isAlignmentComplete+ ) {+ return {...current, enteringSheet: null};+ }+ return {+ ...current,+ enteringSheet: null,+ retainedPhase: 'fading',+ };+ }++ if (+ phase === 'aligning' &&+ current.retainedSheet === sheetId &&+ current.retainedPhase === 'aligning'+ ) {+ return current.enteringSheet == null+ ? {...current, retainedPhase: 'fading'}+ : {...current, isAlignmentComplete: true};+ }++ if (+ (phase === 'fading' || phase === 'exiting') &&+ current.retainedSheet === sheetId &&+ current.retainedPhase === phase+ ) {+ return IDLE_TRANSITION;+ }++ return current;+ });+ },+ [],+ );++ const setScrimOpacity = useCallback((opacity: number) => {+ dialogRef.current?.style.setProperty(+ '--_sheet-scrim-opacity',+ String(opacity),+ );+ }, []);+ const onSheetScrimOpacityChange = useCallback(+ (sheetId: string, opacity: number) => {+ // A pointer captured by the outgoing sheet can keep delivering gesture+ // events after a handoff. Only the currently committed sheet owns the+ // shared backdrop, so stale gesture updates must not reach the dialog.+ if (sheetId !== committedActiveSheetRef.current) {+ return;+ }+ setScrimOpacity(opacity);+ },+ [setScrimOpacity],+ );++ useLayoutEffect(() => {+ setScrimOpacity(activeSheet == null ? 0 : 1);+ }, [activeSheet, setScrimOpacity]);++ const contextValue = useMemo<BottomSheetSwitcherContextValue>(+ () => ({+ activeSheet,+ hasScrim,+ onActiveSheetChange,+ getSheetPhase,+ getSheetAlignmentOffset,+ registerSheetElement,+ registerSheetLabel,+ onSheetEnterStart,+ onSheetTransitionComplete,+ onSheetScrimOpacityChange,+ }),+ [+ activeSheet,+ getSheetAlignmentOffset,+ getSheetPhase,+ hasScrim,+ onActiveSheetChange,+ onSheetEnterStart,+ onSheetScrimOpacityChange,+ onSheetTransitionComplete,+ registerSheetElement,+ registerSheetLabel,+ ],+ );++ const activeLabel =+ (activeSheet == null ? null : sheetLabels.get(activeSheet)) ??+ (visibleTransition.retainedSheet == null+ ? undefined+ : sheetLabels.get(visibleTransition.retainedSheet));++ const handleCancel = useCallback(+ (event: SyntheticEvent<HTMLDialogElement>) => {+ event.preventDefault();+ close();+ },+ [close],+ );+ const handleKeyDown = useCallback(+ (event: ReactKeyboardEvent<HTMLDialogElement>) => {+ // Modal Escape is owned by useFocusTrap so nested traps can win. A+ // non-modal switcher has no outer trap, so retain local dismissal while+ // deferring to an active nested layer and ignoring IME cancellation.+ if (+ !isModal &&+ event.key === 'Escape' &&+ !isImeKeyEvent(event.nativeEvent) &&+ !hasActiveFocusTrapEscape()+ ) {+ event.preventDefault();+ close();+ }+ },+ [close, isModal],+ );+ const handleClick = useCallback(+ (event: ReactMouseEvent<HTMLDialogElement>) => {+ if (hasScrim && event.target === event.currentTarget) {+ close();+ }+ },+ [close, hasScrim],+ );++ const dialogStyleProps = stylex.props(+ styles.dialog,+ isFlowVisible && styles.dialogOpen,+ hasScrim && styles.scrim,+ !hasScrim && styles.dialogNonModal,+ xstyle,+ );+ const dialogPresentationProps = hasScrim+ ? mergeProps(+ themeProps('bottom-sheet-switcher-scrim'),+ dialogStyleProps,+ className,+ style,+ )+ : mergeProps(dialogStyleProps, className, style);+ const ariaLabel =+ props['aria-label'] ??+ (props['aria-labelledby'] == null ? activeLabel : undefined);++ return (+ <BottomSheetSwitcherContext.Provider value={contextValue}>+ <dialog+ {...props}+ {...dialogPresentationProps}+ ref={mergeRefs(ref, dialogRef, containerRef)}+ aria-label={ariaLabel}+ aria-modal={isModal ? 'true' : undefined}+ onCancel={composeEventHandlers(onCancel, handleCancel)}+ onClick={composeEventHandlers(onClick, handleClick)}+ onKeyDown={composeEventHandlers(onKeyDown, handleKeyDown)}>+ {children}+ </dialog>+ </BottomSheetSwitcherContext.Provider>+ );+}++BottomSheetSwitcher.displayName = 'BottomSheetSwitcher';diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcherContext.ts b/packages/lab/src/BottomSheet/BottomSheetSwitcherContext.tsnew file mode 100644index 0000000000..af58d9c587--- /dev/null+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcherContext.ts@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file BottomSheetSwitcherContext.ts+ * @input Uses React context+ * @output Internal phase and lifecycle context shared by BottomSheetSwitcher and BottomSheet+ * @position Private coordination layer for mutually exclusive BottomSheets+ */++import {createContext} from 'react';++export type BottomSheetSwitcherPhase =+ | 'entering'+ | 'active'+ | 'covered'+ | 'aligning'+ | 'fading'+ | 'exiting'+ | 'hidden';++export interface BottomSheetSwitcherTransitionEvent {+ sheetId: string;+ phase: 'entering' | 'aligning' | 'fading' | 'exiting';+}++export interface BottomSheetSwitcherContextValue {+ activeSheet: string | null;+ hasScrim: boolean;+ onActiveSheetChange: (sheetId: string | null) => void;+ getSheetPhase: (sheetId: string) => BottomSheetSwitcherPhase;+ getSheetAlignmentOffset: (sheetId: string) => number;+ registerSheetElement: (sheetId: string, element: HTMLElement | null) => void;+ registerSheetLabel: (sheetId: string, label: string | null) => void;+ onSheetEnterStart: (sheetId: string) => void;+ onSheetTransitionComplete: (+ event: BottomSheetSwitcherTransitionEvent,+ ) => void;+ onSheetScrimOpacityChange: (sheetId: string, opacity: number) => void;+}++export const BottomSheetSwitcherContext =+ createContext<BottomSheetSwitcherContextValue | null>(null);++BottomSheetSwitcherContext.displayName = 'BottomSheetSwitcherContext';diff --git a/packages/lab/src/BottomSheet/index.ts b/packages/lab/src/BottomSheet/index.tsindex 661f21083b..87d0c132a7 100644--- a/packages/lab/src/BottomSheet/index.ts+++ b/packages/lab/src/BottomSheet/index.ts@@ -2,10 +2,12 @@/*** @file index.ts- * @input BottomSheet.tsx- * @output Re-exports BottomSheet component and BottomSheetProps type+ * @input BottomSheet.tsx, BottomSheetSwitcher.tsx+ * @output Re-exports the BottomSheet public API* @position Lab entry point for the BottomSheet directory*/export {BottomSheet} from './BottomSheet';export type {BottomSheetProps} from './BottomSheet';+export {BottomSheetSwitcher} from './BottomSheetSwitcher';+export type {BottomSheetSwitcherProps} from './BottomSheetSwitcher';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 12a9ad2880..f4f019d42b 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -46,7 +46,12 @@ export * from './Chat';export {Drawer, type DrawerProps} from './Drawer';// BottomSheet — mobile touch sheet on a native modal <dialog>-export {BottomSheet, type BottomSheetProps} from './BottomSheet';+export {+ BottomSheet,+ type BottomSheetProps,+ BottomSheetSwitcher,+ type BottomSheetSwitcherProps,+} from './BottomSheet';// Tour — guided product-tour / NUX walkthrough (facebook/astryx#4239)export {