Skip to content

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

TypeScript

feat(lab): add purpose to BottomSheet (#5086)

Xinzi Zhou10bcaa15879c
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsx
index b90b890f7e..64bbd41949 100644
--- a/apps/storybook/stories/BottomSheet.stories.tsx
+++ b/apps/storybook/stories/BottomSheet.stories.tsx
@@ -176,6 +176,35 @@ export const Showcase: Story = {
},
};
+export const FormPurpose: Story = {
+ name: 'Form purpose',
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Button label="Edit profile" onClick={() => setIsOpen(true)} />
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ purpose="form"
+ label="Edit profile"
+ height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <Heading level={3}>Edit profile</Heading>
+ <Text type="supporting" color="secondary">
+ Swiping down or clicking the scrim keeps this form open. Escape
+ and the explicit actions can still close it.
+ </Text>
+ <Button label="Save changes" onClick={() => setIsOpen(false)} />
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+ },
+};
+
export const TallSheet: Story = {
render: () => {
const [isOpen, setIsOpen] = useState(false);
diff --git a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs
index 49af24da83..6bf555f67c 100644
--- a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs
+++ b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs
@@ -54,7 +54,7 @@ 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. 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>.",
+ "A mobile touch sheet that rises from the bottom edge, with animated entrance and exit, a grab handle, drag-to-resize snap points, and purpose-controlled dismissal. 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',
@@ -66,7 +66,14 @@ export const docs = {
name: 'onOpenChange',
type: '(isOpen: boolean) => void',
description:
- '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.',
+ 'For a standalone sheet, called when it requests an open-state change. Automatic calls follow purpose: info dismisses on Escape, scrim click, or swipe; form dismisses on Escape only; required never dismisses implicitly. Omit inside BottomSheetSwitcher.',
+ },
+ {
+ name: 'purpose',
+ type: "'required' | 'form' | 'info'",
+ description:
+ "Controls implicit dismissal behavior, matching Dialog. info allows Escape, scrim click, and swipe-to-dismiss. form protects entered data by blocking scrim click and swipe while allowing Escape. required blocks every implicit dismissal path and uses role='alertdialog'. Explicit controls may still update the controlled state. Works for standalone and BottomSheetSwitcher-managed sheets.",
+ default: "'info'",
},
{
name: 'sheetId',
@@ -99,7 +106,7 @@ export const docs = {
name: 'hasScrim',
type: 'boolean',
description:
- '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.',
+ "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 when purpose='info', 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',
},
],
@@ -117,6 +124,11 @@ export const docs = {
description:
"Pick the starting height that fits the content: 'hug' for short bounded content, 'capped' for lists, and 'tall' for forms or streaming/resizing content.",
},
+ {
+ guidance: true,
+ description:
+ "Use purpose='form' to protect entered data from scrim clicks and swipes while keeping Escape available; reserve purpose='required' for flows that must end through an explicit action.",
+ },
{
guidance: false,
description:
@@ -194,6 +206,17 @@ export const docs = {
label="Nearby places"
hasScrim={false}>
<PlaceList />
+</BottomSheet>`,
+ },
+ {
+ label: 'Protect form input',
+ code: `const [isOpen, setIsOpen] = useState(false);
+<BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ purpose="form"
+ label="Edit profile">
+ <ProfileForm onSave={() => setIsOpen(false)} />
</BottomSheet>`,
},
],
@@ -202,7 +225,7 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
description:
- 'mobile touch sheet rising from the bottom edge (native <dialog>): grab handle, drag-to-resize snap points, swipe-to-dismiss, fully-expanded Tall visual-viewport mobile-keyboard handling, named height scale, modal (default) or non-modal (hasScrim={false}) presentation',
+ 'mobile touch sheet rising from the bottom edge (native <dialog>): grab handle, drag-to-resize snap points, Dialog-aligned dismissal purpose (info/form/required), fully-expanded Tall visual-viewport mobile-keyboard handling, named height scale, modal (default) or non-modal (hasScrim={false}) presentation',
usage: {
description:
'Mobile touch surface for filters, actions, forms, and detail views that should rise from the bottom of the viewport; use BottomSheetSwitcher for multi-step flows.',
@@ -217,6 +240,11 @@ export const docsDense = {
description:
"Pick the starting height that fits the content: 'hug' for short bounded content, 'capped' for lists, and 'tall' for forms or streaming/resizing content.",
},
+ {
+ guidance: true,
+ description:
+ "Use purpose='form' to protect entered data from scrim clicks and swipes while keeping Escape available; reserve purpose='required' for flows that must end through an explicit action.",
+ },
{
guidance: false,
description:
diff --git a/packages/lab/src/BottomSheet/BottomSheet.test.tsx b/packages/lab/src/BottomSheet/BottomSheet.test.tsx
index 00129b350c..98da4c284a 100644
--- a/packages/lab/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/lab/src/BottomSheet/BottomSheet.test.tsx
@@ -320,6 +320,55 @@ describe('BottomSheet', () => {
expect(onOpenChange).toHaveBeenCalledWith(false);
});
+ it('purpose=form blocks scrim and swipe dismissal but allows Escape', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <BottomSheet
+ isOpen
+ purpose="form"
+ onOpenChange={onOpenChange}
+ label="Edit profile">
+ Content
+ </BottomSheet>,
+ );
+ const dialog = screen.getByRole('dialog');
+
+ fireEvent.click(dialog);
+ drag(getHandle(), [{y: 0}, {y: 40}, {y: 120}]);
+
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(dialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});
+
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ fireEvent(dialog, new Event('cancel', {cancelable: true}));
+
+ expect(onOpenChange).toHaveBeenCalledTimes(2);
+ expect(onOpenChange).toHaveBeenNthCalledWith(1, false);
+ expect(onOpenChange).toHaveBeenNthCalledWith(2, false);
+ });
+
+ it('purpose=required blocks every implicit dismissal path', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <BottomSheet
+ isOpen
+ purpose="required"
+ onOpenChange={onOpenChange}
+ label="Required action">
+ Content
+ </BottomSheet>,
+ );
+ const dialog = screen.getByRole('alertdialog');
+
+ fireEvent.click(dialog);
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ fireEvent(dialog, new Event('cancel', {cancelable: true}));
+ drag(getHandle(), [{y: 0}, {y: 40}, {y: 120}]);
+
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(dialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});
+ });
+
it('keeps a standalone modal sheet presented through its exit animation', () => {
render(<ExitHarness />);
const dialog = screen.getByRole('dialog', {name: 'Filters'});
diff --git a/packages/lab/src/BottomSheet/BottomSheet.tsx b/packages/lab/src/BottomSheet/BottomSheet.tsx
index 0e2a50ceac..ee8ece4b5c 100644
--- a/packages/lab/src/BottomSheet/BottomSheet.tsx
+++ b/packages/lab/src/BottomSheet/BottomSheet.tsx
@@ -34,6 +34,7 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
+import type {DialogPurpose} from '@astryxdesign/core/Dialog';
import {
colorVars,
durationVars,
@@ -123,6 +124,15 @@ interface BottomSheetSharedProps extends BaseProps<HTMLDivElement> {
/** Height budget or custom CSS length. Only fully expanded Tall is keyboard-aware. @default 'capped' */
height?: BottomSheetHeight | number | string;
+
+ /**
+ * Configures implicit dismissal behavior, matching Dialog.
+ * - required: Blocks swipe, scrim click, and Escape
+ * - form: Blocks swipe and scrim click, allows Escape
+ * - info: Allows swipe, scrim click, and Escape
+ * @default 'info'
+ */
+ purpose?: DialogPurpose;
}
interface StandaloneBottomSheetProps extends BottomSheetSharedProps {
@@ -183,6 +193,7 @@ function StandaloneBottomSheet({
children,
height = 'capped',
hasScrim = true,
+ purpose = 'info',
xstyle,
...props
}: StandaloneBottomSheetProps) {
@@ -197,7 +208,16 @@ function StandaloneBottomSheet({
? {kind: 'exiting'}
: {kind: 'hidden'};
- const close = useCallback(() => onOpenChange(false), [onOpenChange]);
+ const dismissOnEscape = useCallback(() => {
+ if (purpose !== 'required') {
+ onOpenChange(false);
+ }
+ }, [onOpenChange, purpose]);
+ const dismissOnLightInteraction = useCallback(() => {
+ if (purpose === 'info') {
+ onOpenChange(false);
+ }
+ }, [onOpenChange, purpose]);
const handlePanelElementChange = useCallback(
(element: HTMLDivElement | null) => {
panelRef.current = element;
@@ -264,26 +284,26 @@ function StandaloneBottomSheet({
const handleCancel = useCallback(
(event: React.SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
- close();
+ dismissOnEscape();
},
- [close],
+ [dismissOnEscape],
);
const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDialogElement>) => {
if (event.key === 'Escape') {
event.preventDefault();
- close();
+ dismissOnEscape();
}
},
- [close],
+ [dismissOnEscape],
);
const handleClick = useCallback(
(event: React.MouseEvent<HTMLDialogElement>) => {
if (hasScrim && event.target === event.currentTarget) {
- close();
+ dismissOnLightInteraction();
}
},
- [close, hasScrim],
+ [dismissOnLightInteraction, hasScrim],
);
return (
@@ -298,6 +318,7 @@ function StandaloneBottomSheet({
aria-label={label}
aria-hidden={!isOpen && isPresented ? 'true' : undefined}
aria-modal={hasScrim && isOpen ? 'true' : undefined}
+ role={purpose === 'required' ? 'alertdialog' : undefined}
inert={!isOpen && isPresented ? true : undefined}
onCancel={handleCancel}
onClick={handleClick}
@@ -308,8 +329,9 @@ function StandaloneBottomSheet({
ref={ref}
state={panelState}
height={height}
+ canSwipeDismiss={purpose === 'info'}
xstyle={xstyle}
- onDismiss={close}
+ onDismiss={dismissOnLightInteraction}
onScrimOpacity={handleScrimOpacity}
onElementChange={handlePanelElementChange}
onMotionComplete={handleMotionComplete}>
@@ -331,6 +353,7 @@ function SwitcherBottomSheetItem({
label,
children,
height = 'capped',
+ purpose = 'info',
xstyle,
...props
}: SwitcherBottomSheetItemProps) {
@@ -342,6 +365,7 @@ function SwitcherBottomSheetItem({
getSheetAlignmentOffset,
registerSheetElement,
registerSheetLabel,
+ registerSheetPurpose,
onSheetEnterStart,
onSheetTransitionComplete,
onSheetScrimOpacityChange,
@@ -369,11 +393,11 @@ function SwitcherBottomSheetItem({
previousPhaseRef.current = phase;
}, [phase]);
- const close = useCallback(() => {
- if (hasValidSheetId && activeSheet === sheetId) {
+ const dismissOnSwipe = useCallback(() => {
+ if (purpose === 'info' && hasValidSheetId && activeSheet === sheetId) {
onActiveSheetChange(null);
}
- }, [activeSheet, hasValidSheetId, onActiveSheetChange, sheetId]);
+ }, [activeSheet, hasValidSheetId, onActiveSheetChange, purpose, sheetId]);
const handlePanelElementChange = useCallback(
(element: HTMLDivElement | null) => {
panelRef.current = element;
@@ -416,6 +440,14 @@ function SwitcherBottomSheetItem({
return () => registerSheetLabel(sheetId, null);
}, [hasValidSheetId, label, registerSheetLabel, sheetId]);
+ useLayoutEffect(() => {
+ if (!hasValidSheetId) {
+ return;
+ }
+ registerSheetPurpose(sheetId, purpose);
+ return () => registerSheetPurpose(sheetId, null);
+ }, [hasValidSheetId, purpose, registerSheetPurpose, sheetId]);
+
useEffect(() => {
if (isInteractive) {
const wasInteractive =
@@ -451,8 +483,9 @@ function SwitcherBottomSheetItem({
ref={ref}
state={panelState}
height={height}
+ canSwipeDismiss={purpose === 'info'}
xstyle={xstyle}
- onDismiss={close}
+ onDismiss={dismissOnSwipe}
onScrimOpacity={handleScrimOpacity}
onElementChange={handlePanelElementChange}
onMotionStart={handleMotionStart}
diff --git a/packages/lab/src/BottomSheet/BottomSheetPanel.tsx b/packages/lab/src/BottomSheet/BottomSheetPanel.tsx
index 7385d222b2..0bf75f456d 100644
--- a/packages/lab/src/BottomSheet/BottomSheetPanel.tsx
+++ b/packages/lab/src/BottomSheet/BottomSheetPanel.tsx
@@ -163,6 +163,7 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {
state: BottomSheetPanelState;
height: BottomSheetHeight | number | string;
children: ReactNode;
+ canSwipeDismiss?: boolean;
onDismiss: () => void;
onScrimOpacity: (opacity: number) => void;
onElementChange?: (element: HTMLDivElement | null) => void;
@@ -289,6 +290,7 @@ export function BottomSheetPanel({
style,
tabIndex,
xstyle,
+ canSwipeDismiss = true,
onDismiss,
onScrimOpacity,
onElementChange,
@@ -338,6 +340,7 @@ export function BottomSheetPanel({
isDragging,
} = useSheetGestures({
isOpen: isInteractive,
+ canDismiss: canSwipeDismiss,
onDismiss,
snapHeights: defaultSnapHeights,
onScrimOpacity,
diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjs b/packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjs
index e764101fb4..dda74fece6 100644
--- a/packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjs
+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcher.doc.mjs
@@ -21,14 +21,14 @@ export const docs = {
name: 'onActiveSheetChange',
type: '(activeSheet: 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.',
+ "Called with null when the active sheet dismisses according to its purpose. Child BottomSheets may use purpose='form' or purpose='required' to limit implicit dismissal while flow controls can still use the same state setter to switch sheets or close the flow.",
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.',
+ "Whether the shared dialog is modal. true uses showModal() once for one native ::backdrop, focus trap, scroll lock, and click-to-dismiss when the active BottomSheet has purpose='info'. 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',
},
{
diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx b/packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx
index 43db598f29..0f2e79c337 100644
--- a/packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx
+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcher.test.tsx
@@ -646,6 +646,72 @@ describe('BottomSheetSwitcher', () => {
expect(onActiveSheetChange).toHaveBeenCalledWith(null);
});
+ it('honors purpose=form for a switcher-managed sheet', () => {
+ const onActiveSheetChange = vi.fn();
+ render(
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={onActiveSheetChange}>
+ <BottomSheet sheetId="details" label="Edit details" purpose="form">
+ Content
+ </BottomSheet>
+ </BottomSheetSwitcher>,
+ );
+ const dialog = getSharedDialog();
+ const panel = getSheetPanel(dialog);
+ const handle = panel.firstElementChild;
+ if (!(handle instanceof HTMLElement)) {
+ throw new Error('sheet handle not found');
+ }
+
+ fireEvent.click(dialog);
+ fireEvent.pointerDown(handle, {pointerId: 1, clientY: 0});
+ fireEvent.pointerMove(handle, {pointerId: 1, clientY: 120});
+ fireEvent.pointerUp(handle, {pointerId: 1, clientY: 120});
+
+ expect(onActiveSheetChange).not.toHaveBeenCalled();
+ expect(dialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});
+
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ fireEvent(dialog, new Event('cancel', {cancelable: true}));
+
+ expect(onActiveSheetChange).toHaveBeenCalledTimes(2);
+ expect(onActiveSheetChange).toHaveBeenNthCalledWith(1, null);
+ expect(onActiveSheetChange).toHaveBeenNthCalledWith(2, null);
+ });
+
+ it('honors purpose=required for a switcher-managed sheet', () => {
+ const onActiveSheetChange = vi.fn();
+ render(
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={onActiveSheetChange}>
+ <BottomSheet
+ sheetId="details"
+ label="Required details"
+ purpose="required">
+ Content
+ </BottomSheet>
+ </BottomSheetSwitcher>,
+ );
+ const dialog = screen.getByRole('alertdialog');
+ const panel = getSheetPanel(dialog);
+ const handle = panel.firstElementChild;
+ if (!(handle instanceof HTMLElement)) {
+ throw new Error('sheet handle not found');
+ }
+
+ fireEvent.click(dialog);
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ fireEvent(dialog, new Event('cancel', {cancelable: true}));
+ fireEvent.pointerDown(handle, {pointerId: 1, clientY: 0});
+ fireEvent.pointerMove(handle, {pointerId: 1, clientY: 120});
+ fireEvent.pointerUp(handle, {pointerId: 1, clientY: 120});
+
+ expect(onActiveSheetChange).not.toHaveBeenCalled();
+ expect(dialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});
+ });
+
it('ignores Escape while an IME composition is active', () => {
const onActiveSheetChange = vi.fn();
render(
diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/lab/src/BottomSheet/BottomSheetSwitcher.tsx
index ed5dac3f82..37d85e7774 100644
--- a/packages/lab/src/BottomSheet/BottomSheetSwitcher.tsx
+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcher.tsx
@@ -41,6 +41,7 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
+import type {DialogPurpose} from '@astryxdesign/core/Dialog';
import {
colorVars,
durationVars,
@@ -226,6 +227,9 @@ export function BottomSheetSwitcher({
const [sheetLabels, setSheetLabels] = useState<ReadonlyMap<string, string>>(
() => new Map(),
);
+ const [sheetPurposes, setSheetPurposes] = useState<
+ ReadonlyMap<string, DialogPurpose>
+ >(() => new Map());
const [unmountedSheetIds, setUnmountedSheetIds] = useState<
ReadonlySet<string>
>(() => new Set());
@@ -244,6 +248,10 @@ export function BottomSheetSwitcher({
(visibleTransition.retainedSheet != null &&
!unmountedSheetIds.has(visibleTransition.retainedSheet));
const isModal = hasScrim && isFlowVisible;
+ const activeSheetPurpose =
+ (activeSheet == null ? null : sheetPurposes.get(activeSheet)) ?? 'info';
+ const allowsEscapeDismiss = activeSheetPurpose !== 'required';
+ const allowsLightDismiss = activeSheetPurpose === 'info';
useLayoutEffect(() => {
const previousActiveSheet = committedActiveSheetRef.current;
@@ -263,13 +271,19 @@ export function BottomSheetSwitcher({
);
}, [activeSheet]);
- const close = useCallback(
- () => onActiveSheetChange(null),
- [onActiveSheetChange],
- );
+ const dismissOnEscape = useCallback(() => {
+ if (allowsEscapeDismiss) {
+ onActiveSheetChange(null);
+ }
+ }, [allowsEscapeDismiss, onActiveSheetChange]);
+ const dismissOnLightInteraction = useCallback(() => {
+ if (allowsLightDismiss) {
+ onActiveSheetChange(null);
+ }
+ }, [allowsLightDismiss, onActiveSheetChange]);
const {containerRef} = useFocusTrap<HTMLDialogElement>({
isActive: isModal,
- onEscape: close,
+ onEscape: dismissOnEscape,
});
useScrollLock(isModal);
@@ -387,6 +401,28 @@ export function BottomSheetSwitcher({
[],
);
+ const registerSheetPurpose = useCallback(
+ (sheetId: string, purpose: DialogPurpose | null) => {
+ setSheetPurposes(current => {
+ if (purpose == null) {
+ if (!current.has(sheetId)) {
+ return current;
+ }
+ const next = new Map(current);
+ next.delete(sheetId);
+ return next;
+ }
+ if (current.get(sheetId) === purpose) {
+ return current;
+ }
+ const next = new Map(current);
+ next.set(sheetId, purpose);
+ return next;
+ });
+ },
+ [],
+ );
+
useLayoutEffect(() => {
setTransition(current =>
current.retainedSheet != null &&
@@ -500,6 +536,7 @@ export function BottomSheetSwitcher({
getSheetAlignmentOffset,
registerSheetElement,
registerSheetLabel,
+ registerSheetPurpose,
onSheetEnterStart,
onSheetTransitionComplete,
onSheetScrimOpacityChange,
@@ -515,6 +552,7 @@ export function BottomSheetSwitcher({
onSheetTransitionComplete,
registerSheetElement,
registerSheetLabel,
+ registerSheetPurpose,
],
);
@@ -527,9 +565,9 @@ export function BottomSheetSwitcher({
const handleCancel = useCallback(
(event: SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
- close();
+ dismissOnEscape();
},
- [close],
+ [dismissOnEscape],
);
const handleKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLDialogElement>) => {
@@ -543,18 +581,18 @@ export function BottomSheetSwitcher({
!hasActiveFocusTrapEscape()
) {
event.preventDefault();
- close();
+ dismissOnEscape();
}
},
- [close, isModal],
+ [dismissOnEscape, isModal],
);
const handleClick = useCallback(
(event: ReactMouseEvent<HTMLDialogElement>) => {
if (hasScrim && event.target === event.currentTarget) {
- close();
+ dismissOnLightInteraction();
}
},
- [close, hasScrim],
+ [dismissOnLightInteraction, hasScrim],
);
const dialogStyleProps = stylex.props(
@@ -583,7 +621,10 @@ export function BottomSheetSwitcher({
aria-modal={isModal ? 'true' : undefined}
onCancel={composeEventHandlers(onCancel, handleCancel)}
onClick={composeEventHandlers(onClick, handleClick)}
- onKeyDown={composeEventHandlers(onKeyDown, handleKeyDown)}>
+ onKeyDown={composeEventHandlers(onKeyDown, handleKeyDown)}
+ {...(activeSheetPurpose === 'required'
+ ? {role: 'alertdialog'}
+ : undefined)}>
{children}
</dialog>
</BottomSheetSwitcherContext.Provider>
diff --git a/packages/lab/src/BottomSheet/BottomSheetSwitcherContext.ts b/packages/lab/src/BottomSheet/BottomSheetSwitcherContext.ts
index af58d9c587..e6399fa3ad 100644
--- a/packages/lab/src/BottomSheet/BottomSheetSwitcherContext.ts
+++ b/packages/lab/src/BottomSheet/BottomSheetSwitcherContext.ts
@@ -10,6 +10,7 @@
*/
import {createContext} from 'react';
+import type {DialogPurpose} from '@astryxdesign/core/Dialog';
export type BottomSheetSwitcherPhase =
| 'entering'
@@ -33,6 +34,10 @@ export interface BottomSheetSwitcherContextValue {
getSheetAlignmentOffset: (sheetId: string) => number;
registerSheetElement: (sheetId: string, element: HTMLElement | null) => void;
registerSheetLabel: (sheetId: string, label: string | null) => void;
+ registerSheetPurpose: (
+ sheetId: string,
+ purpose: DialogPurpose | null,
+ ) => void;
onSheetEnterStart: (sheetId: string) => void;
onSheetTransitionComplete: (
event: BottomSheetSwitcherTransitionEvent,
diff --git a/packages/lab/src/BottomSheet/useSheetGestures.test.ts b/packages/lab/src/BottomSheet/useSheetGestures.test.ts
index 24765b7754..a4a920b013 100644
--- a/packages/lab/src/BottomSheet/useSheetGestures.test.ts
+++ b/packages/lab/src/BottomSheet/useSheetGestures.test.ts
@@ -108,6 +108,26 @@ describe('useSheetGestures', () => {
expect(onDismiss).toHaveBeenCalledTimes(1);
});
+ it('settles instead of dismissing on a downward flick when canDismiss is false', () => {
+ const onSnap = vi.fn();
+ const onScrimOpacity = vi.fn();
+ const {hook, onDismiss} = setup({
+ canDismiss: false,
+ snapHeights: () => [200],
+ onSnap,
+ onScrimOpacity,
+ });
+ const t = makeTarget();
+ down(hook, 0, 0, t);
+ move(hook, 60, 20, t);
+ up(hook, 60, 22, t);
+
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(hook.result.current.settledOffset).toBe(200);
+ expect(onSnap).toHaveBeenLastCalledWith(200);
+ expect(onScrimOpacity).toHaveBeenLastCalledWith(0.3);
+ });
+
it('expands to the tallest detent on a fast upward flick', () => {
const onSnap = vi.fn();
const {hook, onDismiss} = setup({snapHeights: () => [200], onSnap});
@@ -190,6 +210,24 @@ describe('useSheetGestures', () => {
expect(onDismiss).toHaveBeenCalledTimes(1);
});
+ it('rebounds to the shortest detent when canDismiss is false', () => {
+ const onScrimOpacity = vi.fn();
+ const {hook, onDismiss} = setup({
+ canDismiss: false,
+ snapHeights: () => [200],
+ onScrimOpacity,
+ });
+ const t = makeTarget();
+ down(hook, 0, 0, t);
+ move(hook, 160, 400, t);
+ move(hook, 330, 900, t);
+ up(hook, 330, 1400, t);
+
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(hook.result.current.settledOffset).toBe(200);
+ expect(onScrimOpacity).toHaveBeenLastCalledWith(0.3);
+ });
+
it('fades the scrim from full toward the peek floor as it collapses onto the peek detent', () => {
const onScrimOpacity = vi.fn();
// Sheet 400, detents at 200 and 300 -> offsets [0, 100, 200]. The fade
diff --git a/packages/lab/src/BottomSheet/useSheetGestures.ts b/packages/lab/src/BottomSheet/useSheetGestures.ts
index a84bea9e1f..b995fde804 100644
--- a/packages/lab/src/BottomSheet/useSheetGestures.ts
+++ b/packages/lab/src/BottomSheet/useSheetGestures.ts
@@ -102,6 +102,12 @@ function magnetize(value: number, targets: number[]): number {
export interface UseSheetGesturesOptions {
/** Whether the owning sheet is open. Drag state resets when it closes. */
isOpen: boolean;
+ /**
+ * Whether a downward swipe may dismiss the sheet. When false, a gesture
+ * past the dismiss threshold settles at the shortest detent instead.
+ * @default true
+ */
+ canDismiss?: boolean;
/** Called on a swipe-to-close (fast downward flick, or drag past the floor). */
onDismiss: () => void;
/**
@@ -198,6 +204,7 @@ function prefersReducedMotion(): boolean {
*/
export function useSheetGestures({
isOpen,
+ canDismiss = true,
onDismiss,
snapHeights,
onSnap,
@@ -208,11 +215,13 @@ export function useSheetGestures({
const [isDragging, setIsDragging] = useState(false);
const onDismissRef = useRef(onDismiss);
+ const canDismissRef = useRef(canDismiss);
const onSnapRef = useRef(onSnap);
const onScrimOpacityRef = useRef(onScrimOpacity);
const snapHeightsRef = useRef(snapHeights);
useEffect(() => {
onDismissRef.current = onDismiss;
+ canDismissRef.current = canDismiss;
onSnapRef.current = onSnap;
onScrimOpacityRef.current = onScrimOpacity;
snapHeightsRef.current = snapHeights;
@@ -297,9 +306,25 @@ export function useSheetGestures({
const shortestDetentHeight = height - maxOffset;
const speed = Math.abs(velocity);
const isFlick = speed > FLICK_VELOCITY && travel > FLICK_MIN_DISTANCE;
+ const settleAt = (target: number) => {
+ setSettledOffset(target);
+ onSnapRef.current?.(height - target);
+ const dismissOffset =
+ maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
+ onScrimOpacityRef.current?.(
+ scrimOpacityForOffset(target, offsets, dismissOffset),
+ );
+ if (target !== baseOffset) {
+ hapticTick();
+ }
+ };
if (dir > 0 && isFlick) {
- onDismissRef.current();
+ if (canDismissRef.current) {
+ onDismissRef.current();
+ } else {
+ settleAt(maxOffset);
+ }
return;
}
// Fast upward flick = expand to the tallest detent (the sheet's full
@@ -312,24 +337,17 @@ export function useSheetGestures({
return;
}
if (offset > maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO) {
- onDismissRef.current();
+ if (canDismissRef.current) {
+ onDismissRef.current();
+ } else {
+ settleAt(maxOffset);
+ }
return;
}
// Settle to the nearest detent in the drag direction (never back past
// the starting detent), de-duped and direction-clamped by the util.
const target = resolveSettleOffset(offset, offsets, dir, baseOffset);
- setSettledOffset(target);
- onSnapRef.current?.(height - target);
- // Keep the scrim in sync with the resting detent (faint floor at the peek).
- const dismissOffset =
- maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
- onScrimOpacityRef.current?.(
- scrimOpacityForOffset(target, offsets, dismissOffset),
- );
- // Haptic "tick" when landing on a different detent (where supported).
- if (target !== baseOffset) {
- hapticTick();
- }
+ settleAt(target);
},
[detentOffsets],
);