An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): BottomSheet peek detent, snap points, and swipe-to-dismiss (#4519)
Cindy Zhang746765948787
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsxindex 7d24e9a53a..37c6bc720a 100644--- a/apps/storybook/stories/BottomSheet.stories.tsx+++ b/apps/storybook/stories/BottomSheet.stories.tsx@@ -71,7 +71,8 @@ export const TallSheet: Story = {<Section padding={4}><VStack gap={3}><Text type="supporting" color="secondary">- Drag the handle down or press Escape to dismiss.+ Drag the handle to resize between snap points; flick down to+ dismiss or up to expand. Escape also dismisses.</Text><Divider />{Array.from({length: 12}, (_, i) => (@@ -90,7 +91,7 @@ export const TallSheet: Story = {},};-export const AutoHeight: Story = {+export const HugHeight: Story = {render: () => {const [isOpen, setIsOpen] = useState(false);return (@@ -100,12 +101,12 @@ export const AutoHeight: Story = {isOpen={isOpen}onOpenChange={setIsOpen}label="Add a comment"- height="auto">+ height="hug"><Section padding={4}><VStack gap={4}><Heading level={3}>Add a comment</Heading><Text type="supporting" color="secondary">- The sheet fits its content up to the tall budget.+ The sheet fits its content, up to 92% of the viewport.</Text><Divider /><TextInput label="Title" value="" />diff --git a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs b/packages/lab/src/BottomSheet/BottomSheet.doc.mjsindex 536e9486fb..f1068e7a58 100644--- a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs@@ -12,7 +12,7 @@ export const docs = {{className: 'astryx-bottom-sheet', visualProps: []},],},- description: 'A mobile touch sheet that rises from the bottom edge, with a grab handle and swipe-to-dismiss. Built on the Drawer <dialog> engine.',+ description: 'A mobile touch sheet that rises from the bottom edge, with a grab handle, drag-to-resize snap points, and swipe-to-dismiss. Built on a native modal <dialog>.',props: [{name: 'isOpen',@@ -40,17 +40,17 @@ export const docs = {},{name: 'height',- type: "'short' | 'medium' | 'tall' | 'auto'",- description: "How tall the sheet is: 'short' is a fixed peek height, 'medium' is half the viewport, 'tall' is nearly the full viewport, and 'auto' fits its content up to the 'tall' budget. On shorter viewports the sheet fills the available height.",- default: "'medium'",+ type: "'hug' | 'capped' | 'tall' | number | string",+ description: "How tall the sheet is. Named budgets: 'hug' fits its content up to 92% of the viewport, 'capped' is a scrolling mid-height panel (~62%), and 'tall' is a pinned near-full panel (~92%) for content that streams in. Or pass a number (px) / CSS length for a custom budget. The user can drag between snap points regardless. On shorter viewports the sheet fills the available height.",+ default: "'capped'",},],usage: {- description: 'A mobile touch surface for filters, actions, and detail views that should rise from the bottom of the screen. The sheet is modal: focus is trapped while open and restored to the opener on close, and Escape dismisses, so the swipe gesture always has a keyboard equivalent. Content padding clears the home indicator via env(safe-area-inset-bottom).',+ description: 'A mobile touch surface for filters, actions, and detail views that should rise from the bottom of the screen. Drag the grab handle to resize: a slow drag settles to the nearest snap point (a short peek, ~half, and ~full detent, filtered to those shorter than the sheet), a fast flick down dismisses, a fast flick up expands. Pulling down on the content when it is scrolled to the top also drags the sheet, giving a larger, more forgiving target. The scrim fades out as the sheet collapses onto its shortest "peek" detent, so a glance-height sheet reveals the content behind it (the sheet stays modal — the background is inert until dismissed). The sheet is modal: focus is trapped while open and restored to the opener on close, and Escape dismisses, so the swipe gesture always has a keyboard equivalent. Content padding clears the home indicator via env(safe-area-inset-bottom).',bestPractices: [{ guidance: true, description: 'Use for mobile-first surfaces (filters, share sheets, quick actions) where the content should rise from the bottom edge.' },{ guidance: true, description: 'Keep the caller as the source of truth: derive isOpen from state and clear it in onOpenChange.' },- { guidance: true, description: "Pick a height that fits the content: 'auto' for short sheets, 'medium'/'tall' for lists and forms." },+ { guidance: true, description: "Pick the starting height that fits the content: 'hug' for short bounded content, 'capped' for lists, 'tall' for streaming/resizing content; the user can then drag between snap points." },{ guidance: false, description: 'Use a BottomSheet for desktop inspectors or master-detail; use Drawer (side="end", hasScrim={false}) instead.' },],},@@ -77,13 +77,13 @@ export const docs = {</BottomSheet>`,},{- label: 'Auto height (fits content)',+ label: 'Hug height (fits content)',code: `const [isOpen, setIsOpen] = useState(false);<BottomSheetisOpen={isOpen}onOpenChange={setIsOpen}label="Share"- height="auto">+ height="hug"><ShareActions /></BottomSheet>`,},@@ -92,13 +92,13 @@ export const docs = {/** @type {import('../../../core/src/docs-types').TranslationDoc} */export const docsDense = {- description: 'mobile touch sheet rising from the bottom edge (built on the Drawer <dialog> engine): grab handle, swipe-to-dismiss, named height scale',+ description: 'mobile touch sheet rising from the bottom edge (native modal <dialog>): grab handle, drag-to-resize snap points, swipe-to-dismiss, named height scale',usage: {- description: 'Mobile surface for filters, actions, and detail views. Modal: focus trap + restore, and Escape dismisses so swipe has a keyboard equivalent. Content clears the home indicator via safe-area inset.',+ description: 'Mobile surface for filters, actions, and detail views. Drag the handle to resize between snap points; flick down to dismiss, up to expand. Modal: focus trap + restore, and Escape dismisses so swipe has a keyboard equivalent. Content clears the home indicator via safe-area inset.',bestPractices: [{ guidance: true, description: 'Use for mobile-first bottom surfaces (filters, share sheets, quick actions).' },{ guidance: true, description: 'Derive isOpen from state; clear it in onOpenChange.' },- { guidance: true, description: "Pick a height that fits: 'auto' for short sheets, 'medium'/'tall' for lists and forms." },+ { guidance: true, description: "Pick a height that fits: 'hug' for short content, 'capped' for lists, 'tall' for streaming content." },{ guidance: false, description: 'Use for desktop inspectors or master-detail; use Drawer instead.' },],},diff --git a/packages/lab/src/BottomSheet/BottomSheet.test.tsx b/packages/lab/src/BottomSheet/BottomSheet.test.tsxindex d4f15731aa..0440027c87 100644--- a/packages/lab/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/lab/src/BottomSheet/BottomSheet.test.tsx@@ -51,10 +51,17 @@ afterEach(() => {vi.unstubAllGlobals();});+function getSheet(): HTMLElement {+ const sheet = document.querySelector<HTMLElement>('.astryx-bottom-sheet');+ if (!sheet) {+ throw new Error('sheet panel not found');+ }+ return sheet;+}++// The grab handle is the panel's first child (decorative, aria-hidden).function getHandle(): HTMLElement {- const handle = document.querySelector<HTMLElement>(- '[data-astryx-sheet-handle]',- );+ const handle = getSheet().querySelector<HTMLElement>('[aria-hidden="true"]');if (!handle) {throw new Error('grab handle not found');}@@ -156,7 +163,23 @@ describe('BottomSheet', () => {describe('height', () => {it('renders for each named height without error', () => {- for (const height of ['short', 'medium', 'tall', 'auto'] as const) {+ for (const height of ['hug', 'capped', 'tall'] as const) {+ const {unmount} = render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Filters"+ height={height}>+ Content+ </BottomSheet>,+ );+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ unmount();+ }+ });++ it('accepts a freeform height (number or CSS length)', () => {+ for (const height of [480, '70dvh'] as const) {const {unmount} = render(<BottomSheetisOpen@@ -207,6 +230,47 @@ describe('BottomSheet', () => {});});+ describe('initial focus', () => {+ it('focuses the sheet panel on open, not the first control', () => {+ render(+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">+ <button type="button">First action</button>+ </BottomSheet>,+ );+ const panel = getSheet();+ expect(document.activeElement).toBe(panel);+ expect(document.activeElement).not.toBe(+ screen.getByRole('button', {name: 'First action'}),+ );+ });++ it('honors a descendant with data-autofocus', () => {+ render(+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">+ <input data-autofocus aria-label="Search" />+ </BottomSheet>,+ );+ expect(document.activeElement).toBe(+ screen.getByRole('textbox', {name: 'Search'}),+ );+ });+ });++ describe('accessible name', () => {+ it('warns in development when label is empty', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(+ <BottomSheet isOpen onOpenChange={() => {}} label="">+ Content+ </BottomSheet>,+ );+ expect(+ warn.mock.calls.some(args => String(args[0]).includes('BottomSheet')),+ ).toBe(true);+ warn.mockRestore();+ });+ });+describe('reduced motion', () => {it('opens without throwing when prefers-reduced-motion is set', () => {vi.stubGlobal(diff --git a/packages/lab/src/BottomSheet/BottomSheet.tsx b/packages/lab/src/BottomSheet/BottomSheet.tsxindex adc1eb8c98..fc5142d80b 100644--- a/packages/lab/src/BottomSheet/BottomSheet.tsx+++ b/packages/lab/src/BottomSheet/BottomSheet.tsx@@ -4,21 +4,22 @@/*** @file BottomSheet.tsx- * @input Uses React, StyleX, theme tokens, Drawer, useSheetGestures, themeProps+ * @input Uses React, StyleX, theme tokens, core hooks (useScrollLock), utils, useSheetGestures* @output Exports BottomSheet component and BottomSheetProps* @position Lab implementation; consumed by index.ts, tested by BottomSheet.test.tsx, demonstrated in Storybook*- * A mobile touch surface that rises from the bottom edge with a grab handle- * and swipe-to-dismiss. Built ON TOP OF the lab Drawer's native `<dialog>`- * engine (`side="bottom"`) rather than forking it — Drawer owns- * showModal/show, the open/close slide animation, focus trap + restore,- * scroll lock, the Escape/scrim contract, and the LIFO overlay registry.- * BottomSheet layers the grab handle and the drag-to-dismiss gesture on top,- * inside the dialog.+ * A mobile touch surface that rises from the bottom edge: grab handle, snap+ * points, and swipe-to-dismiss. It owns a native modal `<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.*- * The gesture translate is applied to an inner sheet wrapper, not the- * `<dialog>` itself, so Drawer owns the open/close slide and the drag- * translates within it without the two transforms fighting.+ * 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.** SYNC: When modified, update these files to stay in sync:* - /packages/lab/src/BottomSheet/BottomSheet.doc.mjs (props table, features, usage)@@ -27,81 +28,166 @@* - /apps/storybook/stories/BottomSheet.stories.tsx (examples and visual coverage)*/-import {type ReactNode} from 'react';+import {useCallback, useEffect, useRef, 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 {Drawer} from '../Drawer';+import {useDevWarning, useScrollLock} from '@astryxdesign/core/hooks';+import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';import {useSheetGestures} from './useSheetGestures';+// 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. `medium`/`tall` track the viewport so- * the sheet scales with the device; `short` is a fixed peek height. `auto`- * is handled separately (fits content, capped at the `tall` budget).+ * 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 = {- short: '240px',- medium: '50dvh',- tall: '90dvh',- auto: '90dvh',+ 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;-// Sheets on wide touch devices (tablets) shouldn't stretch edge to edge;-// cap and center them. Matches the `sm` layout breakpoint. On phones the-// viewport is narrower than this, so the sheet stays full-width.-const MAX_SHEET_WIDTH = 640;+// 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;++/**+ * 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);+}const styles = stylex.create({- // Inner wrapper that carries the live drag translate AND the visible sheet- // surface (background, rounded top, width cap). The translate must live on- // the painted surface — not the <dialog> — so the whole sheet follows the- // swipe instead of the content sliding out of a fixed white panel. Drawer- // owns the open/close slide on the <dialog>; this wrapper adds the gesture- // offset within it so the two transforms don't fight. Safe-area padding- // clears the home indicator on notched devices.+ // 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.+ dialog: {+ position: 'fixed',+ inset: 0,+ width: '100dvw',+ height: '100dvh',+ maxWidth: 'none',+ maxHeight: 'none',+ margin: 0,+ padding: 0,+ border: 'none',+ backgroundColor: 'transparent',+ overflow: 'visible',+ pointerEvents: 'none',+ display: 'none',+ outline: 'none',+ },+ dialogOpen: {+ display: 'block',+ },+ // Opacity is a var the drag handler lowers toward dismissal;+ // @starting-style animates the entrance fade-in.+ scrim: {+ '::backdrop': {+ backgroundColor: colorVars['--color-overlay'],+ backdropFilter: 'blur(2px)',+ 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',+ },+ },+ },+ positioner: {+ position: 'absolute',+ insetInline: 0,+ insetBlockEnd: 0,+ display: 'flex',+ justifyContent: 'center',+ pointerEvents: 'none',+ },sheet: {+ pointerEvents: 'auto',+ boxSizing: 'border-box',display: 'flex',flexDirection: 'column',minHeight: 0,- height: '100%',width: '100%',- maxWidth: MAX_SHEET_WIDTH,- marginInline: 'auto',+ maxWidth: 640,backgroundColor: colorVars['--color-background-surface'],- borderStartStartRadius: radiusVars['--radius-page'],- borderStartEndRadius: radiusVars['--radius-page'],+ 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',- paddingBlockEnd: `env(safe-area-inset-bottom, 0px)`,+ // 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',+ },},- // Neutralize Drawer's <dialog> surface so only the swipeable wrapper paints.- // Without this the dialog's white background + shadow stay fixed while the- // wrapper slides, leaving a static panel behind the drag. The scrim behind- // the sheet provides the depth separation a shadow would.- dialogSurface: {- backgroundColor: 'transparent',- boxShadow: 'none',- borderBlockStartWidth: 0,+ sheetClosing: {+ transform: 'translateY(100%)',},handleBar: {flexShrink: 0,display: 'flex',alignItems: 'center',justifyContent: 'center',- paddingBlock: spacingVars['--spacing-2'],+ // 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: 36,- height: 4,+ width: sizeVars['--size-element-lg'],+ height: spacingVars['--spacing-1'],borderRadius: radiusVars['--radius-full'],backgroundColor: colorVars['--color-border'],},@@ -109,16 +195,26 @@ const styles = stylex.create({flexGrow: 1,minHeight: 0,overflowY: 'auto',- overscrollBehavior: 'contain',+ // 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',},- // `auto` fits content instead of filling the height budget; the budget- // becomes an upper bound. Applied to the <dialog> (overrides Drawer's- // block-size treatment, which is applied earlier in the props chain).- autoHeight: {+ // 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)`,+ },+ hugHeight: {height: 'fit-content',- maxHeight: HEIGHT_BUDGETS.auto,+ maxHeight: `calc(${HEIGHT_BUDGETS.hug} + ${OVERSCROLL_PADDING}px)`,},});+export interface BottomSheetProps extends BaseProps<HTMLDialogElement> {/** Ref forwarded to the underlying <dialog> element. */ref?: React.Ref<HTMLDialogElement>;@@ -127,8 +223,8 @@ export interface BottomSheetProps extends BaseProps<HTMLDialogElement> {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+ * 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;@@ -143,28 +239,32 @@ export interface BottomSheetProps extends BaseProps<HTMLDialogElement> {children: ReactNode;/**- * How tall the sheet is:- * - `'short'` — a fixed peek height- * - `'medium'` — half the viewport- * - `'tall'` — nearly the full viewport- * - `'auto'` — fits its content, capped at the `'tall'` budget+ * 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.*- * On viewports shorter than the budget the sheet fills the available- * height.- * @default 'medium'+ * 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?: BottomSheetHeight;+ height?: BottomSheetHeight | number | string;/** Test ID for the root element. */'data-testid'?: string;}/**- * A mobile touch sheet that rises from the bottom edge, with a grab handle- * and swipe-to-dismiss. Built on the lab Drawer's `<dialog>` engine- * (`side="bottom"`): Drawer owns the open/close slide, focus trap + restore,- * scroll lock, and the Escape/scrim contract, while BottomSheet layers the- * grab handle and drag-to-dismiss on top.+ * 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 modal+ * `<dialog>` (top layer, focus trap, `::backdrop` scrim) and locks body scroll+ * while open; a slow drag settles to the nearest snap point, a flick down+ * dismisses, and Escape closes — so the swipe always has a keyboard+ * equivalent.** @example* ```@@ -178,48 +278,182 @@ export interface BottomSheetProps extends BaseProps<HTMLDialogElement> {* ```*/export function BottomSheet({+ ref,isOpen,onOpenChange,label,children,- height = 'medium',+ height = 'capped',xstyle,...props}: BottomSheetProps) {- const close = () => onOpenChange(false);- const {contentProps, handleProps} = useSheetGestures({+ const dialogRef = useRef<HTMLDialogElement | null>(null);+ const triggerRef = useRef<HTMLElement | null>(null);+ const sheetNodeRef = useRef<HTMLDivElement | null>(null);+ const close = useCallback(() => onOpenChange(false), [onOpenChange]);++ // Set imperatively (not via state) so a 60fps drag doesn't re-render. The+ // hook reports the scrim opacity for the current detent (hidden at the peek).+ const handleScrimOpacity = useCallback((opacity: number) => {+ dialogRef.current?.style.setProperty(+ '--_sheet-scrim-opacity',+ String(opacity),+ );+ }, []);++ const {contentProps, handleProps, bodyProps, sheetRef} = useSheetGestures({isOpen,onDismiss: close,+ snapHeights: defaultSnapHeights,+ onScrimOpacity: handleScrimOpacity,});+ // showModal() enters the top layer with a focus trap + ::backdrop; on close+ // we animate out (below) then restore focus to the opener.+ useEffect(() => {+ const dialog = dialogRef.current;+ if (!dialog) {+ return;+ }+ if (isOpen) {+ triggerRef.current = document.activeElement as HTMLElement | null;+ dialog.style.setProperty('--_sheet-scrim-opacity', '1');+ if (!dialog.open) {+ dialog.showModal();+ // Override showModal()'s default (first tabbable) to land on the panel,+ // so AT reads from the label — unless a descendant sets data-autofocus.+ const autofocus = dialog.querySelector<HTMLElement>('[data-autofocus]');+ if (autofocus) {+ autofocus.focus();+ } else {+ sheetNodeRef.current?.focus();+ }+ }+ } else if (dialog.open) {+ // 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();+ }+ 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 (410ms) 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);+ };+ }+ }, [isOpen]);++ useScrollLock(isOpen);++ // Enforce an accessible name: label is required by types, but a JS caller+ // can still pass an empty string, leaving the sheet unnamed.+ useDevWarning(+ 'BottomSheet',+ 'requires a non-empty `label` for an accessible name; the open sheet ' ++ 'has no built-in heading to derive one from.',+ isOpen && !label,+ );++ const handleCancel = useCallback(+ (event: React.SyntheticEvent<HTMLDialogElement>) => {+ event.preventDefault();+ close();+ },+ [close],+ );+ // Explicit Escape handler in addition to the native `cancel` event, for+ // environments that don't synthesize `cancel`.+ const handleKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLDialogElement>) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ close();+ }+ },+ [close],+ );+ const handleClick = useCallback(+ (event: React.MouseEvent<HTMLDialogElement>) => {+ if (event.target === event.currentTarget) {+ close();+ }+ },+ [close],+ );++ 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 (- <Drawer- isOpen={isOpen}- onClose={close}- side="bottom"- size={HEIGHT_BUDGETS[height]}- label={label}- hasScrim- hasCloseButton={false}- xstyle={[styles.dialogSurface, height === 'auto' && styles.autoHeight]}+ <dialog+ {...stylex.props(+ styles.dialog,+ isOpen && styles.dialogOpen,+ styles.scrim,+ )}+ ref={mergeRefs(ref, dialogRef)}+ aria-label={label}+ aria-modal="true"+ onCancel={handleCancel}+ onClick={handleClick}+ onKeyDown={handleKeyDown}{...props}>- <div- data-astryx-sheet=""- {...mergeProps(- themeProps('bottom-sheet'),- stylex.props(styles.sheet, xstyle),- contentProps.style,- )}>+ <div {...stylex.props(styles.positioner)}><div- data-astryx-sheet-handle=""- {...stylex.props(styles.handleBar)}- {...handleProps}- aria-hidden="true">- <div {...stylex.props(styles.handlePill)} />+ ref={mergeRefs(sheetRef, sheetNodeRef)}+ tabIndex={-1}+ {...mergeProps(+ themeProps('bottom-sheet'),+ stylex.props(+ styles.sheet,+ isHug ? styles.hugHeight : styles.budget,+ !isOpen && styles.sheetClosing,+ xstyle,+ ),+ undefined,+ {+ ['--_sheet-budget' as string]: budget,+ ...contentProps.style,+ },+ )}>+ <div+ {...stylex.props(styles.handleBar)}+ {...handleProps}+ aria-hidden="true">+ <div {...stylex.props(styles.handlePill)} />+ </div>+ <div {...stylex.props(styles.body)} {...bodyProps}>+ {children}+ </div></div>- <div {...stylex.props(styles.body)}>{children}</div></div>- </Drawer>+ </dialog>);}diff --git a/packages/lab/src/BottomSheet/snapOffsets.test.ts b/packages/lab/src/BottomSheet/snapOffsets.test.tsnew file mode 100644index 0000000000..8c72b05ab9--- /dev/null+++ b/packages/lab/src/BottomSheet/snapOffsets.test.ts@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file snapOffsets.test.ts+ * @input Uses vitest, snapOffsets pure helpers+ * @output Unit tests for the snap-point -> translateY offset geometry+ * @position Testing; validates snapOffsets.ts (no DOM needed)+ *+ * SYNC: When snapOffsets.ts changes, update these tests to match.+ */++import {describe, it, expect} from 'vitest';+import {+ snapFractionsToHeights,+ computeDetentOffsets,+ nearestOffset,+ resolveSettleOffset,+ scrimOpacityForOffset,+ DETENT_DEDUP_PX,+} from './snapOffsets';++describe('snapFractionsToHeights', () => {+ it('scales in-range fractions to px', () => {+ expect(snapFractionsToHeights([0.5, 0.92], 800)).toEqual([400, 736]);+ });+ it('drops out-of-range fractions', () => {+ expect(snapFractionsToHeights([0, 0.5, 1, 1.2, -0.3], 1000)).toEqual([+ 500, 1000,+ ]);+ });+});++describe('computeDetentOffsets', () => {+ it('always includes fully-open (0) first, ascending', () => {+ // sheet 800; detent visible heights 400, 640 -> offsets 400, 160 -> sorted+ expect(computeDetentOffsets(800, [400, 640])).toEqual([0, 160, 400]);+ });++ it('drops detents at or taller than the sheet (cannot translate up)', () => {+ // 800 and 900 are >= sheet 800 -> dropped; only 500 (offset 300) remains+ expect(computeDetentOffsets(800, [500, 800, 900])).toEqual([0, 300]);+ });++ it('de-dupes near-equal detents, keeping the taller (smaller offset)', () => {+ // sheet 800; heights 760 (offset 40) and 400 (offset 400). 40 is within+ // DETENT_DEDUP_PX of the fully-open 0 -> collapses to just [0, 400].+ expect(computeDetentOffsets(800, [760, 400])).toEqual([0, 400]);+ });++ it('keeps detents that are farther apart than the dedup threshold', () => {+ // offsets 0, 100, 400 with default 48px dedup -> all kept+ expect(computeDetentOffsets(800, [700, 400])).toEqual([0, 100, 400]);+ });++ it('respects a custom dedup threshold', () => {+ // offsets 0, 100, 400; dedup 150 -> 100 collapses into 0+ expect(computeDetentOffsets(800, [700, 400], 150)).toEqual([0, 400]);+ });++ it('a single-height sheet has just the fully-open detent', () => {+ expect(computeDetentOffsets(600, [])).toEqual([0]);+ });+});++describe('nearestOffset', () => {+ it('picks the closest offset', () => {+ expect(nearestOffset(180, [0, 200, 400])).toBe(200);+ expect(nearestOffset(90, [0, 200, 400])).toBe(0);+ });+});++describe('resolveSettleOffset', () => {+ const offsets = [0, 200, 400]; // full, mid, short++ it('a down-drag never settles above the starting detent', () => {+ // start at mid (200), drag down to ~240 -> nearest at/below is 200 (mid),+ // never back up to 0.+ expect(resolveSettleOffset(240, offsets, 1, 200)).toBe(200);+ });++ it('a down-drag past the midpoint moves to the next lower detent', () => {+ // start mid (200), drag to 320 -> nearest at/below is 400 (short)+ expect(resolveSettleOffset(320, offsets, 1, 200)).toBe(400);+ });++ it('an up-drag never settles below the starting detent', () => {+ // start mid (200), drag up to ~160 -> nearest at/above is 0 or 200; 160 is+ // closer to 200, so it holds mid rather than dropping to short.+ expect(resolveSettleOffset(160, offsets, -1, 200)).toBe(200);+ });++ it('an up-drag past the midpoint expands to the next higher detent', () => {+ // start mid (200), drag up to 80 -> nearest at/above is 0 (full)+ expect(resolveSettleOffset(80, offsets, -1, 200)).toBe(0);+ });++ it('with no direction, picks the plain nearest', () => {+ expect(resolveSettleOffset(180, offsets, 0, 200)).toBe(200);+ });+});++describe('scrimOpacityForOffset', () => {+ describe('with a peek detent (>= 2 detents)', () => {+ const offsets = [0, 100, 200]; // full, mid, peek+ const dismissOffset = 280;++ it('is full at or above the mid detent', () => {+ expect(scrimOpacityForOffset(0, offsets, dismissOffset)).toBe(1);+ expect(scrimOpacityForOffset(100, offsets, dismissOffset)).toBe(1);+ expect(scrimOpacityForOffset(60, offsets, dismissOffset)).toBe(1);+ });++ it('fades linearly from the mid detent to the peek', () => {+ expect(scrimOpacityForOffset(150, offsets, dismissOffset)).toBeCloseTo(+ 0.5,+ );+ });++ it('is hidden at or below the peek detent', () => {+ expect(scrimOpacityForOffset(200, offsets, dismissOffset)).toBe(0);+ expect(scrimOpacityForOffset(240, offsets, dismissOffset)).toBe(0);+ });+ });++ describe('with a single detent (no peek)', () => {+ const offsets = [0];+ const dismissOffset = 160;++ it('stays full until the drag begins collapsing', () => {+ expect(scrimOpacityForOffset(0, offsets, dismissOffset)).toBe(1);+ });++ it('fades across the dismiss overshoot toward the threshold', () => {+ expect(scrimOpacityForOffset(80, offsets, dismissOffset)).toBeCloseTo(+ 0.5,+ );+ expect(scrimOpacityForOffset(160, offsets, dismissOffset)).toBe(0);+ });+ });+});++describe('DETENT_DEDUP_PX', () => {+ it('is a sane positive threshold', () => {+ expect(DETENT_DEDUP_PX).toBeGreaterThan(0);+ });+});diff --git a/packages/lab/src/BottomSheet/snapOffsets.ts b/packages/lab/src/BottomSheet/snapOffsets.tsnew file mode 100644index 0000000000..ea2e1557ed--- /dev/null+++ b/packages/lab/src/BottomSheet/snapOffsets.ts@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file snapOffsets.ts+ * @input Pure geometry helpers — no React, no DOM.+ * @output Converts snap points to translateY offsets for the sheet surface.+ * @position Internal to BottomSheet; consumed by useSheetGestures, tested by+ * snapOffsets.test.ts.+ *+ * The sheet is rendered at its full (fully-open) height and *translated down*+ * to express shorter detents — translate is GPU-composited, so this is cheaper+ * than animating layout height. A detent is therefore a translateY offset in+ * px from the fully-open position (0 = fully open, larger = more collapsed).+ * These helpers turn snap points into that offset list; they are pure so the+ * geometry can be unit-tested without a DOM.+ */++/**+ * Detents whose resting offsets land within this many px of each other are+ * treated as the same stop (the taller one wins). Stops the sheet from having+ * two near-identical rest positions — e.g. when a content-hugging height sits+ * a hair away from a fractional snap point.+ */+export const DETENT_DEDUP_PX = 48;++/** Resolve snap points given as viewport fractions (0, 1] to px heights. */+export function snapFractionsToHeights(+ fractions: readonly number[],+ viewportPx: number,+): number[] {+ return fractions.filter(f => f > 0 && f <= 1).map(f => f * viewportPx);+}++/**+ * Given the sheet's full height (px, as rendered fully open) and a set of+ * candidate detent *visible heights* (px), return the resting translateY+ * offsets from fully-open, ascending and de-duplicated.+ *+ * - `0` (fully open) is always the first detent.+ * - Only heights strictly shorter than the sheet become collapsed detents; a+ * height >= the sheet can't be shown by translating down, so it's dropped.+ * - Offsets closer than `dedupPx` collapse to the smaller (taller) offset, so+ * near-identical detents — e.g. a hug height ≈ a snap point — become one stop.+ */+export function computeDetentOffsets(+ sheetHeight: number,+ detentHeights: readonly number[],+ dedupPx: number = DETENT_DEDUP_PX,+): number[] {+ const collapsed = detentHeights+ .filter(h => h > 0 && h < sheetHeight)+ .map(h => sheetHeight - h);+ const ascending = [0, ...collapsed].sort((a, b) => a - b);++ const deduped: number[] = [];+ for (const offset of ascending) {+ const last = deduped[deduped.length - 1];+ if (last === undefined || offset - last >= dedupPx) {+ deduped.push(offset);+ }+ }+ return deduped;+}++/** Nearest value in `offsets` to `value` (offsets must be non-empty). */+export function nearestOffset(+ value: number,+ offsets: readonly number[],+): number {+ return offsets.reduce(+ (best, o) => (Math.abs(o - value) < Math.abs(best - value) ? o : best),+ offsets[0],+ );+}++/**+ * Scrim opacity (1 = fully visible, 0 = hidden) for a drag/settle `offset`.+ * The scrim stays full while the sheet is at or above its second-shortest+ * detent, then fades to 0 as it collapses onto the shortest ("peek") detent —+ * a glance state that reveals the content behind — and stays hidden below it.+ * A single-detent sheet has no peek, so it instead fades across the dismiss+ * overshoot toward `dismissOffset`.+ */+export function scrimOpacityForOffset(+ offset: number,+ offsets: readonly number[],+ dismissOffset: number,+): number {+ const shortest = offsets[offsets.length - 1];+ const fadeStart = offsets.length >= 2 ? offsets[offsets.length - 2] : 0;+ const fadeEnd = offsets.length >= 2 ? shortest : dismissOffset;+ if (offset <= fadeStart) {+ return 1;+ }+ if (offset >= fadeEnd) {+ return 0;+ }+ return 1 - (offset - fadeStart) / (fadeEnd - fadeStart);+}++/**+ * Settle target for a released drag. Restricts candidates to the drag+ * direction so a committed drag never snaps *back past* where it started+ * (a down-drag settles at/below the start, an up-drag at/above), then picks+ * the nearest remaining detent. `dir`: 1 = dragged down, -1 = up, 0 = neither.+ */+export function resolveSettleOffset(+ value: number,+ offsets: readonly number[],+ dir: number,+ baseOffset: number,+): number {+ let candidates = offsets;+ if (dir > 0) {+ const downward = offsets.filter(o => o >= baseOffset);+ if (downward.length > 0) {+ candidates = downward;+ }+ } else if (dir < 0) {+ const upward = offsets.filter(o => o <= baseOffset);+ if (upward.length > 0) {+ candidates = upward;+ }+ }+ return nearestOffset(value, candidates);+}diff --git a/packages/lab/src/BottomSheet/useSheetGestures.doc.mjs b/packages/lab/src/BottomSheet/useSheetGestures.doc.mjsindex e8422b6094..2c6a5d9408 100644--- a/packages/lab/src/BottomSheet/useSheetGestures.doc.mjs+++ b/packages/lab/src/BottomSheet/useSheetGestures.doc.mjs@@ -4,12 +4,12 @@export const docs = {name: 'useSheetGestures',displayName: 'useSheetGestures',- keywords: ['sheet', 'drag', 'swipe', 'dismiss', 'gesture', 'pointer', 'touch', 'bottom sheet'],+ keywords: ['sheet', 'drag', 'swipe', 'snap', 'detent', 'dismiss', 'gesture', 'pointer', 'touch', 'bottom sheet'],params: [{name: 'options',type: 'UseSheetGesturesOptions',- description: 'isOpen and onDismiss. Internal to BottomSheet; not exported from the lab entry point.',+ description: 'isOpen, onDismiss, optional snapHeights (candidate detent heights in px), onSnap, and onScrimOpacity (the scrim opacity to show, 1->0 as the sheet collapses onto its peek detent, for a glance affordance). Internal to BottomSheet, not exported from the lab entry point.',required: true,},],@@ -17,15 +17,16 @@ export const docs = {{name: 'result',type: 'UseSheetGesturesResult',- description: 'contentProps (spread on the sliding surface for the live translate + touch-action guard), handleProps (spread on the grab handle for the pointer drag), plus dragOffset and isDragging for callers that want to drive their own animation.',+ description: 'contentProps (spread on the sliding surface for the live translate + touch-action guard), handleProps (spread on the grab handle for the pointer drag), plus dragOffset, settledOffset, and isDragging for callers that want to drive their own animation.',},],usage: {description:- 'Drag-to-dismiss machinery for the bottom sheet. Tracks a pointer drag down the block axis, translates the sliding surface live, and on release either dismisses (past a distance or velocity threshold) or springs back to fully open. Pointer-events based (one path for mouse + touch), SSR-safe, and respects prefers-reduced-motion. Escape (routed by the owning dialog) provides the keyboard equivalent of the swipe.',+ 'Drag + snap machinery for the bottom sheet. A slow drag on the handle resizes the sheet live and, on release, settles to the nearest snap detent; a fast downward flick dismisses (swipe-to-close); a fast upward flick expands to the tallest detent. The measured sheet height is always the tallest detent, and snapHeights add shorter rest points beneath it. Pointer-events based (one path for mouse + touch), SSR-safe, and respects prefers-reduced-motion. Escape (routed by the owning dialog) provides the keyboard equivalent of the dismiss swipe.',bestPractices: [{ guidance: true, description: 'Spread handleProps on the grab-handle element and contentProps on the sliding surface (the panel that carries the translate).' },- { guidance: false, description: 'Wire onDismiss to anything other than the owning sheet close; it fires when a swipe crosses the dismiss threshold.' },+ { guidance: true, description: 'Pass snapHeights in px relative to the viewport; the hook filters out any that are >= the measured sheet height.' },+ { guidance: false, description: 'Wire onDismiss to anything other than the owning sheet close; it fires on a swipe-to-close or a drag past the shortest detent.' },],},};diff --git a/packages/lab/src/BottomSheet/useSheetGestures.test.ts b/packages/lab/src/BottomSheet/useSheetGestures.test.tsindex 85788dcf8e..446fa20707 100644--- a/packages/lab/src/BottomSheet/useSheetGestures.test.ts+++ b/packages/lab/src/BottomSheet/useSheetGestures.test.ts@@ -36,7 +36,6 @@ function pointerEvent(function makeTarget(): HTMLElement {const el = document.createElement('div');- el.setAttribute('data-astryx-sheet', '');el.setPointerCapture = vi.fn();el.releasePointerCapture = vi.fn();el.getBoundingClientRect = () => ({height: SHEET_HEIGHT}) as DOMRect;@@ -73,70 +72,174 @@ function setup(options: Partial<UseSheetGesturesOptions> = {}) {return {hook, onDismiss};}+type Hook = {+ result: {current: ReturnType<typeof useSheetGestures>};+};++function down(hook: Hook, y: number, t: number, target: HTMLElement) {+ // Register the sheet element the way the component does on mount, so the+ // hook can measure its height (it no longer queries the DOM for it).+ act(() => hook.result.current.sheetRef(target));+ act(() =>+ hook.result.current.handleProps.onPointerDown(pointerEvent(y, t, target)),+ );+}+function move(hook: Hook, y: number, t: number, target: HTMLElement) {+ act(() =>+ hook.result.current.handleProps.onPointerMove(pointerEvent(y, t, target)),+ );+}+function up(hook: Hook, y: number, t: number, target: HTMLElement) {+ act(() =>+ hook.result.current.handleProps.onPointerUp(pointerEvent(y, t, target)),+ );+}+describe('useSheetGestures', () => {- it('dismisses when dragged past the distance threshold (slow drag)', () => {- const {hook, onDismiss} = setup();- const target = makeTarget();- const {handleProps} = hook.result.current;- act(() => {- handleProps.onPointerDown(pointerEvent(0, 0, target));- });- // Drag down slowly, well past 25% of 400px, low velocity.- act(() => {- handleProps.onPointerMove(pointerEvent(60, 200, target));- handleProps.onPointerMove(pointerEvent(140, 600, target));- });- act(() => {- handleProps.onPointerUp(pointerEvent(140, 620, target));- });+ it('dismisses on a fast downward flick (swipe-to-close)', () => {+ const {hook, onDismiss} = setup({snapHeights: () => [200]});+ const t = makeTarget();+ down(hook, 0, 0, t);+ // 60px in 20ms = 3px/ms, and 60px > the flick distance floor.+ move(hook, 60, 20, t);+ up(hook, 60, 22, t);expect(onDismiss).toHaveBeenCalledTimes(1);});- it('dismisses on a fast flick even below the distance threshold', () => {- const {hook, onDismiss} = setup();- const target = makeTarget();- const {handleProps} = hook.result.current;- act(() => {- handleProps.onPointerDown(pointerEvent(0, 0, target));- });- // Small distance (30px < 100px) but very fast (30px / 10ms = 3px/ms).- act(() => {- handleProps.onPointerMove(pointerEvent(30, 10, target));- });- act(() => {- handleProps.onPointerUp(pointerEvent(30, 12, target));- });- expect(onDismiss).toHaveBeenCalledTimes(1);+ it('expands to the tallest detent on a fast upward flick', () => {+ const onSnap = vi.fn();+ const {hook, onDismiss} = setup({snapHeights: () => [200], onSnap});+ const t = makeTarget();+ // Start rested at a lower detent by first snapping there via a slow drag.+ down(hook, 0, 0, t);+ move(hook, 200, 400, t); // slow drag down toward the 200px detent+ up(hook, 200, 800, t);+ onSnap.mockClear();+ // Now flick up fast: 60px in 20ms = 3px/ms, over the distance floor.+ down(hook, 200, 1000, t);+ move(hook, 140, 1020, t);+ up(hook, 140, 1022, t);+ expect(onDismiss).not.toHaveBeenCalled();+ expect(onSnap).toHaveBeenLastCalledWith(SHEET_HEIGHT); // full height+ expect(hook.result.current.settledOffset).toBe(0);});- it('springs back (no dismiss) below the threshold', () => {- const {hook, onDismiss} = setup();- const target = makeTarget();- const {handleProps} = hook.result.current;- act(() => {- handleProps.onPointerDown(pointerEvent(0, 0, target));- });- act(() => {- handleProps.onPointerMove(pointerEvent(20, 300, target));- });- act(() => {- handleProps.onPointerUp(pointerEvent(20, 620, target));- });+ it('does not flick-dismiss on a fast but short nudge', () => {+ const {hook, onDismiss} = setup({snapHeights: () => [200]});+ const t = makeTarget();+ // Fast (20px/10ms = 2px/ms) but only 20px of travel — under the distance+ // floor, so it settles rather than dismissing.+ down(hook, 0, 0, t);+ move(hook, 20, 10, t);+ up(hook, 20, 12, t);expect(onDismiss).not.toHaveBeenCalled();- expect(hook.result.current.dragOffset).toBe(0);- expect(hook.result.current.isDragging).toBe(false);+ });++ it('settles to the nearest detent on a slow drag', () => {+ const onSnap = vi.fn();+ const {hook, onDismiss} = setup({snapHeights: () => [200], onSnap});+ const t = makeTarget();+ // Detents: full=400 (offset 0) and 200 (offset 200). Drag slowly to ~180+ // offset -> nearest is the 200px detent (offset 200).+ down(hook, 0, 0, t);+ move(hook, 90, 300, t);+ move(hook, 180, 700, t);+ up(hook, 180, 1100, t);+ expect(onDismiss).not.toHaveBeenCalled();+ expect(onSnap).toHaveBeenLastCalledWith(200);+ expect(hook.result.current.settledOffset).toBe(200);+ });++ it('a downward drag from a middle detent never snaps back up past it', () => {+ // Three detents on a 600px sheet: full (offset 0), mid 360 (offset 240),+ // short 160 (offset 440). Rest at the mid detent, then drag DOWN a modest+ // amount that's still closer to mid than to short. It must not snap back+ // UP to full — only to mid (stay) or further down.+ const onSnap = vi.fn();+ const {hook} = setup({snapHeights: () => [160, 360], onSnap});+ const t = makeTarget();+ t.getBoundingClientRect = () => ({height: 600}) as DOMRect;+ // Drag to the mid detent (offset 240).+ down(hook, 0, 0, t);+ move(hook, 120, 300, t);+ move(hook, 240, 700, t);+ up(hook, 240, 1100, t);+ expect(hook.result.current.settledOffset).toBe(240);+ onSnap.mockClear();+ // Small slow drag DOWN from mid: offset 240 -> ~300.+ down(hook, 300, 2000, t);+ move(hook, 340, 2200, t);+ move(hook, 360, 2600, t);+ up(hook, 360, 3000, t);+ // Must not have jumped back up to full (offset 0).+ expect(hook.result.current.settledOffset).not.toBe(0);+ expect(hook.result.current.settledOffset).toBeGreaterThanOrEqual(240);+ });++ it('dismisses when dragged well below the shortest detent', () => {+ const {hook, onDismiss} = setup({snapHeights: () => [200]});+ const t = makeTarget();+ // Shortest detent offset = 200 (height 200). Drag slowly past it by+ // >40% of 200 -> offset ~320 dismisses.+ down(hook, 0, 0, t);+ move(hook, 160, 400, t);+ move(hook, 330, 900, t);+ up(hook, 330, 1400, t);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it('fades the scrim from full to hidden as it collapses onto the peek detent', () => {+ const onScrimOpacity = vi.fn();+ // Sheet 400, detents at 200 and 300 -> offsets [0, 100, 200]. The fade+ // spans the mid detent (offset 100) to the peek detent (offset 200):+ // full at/above 100, hidden at/below 200.+ const {hook} = setup({snapHeights: () => [200, 300], onScrimOpacity});+ const t = makeTarget();+ down(hook, 0, 0, t);+ move(hook, 60, 200, t); // offset 60, above the mid detent -> full+ move(hook, 150, 600, t); // offset 150, halfway through the fade -> ~0.5+ move(hook, 220, 1000, t); // offset 220, past the peek -> hidden+ const values = onScrimOpacity.mock.calls.map(c => c[0]);+ expect(values[0]).toBe(1);+ expect(values[1]).toBeGreaterThan(0.4);+ expect(values[1]).toBeLessThan(0.6);+ expect(values[values.length - 1]).toBe(0);+ });++ it('keeps the scrim hidden when settled at the peek detent', () => {+ const onScrimOpacity = vi.fn();+ const {hook} = setup({snapHeights: () => [200, 300], onScrimOpacity});+ const t = makeTarget();+ // Slow drag down to the peek detent (offset 200).+ down(hook, 0, 0, t);+ move(hook, 100, 400, t);+ move(hook, 200, 900, t);+ up(hook, 200, 1400, t);+ expect(hook.result.current.settledOffset).toBe(200);+ // Last reported opacity (on settle) is hidden.+ const values = onScrimOpacity.mock.calls.map(c => c[0]);+ expect(values[values.length - 1]).toBe(0);+ });++ it('magnetically settles the live drag onto a nearby detent', () => {+ // Detents for a 400px sheet with snaps 300 and 200 -> visible-height snaps+ // become offsets [0, 100, 200]. Approaching the middle detent (offset 100)+ // from just below (raw ~90) — inside MAGNET_RANGE and BELOW the shortest+ // detent so the between-detents magnet applies — should ease toward 100.+ const {hook} = setup({snapHeights: () => [200, 300]});+ const t = makeTarget();+ down(hook, 0, 0, t);+ move(hook, 90, 100, t); // raw offset 90, 10px from the 100 detent+ const off = hook.result.current.dragOffset;+ expect(off).toBeGreaterThan(90); // pulled up toward 100+ expect(off).toBeLessThanOrEqual(100);});it('translates the surface live during a drag', () => {- const {hook} = setup();- const target = makeTarget();- const {handleProps} = hook.result.current;- act(() => {- handleProps.onPointerDown(pointerEvent(0, 0, target));- });- act(() => {- handleProps.onPointerMove(pointerEvent(50, 100, target));- });+ const {hook} = setup({snapHeights: () => [200]});+ const t = makeTarget();+ down(hook, 0, 0, t);+ move(hook, 50, 100, t);expect(hook.result.current.dragOffset).toBe(50);expect(hook.result.current.isDragging).toBe(true);expect(hook.result.current.contentProps.style.transform).toBe(@@ -144,17 +247,164 @@ describe('useSheetGestures', () => {);});- it('ignores upward drag past the fully-open position', () => {- const {hook} = setup();- const target = makeTarget();- const {handleProps} = hook.result.current;- act(() => {- handleProps.onPointerDown(pointerEvent(100, 0, target));+ it('rubber-bands an upward drag past the fully-open position', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const t = makeTarget();+ down(hook, 100, 0, t);+ move(hook, 20, 100, t); // drag up 80px past the top of a rested-at-top sheet+ // Overscroll is allowed but damped: a resisted fraction of the raw -80,+ // and negative (above the top), not the raw distance and not clamped to 0.+ const off = hook.result.current.dragOffset;+ expect(off).toBeLessThan(0);+ expect(off).toBeGreaterThan(-80); // resisted, so smaller in magnitude+ });++ it('dismisses a single-height sheet on a slow drag past the floor', () => {+ const {hook, onDismiss} = setup(); // no snapHeights+ const t = makeTarget();+ // Only detent is the full 400px height (offset 0). A slow drag past 40%+ // of it (>160px) with no detent to catch it dismisses.+ down(hook, 0, 0, t);+ move(hook, 120, 400, t);+ move(hook, 240, 900, t);+ up(hook, 240, 1400, t);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ describe('body overscroll', () => {+ // A scrollable body element nested inside the sheet, with a settable+ // scrollTop so we can simulate "at the top" vs "scrolled".+ function makeBody(scrollTop: number) {+ const body = document.createElement('div');+ Object.defineProperty(body, 'scrollTop', {+ value: scrollTop,+ writable: true,+ });+ body.setPointerCapture = vi.fn();+ body.releasePointerCapture = vi.fn();+ body.getBoundingClientRect = () => ({height: SHEET_HEIGHT}) as DOMRect;+ return body;+ }+ function bodyDown(hook: Hook, y: number, t: number, el: HTMLElement) {+ // Register a sheet element so the hook can measure height (it reads the+ // tracked node, not the DOM). The body stands in with the right height.+ act(() => hook.result.current.sheetRef(el));+ act(() =>+ hook.result.current.bodyProps.onPointerDown(pointerEvent(y, t, el)),+ );+ }+ function bodyMove(hook: Hook, y: number, t: number, el: HTMLElement) {+ act(() =>+ hook.result.current.bodyProps.onPointerMove(pointerEvent(y, t, el)),+ );+ }++ it('promotes a top-overscroll pull-down into a sheet drag', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const body = makeBody(0); // at the top+ bodyDown(hook, 0, 0, body);+ bodyMove(hook, 40, 100, body); // pull down while at the top+ expect(hook.result.current.isDragging).toBe(true);+ expect(hook.result.current.dragOffset).toBe(40);+ });++ it('does not hijack scrolling when the body is scrolled down', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const body = makeBody(120); // scrolled, not at the top+ bodyDown(hook, 0, 0, body);+ bodyMove(hook, 40, 100, body);+ expect(hook.result.current.isDragging).toBe(false);});- // Drag UP (clientY decreasing) — no rubber-band overscroll.- act(() => {- handleProps.onPointerMove(pointerEvent(20, 100, target));++ it('does not start a drag on an upward move from the top', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const body = makeBody(0);+ bodyDown(hook, 100, 0, body);+ bodyMove(hook, 60, 100, body); // moving up = scrolling intent+ expect(hook.result.current.isDragging).toBe(false);+ });+ });++ describe('body touch handoff', () => {+ // Attach a real DOM node via the body ref, then dispatch touch events. The+ // hook's non-passive touchmove listener is how the handoff works on touch+ // devices (pointer events get cancelled once native panning starts).+ function makeScroller(opts: {+ scrollTop: number;+ clientHeight: number;+ scrollHeight: number;+ }) {+ const sheet = makeTarget();+ const el = document.createElement('div');+ Object.defineProperty(el, 'scrollTop', {+ value: opts.scrollTop,+ writable: true,+ });+ Object.defineProperty(el, 'clientHeight', {value: opts.clientHeight});+ Object.defineProperty(el, 'scrollHeight', {value: opts.scrollHeight});+ el.getBoundingClientRect = () => ({height: SHEET_HEIGHT}) as DOMRect;+ sheet.appendChild(el);+ document.body.appendChild(sheet);+ return el;+ }+ function touch(el: HTMLElement, type: string, y: number, id = 1) {+ const ev = new Event(type, {bubbles: true, cancelable: true});+ // jsdom lacks TouchEvent; attach the fields the handler reads.+ Object.defineProperty(ev, 'changedTouches', {+ value: [{identifier: id, clientY: y}],+ });+ Object.defineProperty(ev, 'currentTarget', {value: el});+ el.dispatchEvent(ev);+ return ev;+ }++ it('promotes a top pull-down (touch) into a sheet drag', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const el = makeScroller({+ scrollTop: 0,+ clientHeight: 200,+ scrollHeight: 800,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));+ act(() => {+ touch(el, 'touchstart', 0);+ touch(el, 'touchmove', 50);+ });+ expect(hook.result.current.isDragging).toBe(true);+ });++ it('promotes a bottom pull-up (touch) into a sheet drag', () => {+ const {hook} = setup({snapHeights: () => [200]});+ // scrolled to the bottom: scrollTop + clientHeight === scrollHeight+ const el = makeScroller({+ scrollTop: 600,+ clientHeight: 200,+ scrollHeight: 800,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));+ act(() => {+ touch(el, 'touchstart', 300);+ touch(el, 'touchmove', 250); // pull up+ });+ expect(hook.result.current.isDragging).toBe(true);+ });++ it('leaves native scrolling alone in the middle of the content', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const el = makeScroller({+ scrollTop: 300,+ clientHeight: 200,+ scrollHeight: 800,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));+ act(() => {+ touch(el, 'touchstart', 300);+ touch(el, 'touchmove', 250);+ });+ expect(hook.result.current.isDragging).toBe(false);});- expect(hook.result.current.dragOffset).toBe(0);});});diff --git a/packages/lab/src/BottomSheet/useSheetGestures.ts b/packages/lab/src/BottomSheet/useSheetGestures.tsindex 34c4552c56..56dd2c0fef 100644--- a/packages/lab/src/BottomSheet/useSheetGestures.ts+++ b/packages/lab/src/BottomSheet/useSheetGestures.ts@@ -8,13 +8,14 @@* @output Exports useSheetGestures hook and its option/result types* @position Internal to BottomSheet; not exported from the lab entry point*- * Drag-to-dismiss machinery for the bottom sheet. Tracks a pointer drag- * down the block axis, translates the sliding surface live, and on release- * either dismisses (past a distance or velocity threshold) or springs back- * to fully open. Pointer-events based so one code path covers mouse + touch.+ * Drag + snap machinery for the bottom sheet. Tracks a pointer drag down the+ * block axis, translates the sliding surface live, and on release either+ * settles to the nearest snap detent (a slow drag) or dismisses (a fast flick+ * down). A fast flick up expands to the tallest detent. This is the core+ * behavior split the sheet needs: DRAG places, SWIPE closes.*- * Kept private to BottomSheet: the behavior is sheet-specific (a dismiss- * edge on a bottom-anchored surface). It is not a general primitive and is+ * Kept private to BottomSheet: a dismiss edge + detents on a bottom-anchored+ * surface are inherently sheet concepts. It is not a general primitive and is* intentionally not exported.** SSR-safe: no window/document access at module scope; all measurement@@ -35,18 +36,93 @@ import {type CSSProperties,type PointerEvent as ReactPointerEvent,} from 'react';+import {+ computeDetentOffsets,+ resolveSettleOffset,+ scrimOpacityForOffset,+} from './snapOffsets';++// A flick (fast throw) dismisses (down) or expands (up) regardless of where+// it ends. Requires both a speed and a distance floor so a small nudge+// doesn't trigger it.+const FLICK_VELOCITY = 1.2; // px/ms+const FLICK_MIN_DISTANCE = 48; // px traveled during the gesture+// On a slow drag below the shortest detent, dismiss once dragged past it by+// more than this fraction of that detent's height; otherwise snap back to it.+const DISMISS_OVERSHOOT_RATIO = 0.4;+// Within this many px of a detent, the live drag is magnetically eased toward+// it so it "clicks" into place instead of hovering just off the mark.+const MAGNET_RANGE = 40;+// Rubber-band factor for dragging up past fully-open, capped at OVERSCROLL_MAX+// (the sheet reserves that much bottom padding for the lift to reveal).+const OVERSCROLL_RESISTANCE = 0.35;+// SYNC: must match OVERSCROLL_PADDING in BottomSheet.tsx (the reserved bottom+// padding the lift reveals). Kept as a local const rather than a shared import+// so it can be used inside stylex.create there.+const OVERSCROLL_MAX = 48;-// Fraction of the measured sheet height a drag must cross (with low-// velocity) before release dismisses instead of springing back.-const DISMISS_DISTANCE_RATIO = 0.25;-// A quick flick past this speed (px/ms) dismisses regardless of distance.-const DISMISS_VELOCITY = 0.5;+// Short haptic tick on detent settle where supported. iOS Safari doesn't+// expose navigator.vibrate, so this is a no-op there; skipped under+// reduced-motion.+function hapticTick(): void {+ if (+ typeof navigator === 'undefined' ||+ typeof navigator.vibrate !== 'function'+ ) {+ return;+ }+ if (prefersReducedMotion()) {+ return;+ }+ navigator.vibrate(8);+}++// Pull a value toward the nearest of `targets` when within MAGNET_RANGE, easing+// the last stretch so the surface settles crisply onto a detent while dragging.+function magnetize(value: number, targets: number[]): number {+ let nearestTarget = targets[0];+ let nearestDist = Math.abs(value - nearestTarget);+ for (const t of targets) {+ const d = Math.abs(value - t);+ if (d < nearestDist) {+ nearestDist = d;+ nearestTarget = t;+ }+ }+ if (nearestDist >= MAGNET_RANGE) {+ return value;+ }+ // Ease-in over the range: pull grows as you approach (t^2), so the click+ // feels magnetic near the detent but doesn't fight a deliberate drag-through.+ const t = nearestDist / MAGNET_RANGE;+ const pull = 1 - t * t;+ return value + (nearestTarget - value) * pull;+}export interface UseSheetGesturesOptions {/** Whether the owning sheet is open. Drag state resets when it closes. */isOpen: boolean;- /** Called when a drag crosses the dismiss threshold (distance or flick). */+ /** Called on a swipe-to-close (fast downward flick, or drag past the floor). */onDismiss: () => void;+ /**+ * Resolver for candidate detent heights in px BELOW the full sheet height.+ * Called lazily at the start of each drag so the values stay current (e.g.+ * after a rotation or the virtual keyboard opening) without a persistent+ * resize listener. The measured full height is always the tallest detent,+ * so the effective detent set is `[...snapHeights(), fullHeight]`. Omit for+ * a single-height sheet (a drag then only dismisses or springs back).+ */+ snapHeights?: () => number[];+ /** Notified when the settled detent height (px) changes. */+ onSnap?: (heightPx: number) => void;+ /**+ * Called with the scrim opacity the sheet should show (1 = fully visible,+ * 0 = hidden) as the drag moves and on settle. Full while the sheet is at+ * or above its mid detent, fading to 0 as it collapses onto the shortest+ * "peek" detent — so a glance-height sheet reveals the content behind — and+ * on the dismiss overshoot. Lets the owner mirror it onto the scrim.+ */+ onScrimOpacity?: (opacity: number) => void;}export interface SheetContentProps {@@ -61,13 +137,35 @@ export interface SheetHandleProps {onPointerCancel: (event: ReactPointerEvent) => void;}+export interface SheetBodyProps {+ ref: (node: HTMLElement | null) => void;+ onPointerDown: (event: ReactPointerEvent) => void;+ onPointerMove: (event: ReactPointerEvent) => void;+ onPointerUp: (event: ReactPointerEvent) => void;+ onPointerCancel: (event: ReactPointerEvent) => void;+}+export interface UseSheetGesturesResult {+ /**+ * Callback ref for the sheet surface. The hook observes it (ResizeObserver)+ * to keep the fully-open height current, so detents stay correct across+ * rotation / viewport changes without re-measuring mid-drag.+ */+ sheetRef: (node: HTMLElement | null) => void;/** Spread on the sliding surface: live translate + touch-action guard. */contentProps: SheetContentProps;/** Spread on the grab-handle element: pointer drag handlers. */handleProps: SheetHandleProps;- /** Current live drag offset in px (positive = dragged toward the edge). */+ /**+ * Spread on the scrollable body. An overscroll-at-top pull-down starts a+ * sheet drag (a larger, more forgiving target when the content isn't itself+ * scrolling); normal scrolling passes through untouched.+ */+ bodyProps: SheetBodyProps;+ /** Current live drag translate in px (0 = fully expanded, larger = collapsed). */dragOffset: number;+ /** Translate of the resting detent in px (0 = tallest detent). */+ settledOffset: number;/** Whether a drag is currently in progress. */isDragging: boolean;}@@ -80,15 +178,17 @@ function prefersReducedMotion(): boolean {}/**- * Drag-to-dismiss machinery for the bottom sheet. Returns props to spread on- * the grab handle and the sliding surface, plus live drag state for callers- * that want to drive their own animation.+ * Drag + snap machinery for the bottom sheet. Returns props to spread on the+ * grab handle and the sliding surface, plus live drag state. A slow drag+ * settles to the nearest detent; a fast downward flick dismisses; a fast+ * upward flick expands to the tallest detent.** @example* ```* const {contentProps, handleProps} = useSheetGestures({* isOpen,* onDismiss: () => onOpenChange(false),+ * snapHeights: () => [240, 0.5 * (window.visualViewport?.height ?? 0)],* });* <div {...contentProps}>* <div {...handleProps} />@@ -99,14 +199,23 @@ function prefersReducedMotion(): boolean {export function useSheetGestures({isOpen,onDismiss,+ snapHeights,+ onSnap,+ onScrimOpacity,}: UseSheetGesturesOptions): UseSheetGesturesResult {const [dragOffset, setDragOffset] = useState(0);+ const [settledOffset, setSettledOffset] = useState(0);const [isDragging, setIsDragging] = useState(false);- // Latest callback ref so pointer handlers stay stable across renders.const onDismissRef = useRef(onDismiss);+ const onSnapRef = useRef(onSnap);+ const onScrimOpacityRef = useRef(onScrimOpacity);+ const snapHeightsRef = useRef(snapHeights);useEffect(() => {onDismissRef.current = onDismiss;+ onSnapRef.current = onSnap;+ onScrimOpacityRef.current = onScrimOpacity;+ snapHeightsRef.current = snapHeights;});// Live drag bookkeeping (refs so pointermove doesn't churn renders).@@ -117,68 +226,189 @@ export function useSheetGestures({lastTime: number;velocity: number;height: number;+ baseOffset: number;} | null>(null);- // Reset drag state each time the sheet re-opens.+ // Fully-open height, tracked by a ResizeObserver (see sheetRef) so detents+ // stay correct across rotation / viewport changes without re-measuring.+ const sheetHeightRef = useRef(0);+ const sheetElRef = useRef<HTMLElement | null>(null);+ const observerRef = useRef<ResizeObserver | null>(null);+ const sheetRef = useCallback((node: HTMLElement | null) => {+ observerRef.current?.disconnect();+ observerRef.current = null;+ sheetElRef.current = node;+ if (!node || typeof ResizeObserver === 'undefined') {+ if (node) {+ sheetHeightRef.current = node.getBoundingClientRect().height;+ }+ return;+ }+ sheetHeightRef.current = node.getBoundingClientRect().height;+ const ro = new ResizeObserver(entries => {+ const box = entries[0]?.contentRect;+ if (box && box.height > 0) {+ sheetHeightRef.current = box.height;+ }+ });+ ro.observe(node);+ observerRef.current = ro;+ }, []);+ useEffect(() => () => observerRef.current?.disconnect(), []);++ // Reset to the tallest detent each time the sheet re-opens.useEffect(() => {if (isOpen) {setDragOffset(0);+ setSettledOffset(0);setIsDragging(false);}}, [isOpen]);- const measureHeight = useCallback((el: HTMLElement | null): number => {- const sheet = el?.closest<HTMLElement>('[data-astryx-sheet]') ?? el;- return sheet?.getBoundingClientRect().height ?? 0;+ // The fully-open height for detent math. Prefer the ResizeObserver-locked+ // value; fall back to a live measure of the tracked sheet element if the+ // observer hasn't reported yet.+ const measureHeight = useCallback((): number => {+ if (sheetHeightRef.current > 0) {+ return sheetHeightRef.current;+ }+ return sheetElRef.current?.getBoundingClientRect().height ?? 0;+ }, []);++ // Detent translate offsets (px) from the tallest detent, ascending. The+ // tallest detent is offset 0; shorter detents translate further down.+ // Snap heights are resolved lazily here (at drag start) so they reflect the+ // current viewport without a persistent listener.+ const detentOffsets = useCallback((height: number): number[] => {+ return computeDetentOffsets(height, snapHeightsRef.current?.() ?? []);}, []);const settleFromDrag = useCallback(- (offset: number, velocity: number, height: number) => {- const dismiss =- offset > height * DISMISS_DISTANCE_RATIO || velocity > DISMISS_VELOCITY;- if (dismiss) {+ (+ offset: number,+ velocity: number,+ height: number,+ dir: number,+ travel: number,+ baseOffset: number,+ ) => {+ const offsets = detentOffsets(height);+ const maxOffset = offsets[offsets.length - 1];+ const shortestDetentHeight = height - maxOffset;+ const speed = Math.abs(velocity);+ const isFlick = speed > FLICK_VELOCITY && travel > FLICK_MIN_DISTANCE;++ if (dir > 0 && isFlick) {onDismissRef.current();return;}- // Below threshold: spring back to fully open.- setDragOffset(0);+ // Fast upward flick = expand to the tallest detent (the sheet's full+ // provided height).+ if (dir < 0 && isFlick) {+ setSettledOffset(0);+ onSnapRef.current?.(height);+ onScrimOpacityRef.current?.(1);+ hapticTick();+ return;+ }+ if (offset > maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO) {+ onDismissRef.current();+ 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 (hidden 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();+ }},- [],+ [detentOffsets],);- const handlePointerDown = useCallback(- (event: ReactPointerEvent) => {+ const beginDrag = useCallback(+ (event: ReactPointerEvent, sheetHeight: number, startCoord?: number) => {const target = event.currentTarget as HTMLElement;target.setPointerCapture?.(event.pointerId);+ // `startCoord` lets a body-overscroll drag anchor at the original+ // pointer-down position (not the promotion point), so the first frame's+ // delta reflects the full pull distance.+ const start = startCoord ?? event.clientY;dragStateRef.current = {pointerId: event.pointerId,- startCoord: event.clientY,+ startCoord: start,lastCoord: event.clientY,lastTime: event.timeStamp,velocity: 0,- height: measureHeight(target),+ height: sheetHeight,+ baseOffset: settledOffset,};+ // Seed dragOffset at the resting detent so flipping isDragging doesn't+ // jump the sheet to fully-open for one frame.+ setDragOffset(settledOffset);setIsDragging(true);},- [measureHeight],+ [settledOffset],);- const handlePointerMove = useCallback((event: ReactPointerEvent) => {- const state = dragStateRef.current;- if (!state || state.pointerId !== event.pointerId) {- return;- }- // Dragging DOWN (increasing Y) collapses/dismisses. Only allow drag in- // the closing direction past the fully-open position (no overscroll).- const delta = event.clientY - state.startCoord;- const dt = event.timeStamp - state.lastTime;- if (dt > 0) {- state.velocity = (event.clientY - state.lastCoord) / dt;- state.lastCoord = event.clientY;- state.lastTime = event.timeStamp;- }- setDragOffset(Math.max(0, delta));- }, []);+ const handlePointerDown = useCallback(+ (event: ReactPointerEvent) => {+ beginDrag(event, measureHeight());+ },+ [beginDrag, measureHeight],+ );++ const handlePointerMove = useCallback(+ (event: ReactPointerEvent) => {+ const state = dragStateRef.current;+ if (!state || state.pointerId !== event.pointerId) {+ return;+ }+ const delta = event.clientY - state.startCoord;+ const dt = event.timeStamp - state.lastTime;+ if (dt > 0) {+ state.velocity = (event.clientY - state.lastCoord) / dt;+ state.lastCoord = event.clientY;+ state.lastTime = event.timeStamp;+ }+ const offsets = detentOffsets(state.height);++ const raw = state.baseOffset + delta;+ const maxDetentOffset = offsets[offsets.length - 1];+ let next: number;+ if (raw < 0) {+ // Up past fully-open: damped + capped rubber-band; springs back on release.+ next = Math.max(-OVERSCROLL_MAX, raw * OVERSCROLL_RESISTANCE);+ } else if (raw > maxDetentOffset) {+ // In the dismiss zone: no magnet, so it doesn't fight a drag-to-close.+ next = raw;+ } else {+ // Between detents: magnetically ease toward a nearby one.+ next = magnetize(raw, offsets);+ }+ setDragOffset(next);++ // Mirror the scrim to the live drag: full at/above the mid detent,+ // fading to hidden as it collapses onto the peek detent and through the+ // dismiss overshoot.+ const floorOffset = offsets[offsets.length - 1];+ const shortestDetentHeight = state.height - floorOffset;+ const dismissOffset =+ floorOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;+ onScrimOpacityRef.current?.(+ scrimOpacityForOffset(next, offsets, dismissOffset),+ );+ },+ [detentOffsets],+ );const endDrag = useCallback((event: ReactPointerEvent) => {@@ -188,27 +418,238 @@ export function useSheetGestures({}const target = event.currentTarget as HTMLElement;target.releasePointerCapture?.(event.pointerId);- const offset = Math.max(0, event.clientY - state.startCoord);+ const delta = event.clientY - state.startCoord;+ const offset = Math.max(0, state.baseOffset + delta);+ const dir = delta === 0 ? 0 : delta > 0 ? 1 : -1;dragStateRef.current = null;setIsDragging(false);- settleFromDrag(offset, state.velocity, state.height || 1);+ settleFromDrag(+ offset,+ state.velocity,+ state.height || 1,+ dir,+ Math.abs(delta),+ state.baseOffset,+ );},[settleFromDrag],);- // Reduced motion skips the settle transition (snaps instantly).+ // Pointer path for the body at-top pull-down (desktop / mouse). Touch uses+ // the non-passive listener below, since pointer events are cancelled once a+ // native pan starts.+ const armedBodyRef = useRef<{+ pointerId: number;+ startCoord: number;+ scroller: HTMLElement;+ } | null>(null);++ const handleBodyPointerDown = useCallback((event: ReactPointerEvent) => {+ const scroller = event.currentTarget as HTMLElement;+ if (scroller.scrollTop > 0) {+ armedBodyRef.current = null;+ return;+ }+ armedBodyRef.current = {+ pointerId: event.pointerId,+ startCoord: event.clientY,+ scroller,+ };+ }, []);++ const handleBodyPointerMove = useCallback(+ (event: ReactPointerEvent) => {+ if (dragStateRef.current) {+ handlePointerMove(event);+ return;+ }+ const armed = armedBodyRef.current;+ if (!armed || armed.pointerId !== event.pointerId) {+ return;+ }+ const delta = event.clientY - armed.startCoord;+ if (delta > 0 && armed.scroller.scrollTop <= 0) {+ // Downward pull at the top: promote to a sheet drag, anchored at the+ // original pointer-down position so the pull distance carries over.+ armedBodyRef.current = null;+ beginDrag(event, measureHeight(), armed.startCoord);+ handlePointerMove(event);+ } else if (delta < 0) {+ // Upward move = the user is scrolling; disarm so we don't hijack it.+ armedBodyRef.current = null;+ }+ },+ [beginDrag, handlePointerMove, measureHeight],+ );++ const handleBodyEnd = useCallback(+ (event: ReactPointerEvent) => {+ armedBodyRef.current = null;+ if (dragStateRef.current) {+ endDrag(event);+ }+ },+ [endDrag],+ );++ // Non-passive touchmove is the reliable scroll<->drag handoff on touch:+ // preventDefault() at a scroll edge stops the native scroll and drives the+ // sheet drag through the pointer math (Touch adapted to the fields it reads).+ const bodyNodeRef = useRef<HTMLElement | null>(null);+ const touchDragRef = useRef<{+ id: number;+ startY: number;+ top: boolean;+ bottom: boolean;+ } | null>(null);+ const prevTouchHandlers = useRef<{+ start: (e: TouchEvent) => void;+ move: (e: TouchEvent) => void;+ end: (e: TouchEvent) => void;+ } | null>(null);++ const beginDragRef = useRef(beginDrag);+ const pointerMoveRef = useRef(handlePointerMove);+ const endDragRef = useRef(endDrag);+ const measureHeightRef = useRef(measureHeight);+ useEffect(() => {+ beginDragRef.current = beginDrag;+ pointerMoveRef.current = handlePointerMove;+ endDragRef.current = endDrag;+ measureHeightRef.current = measureHeight;+ });++ const bodyRef = useCallback((node: HTMLElement | null) => {+ const asPointer = (touch: Touch, target: HTMLElement) =>+ ({+ pointerId: touch.identifier,+ clientY: touch.clientY,+ timeStamp: Date.now(),+ currentTarget: target,+ setPointerCapture: () => {},+ releasePointerCapture: () => {},+ }) as unknown as ReactPointerEvent;++ const atTop = (el: HTMLElement) => el.scrollTop <= 0;+ const atBottom = (el: HTMLElement) =>+ el.scrollTop + el.clientHeight >= el.scrollHeight - 1;++ const onTouchStart = (event: TouchEvent) => {+ const scroller = event.currentTarget as HTMLElement;+ const touch = event.changedTouches[0];+ // Arm only at a scroll edge; from mid-content this is an ordinary scroll.+ // At the top, a pull DOWN hands off (collapse); at the bottom, a pull UP+ // hands off (expand). Record the edge so the move handler matches it.+ if (!touch) {+ touchDragRef.current = null;+ return;+ }+ const top = atTop(scroller);+ const bottom = atBottom(scroller);+ if (!top && !bottom) {+ touchDragRef.current = null;+ return;+ }+ touchDragRef.current = {+ id: touch.identifier,+ startY: touch.clientY,+ top,+ bottom,+ };+ };++ const onTouchMove = (event: TouchEvent) => {+ const scroller = event.currentTarget as HTMLElement;+ if (dragStateRef.current) {+ const t = [...event.changedTouches].find(+ x => x.identifier === dragStateRef.current?.pointerId,+ );+ if (t) {+ event.preventDefault();+ pointerMoveRef.current(asPointer(t, scroller));+ }+ return;+ }+ const armed = touchDragRef.current;+ if (!armed) {+ return;+ }+ const t = [...event.changedTouches].find(x => x.identifier === armed.id);+ if (!t) {+ return;+ }+ const delta = t.clientY - armed.startY;+ // Promote to a sheet drag on a pull that opposes the armed edge and can+ // no longer scroll that way: at the top, a downward pull (delta > 0)+ // collapses; at the bottom, an upward pull (delta < 0) expands. The+ // opposite direction is a real scroll, so disarm and let it through.+ const pullDownAtTop = armed.top && delta > 0 && atTop(scroller);+ const pullUpAtBottom = armed.bottom && delta < 0 && atBottom(scroller);+ if (pullDownAtTop || pullUpAtBottom) {+ event.preventDefault();+ touchDragRef.current = null;+ beginDragRef.current(+ asPointer(t, scroller),+ measureHeightRef.current(),+ armed.startY,+ );+ pointerMoveRef.current(asPointer(t, scroller));+ } else if ((armed.top && delta < 0) || (armed.bottom && delta > 0)) {+ // Scrolling away from the armed edge; hand back to native scroll.+ touchDragRef.current = null;+ }+ };++ const onTouchEnd = (event: TouchEvent) => {+ touchDragRef.current = null;+ if (dragStateRef.current) {+ const t = event.changedTouches[0];+ if (t) {+ endDragRef.current(asPointer(t, event.currentTarget as HTMLElement));+ }+ }+ };++ const prev = bodyNodeRef.current;+ if (prev && prevTouchHandlers.current) {+ const h = prevTouchHandlers.current;+ prev.removeEventListener('touchstart', h.start);+ prev.removeEventListener('touchmove', h.move);+ prev.removeEventListener('touchend', h.end);+ prev.removeEventListener('touchcancel', h.end);+ }+ bodyNodeRef.current = node;+ if (node) {+ node.addEventListener('touchstart', onTouchStart, {passive: true});+ node.addEventListener('touchmove', onTouchMove, {passive: false});+ node.addEventListener('touchend', onTouchEnd, {passive: true});+ node.addEventListener('touchcancel', onTouchEnd, {passive: true});+ prevTouchHandlers.current = {+ start: onTouchStart,+ move: onTouchMove,+ end: onTouchEnd,+ };+ } else {+ prevTouchHandlers.current = null;+ }+ }, []);+const reducedMotion = useMemo(prefersReducedMotion, [isOpen]);+ // While dragging, follow the finger; otherwise rest at the settled detent.+ const activeOffset = isDragging ? dragOffset : settledOffset;+const contentProps = useMemo<SheetContentProps>(() => ({style: {- transform: dragOffset !== 0 ? `translateY(${dragOffset}px)` : undefined,+ transform:+ activeOffset !== 0 ? `translateY(${activeOffset}px)` : undefined,transition: isDragging || reducedMotion ? 'none' : undefined,touchAction: 'none',overscrollBehavior: 'contain',},}),- [dragOffset, isDragging, reducedMotion],+ [activeOffset, isDragging, reducedMotion],);const handleProps = useMemo<SheetHandleProps>(@@ -222,5 +663,24 @@ export function useSheetGestures({[handlePointerDown, handlePointerMove, endDrag],);- return {contentProps, handleProps, dragOffset, isDragging};+ const bodyProps = useMemo<SheetBodyProps>(+ () => ({+ ref: bodyRef,+ onPointerDown: handleBodyPointerDown,+ onPointerMove: handleBodyPointerMove,+ onPointerUp: handleBodyEnd,+ onPointerCancel: handleBodyEnd,+ }),+ [bodyRef, handleBodyPointerDown, handleBodyPointerMove, handleBodyEnd],+ );++ return {+ sheetRef,+ contentProps,+ handleProps,+ bodyProps,+ dragOffset,+ settledOffset,+ isDragging,+ };}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 83d92c4021..afe37523c1 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -35,7 +35,7 @@ export * from './Chat';// Drawer — experimental overlay panelexport {Drawer, type DrawerProps} from './Drawer';-// BottomSheet — mobile touch sheet built on the Drawer <dialog> engine+// BottomSheet — mobile touch sheet on a native modal <dialog>export {BottomSheet, type BottomSheetProps} from './BottomSheet';// Stat — experimental KPI/metric display