Skip to content

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

TypeScript

feat(core): let the Bottom Sheet's host choose its snap points (#5203)

Xinzi Zhou0e8af82848ca
diff --git a/.changeset/bottom-sheet-configurable-snap-points.md b/.changeset/bottom-sheet-configurable-snap-points.md
new file mode 100644
index 0000000000..4f2bf21e5d
--- /dev/null
+++ b/.changeset/bottom-sheet-configurable-snap-points.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] BottomSheet: `snapPoints` makes the drag-to-resize stops the host's choice. A stop is the sheet's visible height, written as a viewport fraction (`0.5`), a percentage (`'50%'`), or a px length (`'320px'`) — matching `height`, where a bare number is also px and a string carries its unit. Fractions and percentages re-resolve when the viewport changes, so a sheet keeps the stop the user chose across a rotation, and swapping the points under a resting sheet re-anchors it the same way. A stop of a quarter of the sheet or less is a peek: it slides away rather than reflowing into a sliver, and thins the scrim. Taller stops are working surfaces, so they lay their content out and keep the scrim full — previously the shortest stop was always a peek, which would have thinned the backdrop of a half-height sheet.
+
+Behavior change, deliberate and not breaking: every sheet used to carry three built-in stops (14%, 50% and 92% of the viewport), so a drag could leave it resting somewhere the host never asked for. A sheet now opens and closes unless `snapPoints` says otherwise; pass `snapPoints={[0.14, 0.5, 0.92]}` to keep the old stops. No prop, type, or DOM output was removed or renamed, and swipe-to-dismiss, the height budgets, and mobile-keyboard accommodation are untouched.
+
+@imdreamrunner
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsx
index e821bdfc0f..72f5f4d009 100644
--- a/apps/storybook/stories/BottomSheet.stories.tsx
+++ b/apps/storybook/stories/BottomSheet.stories.tsx
@@ -80,8 +80,9 @@ function MobileKeyboardCommentForm({onPost}: {onPost: () => void}) {
<Text type="supporting" color="secondary">
Keep the Tall sheet fully expanded, then focus fields near the
beginning, middle, and end. The outer sheet remains stationary while its
- body scrolls each control above the mobile keyboard. Keyboard
- accommodation is not provided at shorter snap points.
+ body scrolls each control above the mobile keyboard. Drag it down to the
+ half-height stop and the accommodation stops — only a fully expanded
+ Tall sheet provides it — then drag back up and it resumes.
</Text>
<Text type="supporting" color="secondary">
Move the sheet with its handle or close it with Post comment to verify
@@ -218,8 +219,9 @@ export const TallSheet: Story = {
<Section padding={4}>
<VStack gap={3}>
<Text type="supporting" color="secondary">
- Drag the handle to resize between snap points; flick down to
- dismiss or up to expand. Escape also dismisses.
+ A Tall sheet fills most of the viewport and scrolls its content.
+ It has no snap points, so a drag springs back; flick down to
+ dismiss. Escape also dismisses.
</Text>
<Divider />
{Array.from({length: 12}, (_, i) => (
@@ -238,6 +240,80 @@ export const TallSheet: Story = {
},
};
+export const SnapPoints: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Button label="Open nearby places" onClick={() => setIsOpen(true)} />
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Nearby places"
+ height="tall"
+ snapPoints={[0.5]}>
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Text type="supporting" color="secondary">
+ One extra stop, at half the viewport. Drag the handle down to
+ collapse the sheet, then back up — the list keeps its scroll
+ position. Flick down to dismiss.
+ </Text>
+ <Divider />
+ {Array.from({length: 12}, (_, i) => (
+ <VStack key={i} gap={1}>
+ <Text type="label">Place {i + 1}</Text>
+ <Text type="supporting" color="secondary">
+ {(0.2 + i * 0.3).toFixed(1)} mi away
+ </Text>
+ </VStack>
+ ))}
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+ },
+};
+
+export const SnapPointsWithPeek: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Button label="Open route" onClick={() => setIsOpen(true)} />
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Route"
+ height="tall"
+ snapPoints={['96px', '50%']}>
+ <Section padding={4}>
+ <VStack gap={3}>
+ <Heading level={3}>To Ferry Building</Heading>
+ <Text type="supporting" color="secondary">
+ Three stops: full, half the viewport, and a 96px peek. The half
+ stop is a working surface — content laid out, scrim full. The
+ peek is a glance: the sheet slides away rather than reflowing
+ into a sliver, and the scrim thins.
+ </Text>
+ <Divider />
+ {Array.from({length: 10}, (_, i) => (
+ <VStack key={i} gap={1}>
+ <Text type="label">Step {i + 1}</Text>
+ <Text type="supporting" color="secondary">
+ Continue for {(0.1 + i * 0.4).toFixed(1)} mi
+ </Text>
+ </VStack>
+ ))}
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </>
+ );
+ },
+};
+
export const NoScrim: Story = {
render: () => {
const [isOpen, setIsOpen] = useState(false);
@@ -409,7 +485,8 @@ export const MobileKeyboard: Story = {
isOpen={isOpen}
onOpenChange={setIsOpen}
label="Add a comment"
- height="tall">
+ height="tall"
+ snapPoints={[0.5]}>
<Section padding={4}>
<MobileKeyboardCommentForm onPost={() => setIsOpen(false)} />
</Section>
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.doc.mjs b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.doc.mjs
new file mode 100644
index 0000000000..61b6e6747d
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.doc.mjs
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'BottomSheet',
+ name: 'Bottom Sheet — Snap points',
+ displayName: 'Bottom Sheet — Snap points',
+ description:
+ 'Drag-to-resize stops: a half-height working surface, and a peek that slides away and thins the scrim.',
+ isReady: true,
+ aspectRatio: 3 / 4,
+ componentsUsed: [
+ 'BottomSheet',
+ 'Button',
+ 'Divider',
+ 'Heading',
+ 'Icon',
+ 'Item',
+ 'Stack',
+ 'Text',
+ ],
+};
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.tsx b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.tsx
new file mode 100644
index 0000000000..c74e80f456
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSnapPoints.tsx
@@ -0,0 +1,155 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {
+ BottomSheet,
+ type BottomSheetSnapPoint,
+} from '@astryxdesign/core/BottomSheet';
+import {Button} from '@astryxdesign/core/Button';
+import {Divider} from '@astryxdesign/core/Divider';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Icon} from '@astryxdesign/core/Icon';
+import {Item} from '@astryxdesign/core/Item';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
+import {
+ ArrowLeftIcon,
+ ArrowRightIcon,
+ ArrowUpIcon,
+ ArrowUturnLeftIcon,
+ FlagIcon,
+ MapPinIcon,
+} from '@heroicons/react/24/outline';
+
+// Half the viewport is a working surface — the sheet lays its content out at
+// that height and keeps a full scrim. The 96px stop is a peek: a sliver, so the
+// sheet slides away rather than reflowing into it, and the scrim thins.
+const SNAP_POINTS: ReadonlyArray<BottomSheetSnapPoint> = ['96px', '50%'];
+
+const steps = [
+ {
+ icon: MapPinIcon,
+ label: 'Head northeast on Mission St',
+ detail: 'Toward 3rd St',
+ distance: '350 ft',
+ },
+ {
+ icon: ArrowRightIcon,
+ label: 'Turn right onto 3rd St',
+ detail: 'Pass Yerba Buena Gardens on your left',
+ distance: '0.2 mi',
+ },
+ {
+ icon: ArrowUpIcon,
+ label: 'Continue onto Kearny St',
+ detail: 'Stay in the right lane',
+ distance: '0.4 mi',
+ },
+ {
+ icon: ArrowLeftIcon,
+ label: 'Turn left onto Market St',
+ detail: 'Cable car crossing ahead',
+ distance: '0.6 mi',
+ },
+ {
+ icon: ArrowRightIcon,
+ label: 'Bear right onto Sutter St',
+ detail: 'Toward the Financial District',
+ distance: '0.3 mi',
+ },
+ {
+ icon: ArrowUpIcon,
+ label: 'Continue on Sansome St',
+ detail: 'Four blocks, past Pine St',
+ distance: '0.5 mi',
+ },
+ {
+ icon: ArrowUturnLeftIcon,
+ label: 'Make a U-turn at Washington St',
+ detail: 'Construction detour until March',
+ distance: '150 ft',
+ },
+ {
+ icon: ArrowRightIcon,
+ label: 'Turn right onto Battery St',
+ detail: 'Follow signs for the Embarcadero',
+ distance: '0.4 mi',
+ },
+ {
+ icon: ArrowLeftIcon,
+ label: 'Turn left onto Sacramento St',
+ detail: 'Toward the waterfront',
+ distance: '0.2 mi',
+ },
+ {
+ icon: ArrowRightIcon,
+ label: 'Turn right onto The Embarcadero',
+ detail: 'Bay Bridge on your right',
+ distance: '0.5 mi',
+ },
+ {
+ icon: ArrowUpIcon,
+ label: 'Continue past Pier 14',
+ detail: 'Ferry terminal signage begins here',
+ distance: '0.3 mi',
+ },
+ {
+ icon: FlagIcon,
+ label: 'Arrive at the Ferry Building',
+ detail: 'Parking garage entrance on Washington St',
+ distance: '—',
+ },
+];
+
+export default function BottomSheetSnapPoints() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <VStack gap={3} align="start">
+ <Text type="body">
+ This sheet has two extra stops: half the viewport, and a 96px peek.
+ Drag the handle down to collapse it, then back up — it rests at each
+ stop instead of following your finger.
+ </Text>
+ <Button label="Show directions" onClick={() => setIsOpen(true)} />
+ </VStack>
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Directions to the Ferry Building"
+ height="tall"
+ snapPoints={SNAP_POINTS}>
+ <VStack gap={4} padding={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Ferry Building</Heading>
+ <HStack gap={2}>
+ <Text type="label">18 min</Text>
+ <Text type="supporting">3.7 mi · arrive 9:41 AM</Text>
+ </HStack>
+ </VStack>
+ <Divider />
+ <VStack gap={0}>
+ {steps.map(step => (
+ <Item
+ key={step.label}
+ startContent={<Icon icon={step.icon} size="sm" />}
+ label={step.label}
+ description={step.detail}
+ endContent={<Text type="supporting">{step.distance}</Text>}
+ />
+ ))}
+ </VStack>
+ <Divider />
+ <Button
+ label="Start"
+ onClick={() => setIsOpen(false)}
+ variant="primary"
+ />
+ </VStack>
+ </BottomSheet>
+ </>
+ );
+}
diff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjs
index 4a2ecd5233..1c4917b491 100644
--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs
+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs
@@ -13,6 +13,9 @@ export const docs = {
'touch',
'drag',
'swipe',
+ 'snap point',
+ 'detent',
+ 'resize',
'dismiss',
'grab handle',
'dialog',
@@ -54,7 +57,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 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>.",
+ "A mobile touch sheet that rises from the bottom edge, with animated entrance and exit, a grab handle, optional 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',
@@ -99,9 +102,15 @@ export const docs = {
name: 'height',
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. Only a fully expanded 'tall' sheet provides mobile-keyboard accommodation: it stays put and scrolls each focused control above the keyboard. Hug, Capped, numeric and CSS-length heights never do, and a Tall sheet stops doing it the moment the user drags it to a shorter detent — resuming when they drag it back. Outside that state the sheet neither moves nor adds keyboard scroll space, and the browser's own focus reveal is left in place; on iOS that reveal can shift the whole page.",
+ "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. Give snapPoints to let the user drag between heights. On shorter viewports the sheet fills the available height. Only a fully expanded 'tall' sheet provides mobile-keyboard accommodation: it stays put and scrolls each focused control above the keyboard. Hug, Capped, numeric and CSS-length heights never do, and a Tall sheet stops doing it the moment the user drags it to a shorter detent — resuming when they drag it back. Outside that state the sheet neither moves nor adds keyboard scroll space, and the browser's own focus reveal is left in place; on iOS that reveal can shift the whole page.",
default: "'capped'",
},
+ {
+ name: 'snapPoints',
+ type: 'ReadonlyArray<number | string>',
+ description:
+ "Extra heights the sheet can rest at when dragged; its own height is always the tallest stop, and omitting this gives a sheet that only opens and closes. Each stop is the sheet's visible height: a number is a viewport fraction (0.5 is half the screen), '50%' the same in CSS, '320px' an absolute length. A stop of a quarter of the sheet or less is a peek — it slides away instead of reflowing, and thins the scrim.",
+ },
{
name: 'hasScrim',
type: 'boolean',
@@ -156,6 +165,30 @@ export const docs = {
label="Nearby places"
height="tall">
<PlaceList />
+</BottomSheet>`,
+ },
+ {
+ label: 'Collapsible to half the screen',
+ code: `const [isOpen, setIsOpen] = useState(false);
+<BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Nearby places"
+ height="tall"
+ snapPoints={[0.5]}>
+ <PlaceList />
+</BottomSheet>`,
+ },
+ {
+ label: 'A peek, a working height, and full',
+ code: `const [isOpen, setIsOpen] = useState(false);
+<BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Route"
+ height="tall"
+ snapPoints={['96px', '50%']}>
+ <RouteDetails />
</BottomSheet>`,
},
{
@@ -236,7 +269,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, transform-based drag-to-resize snap points, scrolling area resizes to the snapped visible height on release (the peek detent keeps the full height and slides instead), Dialog-aligned dismissal purpose (info/form/required), purpose-gated 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, opt-in transform-based drag-to-resize snap points (snapPoints: viewport fraction, percent or px length), scrolling area resizes to the snapped visible height on release (a peek stop — a quarter of the sheet or less — keeps the full height and slides instead), Dialog-aligned dismissal purpose (info/form/required), purpose-gated swipe-to-dismiss, 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.',
diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsx
index 5a3c358b54..2a2752ffd7 100644
--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx
@@ -15,6 +15,12 @@ import {createRef, useState} from 'react';
import {BottomSheet} from './BottomSheet';
import {BottomSheetSwitcher} from './BottomSheetSwitcher';
+// A sheet has no stops unless its host asks for them, so the tests that
+// exercise detents pass their own. These three — a 14% peek, a half-height
+// stop, and a 92% stop the Tall budget already covers — are the geometry the
+// height assertions below are written against.
+const SNAP_POINTS: ReadonlyArray<number> = [0.14, 0.5, 0.92];
+
// jsdom doesn't implement <dialog> open/close or pointer capture; stub them.
beforeEach(() => {
HTMLDialogElement.prototype.showModal = vi.fn(function (
@@ -178,13 +184,20 @@ function finishSheetExit() {
fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
}
-function ExitHarness({hasScrim}: {hasScrim?: boolean}) {
+function ExitHarness({
+ hasScrim,
+ snapPoints,
+}: {
+ hasScrim?: boolean;
+ snapPoints?: ReadonlyArray<number>;
+}) {
const [isOpen, setIsOpen] = useState(true);
return (
<BottomSheet
isOpen={isOpen}
onOpenChange={setIsOpen}
label="Filters"
+ snapPoints={snapPoints}
hasScrim={hasScrim}>
<button type="button" onClick={() => setIsOpen(false)}>
Close sheet
@@ -616,6 +629,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Release notes"
+ snapPoints={SNAP_POINTS}
height="tall">
Content
</BottomSheet>,
@@ -667,6 +681,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Release notes"
+ snapPoints={SNAP_POINTS}
height="tall">
Content
</BottomSheet>,
@@ -720,6 +735,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Release notes"
+ snapPoints={SNAP_POINTS}
height="tall">
Content
</BottomSheet>,
@@ -797,6 +813,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Release notes"
+ snapPoints={SNAP_POINTS}
height="tall"
style={{transition: 'none'}}>
Content
@@ -830,6 +847,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Release notes"
+ snapPoints={SNAP_POINTS}
height="tall">
Content
</BottomSheet>,
@@ -890,7 +908,7 @@ describe('BottomSheet', () => {
const observers = mockResizeObserverInstances();
mockVisualViewport(800);
mockWindowHeight(800);
- render(<ExitHarness />);
+ render(<ExitHarness snapPoints={SNAP_POINTS} />);
const sheet = getSheet();
const sheetObserver = observers.find(instance =>
instance.observed.has(sheet),
@@ -936,6 +954,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Release notes"
+ snapPoints={SNAP_POINTS}
height="tall">
Content
</BottomSheet>,
@@ -1000,6 +1019,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Release notes"
+ snapPoints={SNAP_POINTS}
height="tall">
Content
</BottomSheet>,
@@ -1039,6 +1059,136 @@ describe('BottomSheet', () => {
});
});
+ describe('snapPoints', () => {
+ // A Tall sheet in an 800px window: a 784px border box, 48px of which is
+ // the reserve below the fold, so 736px of it is visible.
+ function renderTallSheet(
+ snapPoints?: ReadonlyArray<number | string>,
+ onOpenChange: (isOpen: boolean) => void = () => {},
+ ) {
+ const observers = mockResizeObserverInstances();
+ mockVisualViewport(800);
+ mockWindowHeight(800);
+ const view = render(
+ <BottomSheet
+ isOpen
+ onOpenChange={onOpenChange}
+ label="Release notes"
+ snapPoints={snapPoints}
+ height="tall">
+ Content
+ </BottomSheet>,
+ );
+ const sheet = getSheet();
+ const sheetObserver = observers.find(instance =>
+ instance.observed.has(sheet),
+ );
+ act(() => {
+ sheetObserver?.callback(
+ [resizeEntry(784, 736)],
+ sheetObserver as unknown as ResizeObserver,
+ );
+ });
+ return {sheet, view};
+ }
+
+ function dragHandleTo(y: number) {
+ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});
+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y});
+ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y});
+ fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
+ }
+
+ it('has no stops of its own, so a released drag springs back', () => {
+ const onOpenChange = vi.fn();
+ const {sheet} = renderTallSheet(undefined, onOpenChange);
+
+ // 200px down is well short of the dismiss threshold, and there is no
+ // stop to catch it, so the sheet returns to fully open.
+ dragHandleTo(200);
+
+ expect(sheet.style.transform).toBe('');
+ expect(sheet.style.height).toBe('');
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('rests at a stop given as a fraction of the viewport', () => {
+ const {sheet} = renderTallSheet([0.5]);
+
+ // Half of the 800px window is 400px of visible sheet: 736 - 400 = 336px
+ // of travel, taken as layout height once the snap lands.
+ dragHandleTo(336);
+
+ expect(sheet.style.height).toBe('448px');
+ expect(sheet.style.transform).toBe('');
+ });
+
+ it('reads a percentage as the same stop as the fraction', () => {
+ const {sheet} = renderTallSheet(['50%']);
+ dragHandleTo(336);
+ expect(sheet.style.height).toBe('448px');
+ });
+
+ it('rests at a stop given as an absolute px length', () => {
+ const {sheet} = renderTallSheet(['320px']);
+
+ // A 320px stop sits 736 - 320 = 416px down, whatever the window does.
+ dragHandleTo(416);
+
+ expect(sheet.style.height).toBe('368px');
+ expect(sheet.style.transform).toBe('');
+ });
+
+ it('re-anchors to the same stop when the points change under a resting sheet', () => {
+ const {sheet, view} = renderTallSheet([0.5]);
+ dragHandleTo(336);
+ expect(sheet.style.height).toBe('448px');
+
+ // Without an inline height the sheet renders its natural 92dvh budget.
+ vi.spyOn(sheet, 'getBoundingClientRect').mockImplementation(() =>
+ rect({
+ top: 0,
+ bottom: sheet.style.height
+ ? Number.parseFloat(sheet.style.height)
+ : 784,
+ }),
+ );
+
+ // The host moves its one stop from half the window to a quarter of it.
+ // The sheet is resting on that stop, so it follows — no gesture, and
+ // nothing to animate.
+ view.rerender(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Release notes"
+ snapPoints={[0.25]}
+ height="tall">
+ Content
+ </BottomSheet>,
+ );
+
+ // 200px of visible sheet is 736 - 200 = 536px of travel.
+ expect(sheet.style.height).toBe('248px');
+ expect(sheet.style.transform).toBe('');
+ });
+
+ it('ignores a stop it cannot resolve, and warns which one', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ // 200 is the px mistake: a bare number is a fraction, never a length.
+ const {sheet} = renderTallSheet([0.5, 200]);
+
+ expect(
+ warn.mock.calls.some(args => String(args[0]).includes('200')),
+ ).toBe(true);
+
+ // The stop it could read still works.
+ dragHandleTo(336);
+ expect(sheet.style.height).toBe('448px');
+ warn.mockRestore();
+ });
+ });
+
describe('mobile keyboard', () => {
it('claims a transition between fields and delivers it with preventScroll', () => {
mockIOSWebKit();
@@ -1293,6 +1443,7 @@ describe('BottomSheet', () => {
isOpen
onOpenChange={() => {}}
label="Add a comment"
+ snapPoints={SNAP_POINTS}
height="tall">
<input aria-label="Comment" />
</BottomSheet>,
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index 45de45f902..f73a3de3f6 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -49,8 +49,8 @@ import {
type BottomSheetSwitcherPhase,
} from './BottomSheetSwitcherContext';
-export type {BottomSheetHeight} from './BottomSheetPanel';
-import type {BottomSheetHeight} from './BottomSheetPanel';
+export type {BottomSheetHeight, BottomSheetSnapPoint} from './BottomSheetPanel';
+import type {BottomSheetHeight, BottomSheetSnapPoint} from './BottomSheetPanel';
const styles = stylex.create({
dialog: {
@@ -122,6 +122,16 @@ interface BottomSheetSharedProps extends BaseProps<HTMLDivElement> {
/** Height budget or custom CSS length. Only fully expanded Tall is keyboard-aware. @default 'capped' */
height?: BottomSheetHeight | number | string;
+ /**
+ * Extra heights the sheet can rest at when dragged; its own height is always
+ * the tallest stop, and omitting this gives a sheet that only opens and
+ * closes. Each stop is the sheet's visible height: a number is a viewport
+ * fraction (`0.5` is half the screen), `'50%'` the same in CSS, `'320px'` an
+ * absolute length. A stop of a quarter of the sheet or less is a peek — it
+ * slides away instead of reflowing, and thins the scrim.
+ */
+ snapPoints?: ReadonlyArray<BottomSheetSnapPoint>;
+
/**
* Configures implicit dismissal behavior, matching Dialog.
* - required: Blocks swipe, scrim click, and Escape
@@ -193,6 +203,7 @@ function StandaloneBottomSheet({
label,
children,
height = 'capped',
+ snapPoints,
hasScrim = true,
purpose = 'info',
xstyle,
@@ -333,6 +344,7 @@ function StandaloneBottomSheet({
ref={ref}
state={panelState}
height={height}
+ snapPoints={snapPoints}
isSwipeDismissAllowed={purpose === 'info'}
isPageScrollLocked={shouldPresent && hasScrim}
xstyle={xstyle}
@@ -358,6 +370,7 @@ function SwitcherBottomSheetItem({
label,
children,
height = 'capped',
+ snapPoints,
purpose = 'info',
xstyle,
...props
@@ -488,6 +501,7 @@ function SwitcherBottomSheetItem({
ref={ref}
state={panelState}
height={height}
+ snapPoints={snapPoints}
isSwipeDismissAllowed={purpose === 'info'}
isPageScrollLocked={hasScrim}
xstyle={xstyle}
diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
index 3ff380e5f6..4a0d22ecb8 100644
--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
@@ -16,6 +16,7 @@
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/BottomSheet/BottomSheet.tsx
* - /packages/core/src/BottomSheet/BottomSheetPanel.test.tsx
+ * - /packages/core/src/BottomSheet/snapOffsets.ts
* - /packages/core/src/BottomSheet/useMobileKeyboard.ts
* - /packages/core/src/BottomSheet/useSheetGestures.ts
*/
@@ -25,11 +26,13 @@ import {
useEffect,
useImperativeHandle,
useLayoutEffect,
+ useMemo,
useRef,
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
+import {useDevWarning} from '../hooks';
import {
colorVars,
durationVars,
@@ -40,11 +43,14 @@ import {
spacingVars,
} from '../theme/tokens.stylex';
import {mergeProps, themeProps} from '../utils';
+import {
+ isValidSnapPoint,
+ resolveSnapPoints,
+ type BottomSheetSnapPoint,
+} from './snapOffsets';
import {useMobileKeyboard} from './useMobileKeyboard';
import {useSheetGestures} from './useSheetGestures';
-const SNAP_FRACTIONS = [0.14, 0.5, 0.92];
-
const HEIGHT_BUDGETS = {
hug: '92dvh',
capped: '62dvh',
@@ -52,23 +58,39 @@ const HEIGHT_BUDGETS = {
} as const;
export type BottomSheetHeight = keyof typeof HEIGHT_BUDGETS;
+export type {BottomSheetSnapPoint};
// SYNC: must match OVERSCROLL_MAX in useSheetGestures.ts.
const OVERSCROLL_PADDING = 48;
const MOBILE_KEYBOARD_BOTTOM_CLEARANCE = 48;
const TRANSITION_BACKSTOP_BUFFER_MS = 50;
-function defaultSnapHeights(): number[] {
- if (typeof window === 'undefined') {
- return [];
+// Measure the same viewport the height budgets are written against. Those are
+// `dvh`, which the virtual keyboard does not shrink, so reading
+// `visualViewport` here would make the two disagree by exactly the keyboard's
+// height: every detent would move while the sheet it measures did not. A
+// keyboard is `useMobileKeyboard`'s business — it holds the sheet still and
+// scrolls the body — and it does not redefine the sheet's detents.
+function layoutViewportHeight(): number {
+ return typeof window === 'undefined' ? 0 : window.innerHeight;
+}
+
+/**
+ * A stable identity for a set of snap points. Type-tagged, so the fraction
+ * `0.5` and the (invalid) string `'0.5'` cannot collide on one key.
+ *
+ * Recomputed every render — the panel re-renders on every frame of a drag — so
+ * it stays a single pass over a handful of values, and everything derived from
+ * the points hangs off it instead of being rebuilt per frame.
+ */
+function snapPointsKeyFor(
+ points: ReadonlyArray<BottomSheetSnapPoint> | undefined,
+): string {
+ let key = '';
+ for (const point of points ?? []) {
+ key += `${typeof point}:${point}|`;
}
- // Measure the same viewport the height budgets are written against. Those
- // are `dvh`, which the virtual keyboard does not shrink, so reading
- // `visualViewport` here made the two disagree by exactly the keyboard's
- // height: every detent moved while the sheet it was measuring did not. A
- // keyboard is `useMobileKeyboard`'s business — it holds the sheet still and
- // scrolls the body — and it does not redefine the sheet's detents.
- return SNAP_FRACTIONS.map(fraction => fraction * window.innerHeight);
+ return key;
}
const styles = stylex.create({
@@ -171,6 +193,7 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {
state: BottomSheetPanelState;
height: BottomSheetHeight | number | string;
children: ReactNode;
+ snapPoints?: ReadonlyArray<BottomSheetSnapPoint>;
isSwipeDismissAllowed?: boolean;
/** Whether the host has locked page scrolling (a modal, scrim-backed sheet). */
isPageScrollLocked?: boolean;
@@ -296,6 +319,7 @@ export function BottomSheetPanel({
state,
height,
children,
+ snapPoints,
className,
style,
tabIndex,
@@ -340,6 +364,36 @@ export function BottomSheetPanel({
const isFading = isRetained && state.motion === 'fading';
const alignmentOffset = isRetained ? state.alignmentOffset : 0;
+ // Everything derived from the snap points keys off their identity, not the
+ // array's: the resolver's identity is the hook's signal that the stops
+ // changed, so it must not churn on a re-render the drag caused. The memo
+ // reads the points through a ref, so the resolver resolves them at call time
+ // — against whatever the viewport is then, not what it was at memo time.
+ const snapPointsKey = snapPointsKeyFor(snapPoints);
+ const snapPointsRef = useRef(snapPoints);
+ snapPointsRef.current = snapPoints;
+ const {snapHeights, ignoredSnapPointsMessage} = useMemo(() => {
+ if (snapPointsKey === '') {
+ return {snapHeights: undefined, ignoredSnapPointsMessage: ''};
+ }
+ const ignored = (snapPointsRef.current ?? []).filter(
+ point => !isValidSnapPoint(point),
+ );
+ return {
+ snapHeights: () =>
+ resolveSnapPoints(snapPointsRef.current ?? [], layoutViewportHeight()),
+ ignoredSnapPointsMessage:
+ ignored.length === 0
+ ? ''
+ : `snapPoints ignored ${JSON.stringify(ignored)}. A snap point is a viewport fraction above 0 and up to 1 (0.5 is half the screen), a px length ('320px'), or a percentage ('50%').`,
+ };
+ }, [snapPointsKey]);
+ useDevWarning(
+ 'BottomSheet',
+ ignoredSnapPointsMessage,
+ ignoredSnapPointsMessage !== '',
+ );
+
const {
contentProps,
handleProps,
@@ -359,7 +413,7 @@ export function BottomSheetPanel({
canDismiss: isSwipeDismissAllowed,
offscreenBlockEndInset: OVERSCROLL_PADDING,
onDismiss,
- snapHeights: defaultSnapHeights,
+ snapHeights,
onScrimOpacity,
});
diff --git a/packages/core/src/BottomSheet/index.ts b/packages/core/src/BottomSheet/index.ts
index 74ac7d0d93..b2ceeff86a 100644
--- a/packages/core/src/BottomSheet/index.ts
+++ b/packages/core/src/BottomSheet/index.ts
@@ -10,6 +10,10 @@
*/
export {BottomSheet} from './BottomSheet';
-export type {BottomSheetHeight, BottomSheetProps} from './BottomSheet';
+export type {
+ BottomSheetHeight,
+ BottomSheetProps,
+ BottomSheetSnapPoint,
+} from './BottomSheet';
export {BottomSheetSwitcher} from './BottomSheetSwitcher';
export type {BottomSheetSwitcherProps} from './BottomSheetSwitcher';
diff --git a/packages/core/src/BottomSheet/snapOffsets.test.ts b/packages/core/src/BottomSheet/snapOffsets.test.ts
index 3ad92f2b46..a165981687 100644
--- a/packages/core/src/BottomSheet/snapOffsets.test.ts
+++ b/packages/core/src/BottomSheet/snapOffsets.test.ts
@@ -11,24 +11,73 @@
import {describe, it, expect} from 'vitest';
import {
- snapFractionsToHeights,
computeDetentOffsets,
+ isValidSnapPoint,
nearestOffset,
+ peekOffsetFor,
resolveSettleOffset,
+ resolveSnapPoints,
scrimOpacityForOffset,
- isPeekOffset,
DETENT_DEDUP_PX,
} from './snapOffsets';
-describe('snapFractionsToHeights', () => {
- it('scales in-range fractions to px', () => {
- expect(snapFractionsToHeights([0.5, 0.92], 800)).toEqual([400, 736]);
+describe('resolveSnapPoints', () => {
+ it('reads a bare number as a fraction of the viewport', () => {
+ expect(resolveSnapPoints([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([
+
+ it('reads a percentage as the same fraction', () => {
+ expect(resolveSnapPoints(['50%', '92%'], 800)).toEqual([400, 736]);
+ });
+
+ it('reads a px length as an absolute height', () => {
+ expect(resolveSnapPoints(['320px'], 800)).toEqual([320]);
+ });
+
+ it('keeps the caller order, mixing forms', () => {
+ expect(resolveSnapPoints(['120px', 0.5, '90%'], 800)).toEqual([
+ 120, 400, 720,
+ ]);
+ });
+
+ it('accepts fractional and unit-cased lengths, and surrounding space', () => {
+ expect(resolveSnapPoints(['12.5%', '0.5PX', ' 80px '], 800)).toEqual([
+ 100, 0.5, 80,
+ ]);
+ });
+
+ it('drops numbers outside the (0, 1] fraction range', () => {
+ // 200 is the px mistake — a bare number is never a length.
+ expect(resolveSnapPoints([0, 0.5, 1, 1.2, -0.3, 200], 1000)).toEqual([
500, 1000,
]);
});
+
+ it('drops lengths it cannot resolve by arithmetic on the viewport', () => {
+ expect(
+ resolveSnapPoints(
+ ['50', '30rem', '50vh', 'calc(50% - 20px)', '-10px', '', '0px'],
+ 800,
+ ),
+ ).toEqual([]);
+ });
+});
+
+describe('isValidSnapPoint', () => {
+ it('accepts the three supported forms', () => {
+ expect(isValidSnapPoint(0.5)).toBe(true);
+ expect(isValidSnapPoint(1)).toBe(true);
+ expect(isValidSnapPoint('50%')).toBe(true);
+ expect(isValidSnapPoint('320px')).toBe(true);
+ });
+
+ it('rejects what resolveSnapPoints would silently drop', () => {
+ expect(isValidSnapPoint(200)).toBe(false);
+ expect(isValidSnapPoint(0)).toBe(false);
+ expect(isValidSnapPoint('50')).toBe(false);
+ expect(isValidSnapPoint('50vh')).toBe(false);
+ expect(isValidSnapPoint('calc(50% - 20px)')).toBe(false);
+ });
});
describe('computeDetentOffsets', () => {
@@ -100,66 +149,84 @@ describe('resolveSettleOffset', () => {
});
});
-describe('isPeekOffset', () => {
- const offsets = [0, 100, 200]; // full, mid, peek
-
- it('is true only for the shortest detent', () => {
- expect(isPeekOffset(200, offsets)).toBe(true);
- expect(isPeekOffset(100, offsets)).toBe(false);
- expect(isPeekOffset(0, offsets)).toBe(false);
+describe('peekOffsetFor', () => {
+ it('is the shortest stop when that stop is a sliver', () => {
+ // sheet 800; stops at 800, 400 and 100 visible px. The 100px stop is an
+ // eighth of the sheet, well inside the quarter that makes a peek.
+ expect(peekOffsetFor([0, 400, 700], 800)).toBe(700);
});
- it('tolerates sub-pixel rounding around the peek', () => {
- expect(isPeekOffset(200.4, offsets)).toBe(true);
- expect(isPeekOffset(199.6, offsets)).toBe(true);
- expect(isPeekOffset(196, offsets)).toBe(false);
+ it('has no peek when the shortest stop is a working height', () => {
+ // A half-height stop lays its content out and keeps a full scrim; it is
+ // the sheet the caller asked for, not a glance at one.
+ expect(peekOffsetFor([0, 400], 800)).toBeNull();
});
it('has no peek when the sheet has no collapsed stop', () => {
- expect(isPeekOffset(200, [0])).toBe(false);
- expect(isPeekOffset(0, [0])).toBe(false);
+ expect(peekOffsetFor([0], 800)).toBeNull();
});
- it('treats the only collapsed stop as the peek', () => {
- expect(isPeekOffset(200, [0, 200])).toBe(true);
+ it('takes the quarter mark itself as a peek', () => {
+ expect(peekOffsetFor([0, 600], 800)).toBe(600);
});
- it('agrees with the detent scrimOpacityForOffset treats as the peek', () => {
- const dismissOffset = 280;
- const peek = offsets[offsets.length - 1];
- expect(isPeekOffset(peek, offsets)).toBe(true);
- expect(scrimOpacityForOffset(peek, offsets, dismissOffset)).toBeCloseTo(
- 0.3,
- );
+ it('has no peek without a measured sheet', () => {
+ expect(peekOffsetFor([0, 600], 0)).toBeNull();
});
});
describe('scrimOpacityForOffset', () => {
- describe('with a peek detent (>= 2 detents)', () => {
+ describe('with a peek detent', () => {
const offsets = [0, 100, 200]; // full, mid, peek
+ const peekOffset = 200;
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);
+ expect(scrimOpacityForOffset(0, offsets, dismissOffset, peekOffset)).toBe(
+ 1,
+ );
+ expect(
+ scrimOpacityForOffset(100, offsets, dismissOffset, peekOffset),
+ ).toBe(1);
+ expect(
+ scrimOpacityForOffset(60, offsets, dismissOffset, peekOffset),
+ ).toBe(1);
});
it('fades linearly from the mid detent toward the peek floor', () => {
// Halfway from mid (100) to peek (200), opacity is halfway from 1 to the
// 0.3 floor => 0.65.
- expect(scrimOpacityForOffset(150, offsets, dismissOffset)).toBeCloseTo(
- 0.65,
- );
+ expect(
+ scrimOpacityForOffset(150, offsets, dismissOffset, peekOffset),
+ ).toBeCloseTo(0.65);
});
it('thins to the peek floor at or below the peek detent (still modal)', () => {
- expect(scrimOpacityForOffset(200, offsets, dismissOffset)).toBeCloseTo(
- 0.3,
- );
- expect(scrimOpacityForOffset(240, offsets, dismissOffset)).toBeCloseTo(
- 0.3,
- );
+ expect(
+ scrimOpacityForOffset(200, offsets, dismissOffset, peekOffset),
+ ).toBeCloseTo(0.3);
+ expect(
+ scrimOpacityForOffset(240, offsets, dismissOffset, peekOffset),
+ ).toBeCloseTo(0.3);
+ });
+ });
+
+ describe('with collapsed stops but no peek among them', () => {
+ // The shortest stop is a working height, so the scrim is full there and
+ // only fades once the sheet is being dragged out below it.
+ const offsets = [0, 100];
+ const dismissOffset = 160;
+
+ it('stays full at every stop, including the shortest', () => {
+ expect(scrimOpacityForOffset(0, offsets, dismissOffset, null)).toBe(1);
+ expect(scrimOpacityForOffset(100, offsets, dismissOffset, null)).toBe(1);
+ });
+
+ it('fades only across the dismiss overshoot below the shortest stop', () => {
+ expect(
+ scrimOpacityForOffset(130, offsets, dismissOffset, null),
+ ).toBeCloseTo(0.5);
+ expect(scrimOpacityForOffset(160, offsets, dismissOffset, null)).toBe(0);
});
});
@@ -168,14 +235,14 @@ describe('scrimOpacityForOffset', () => {
const dismissOffset = 160;
it('stays full until the drag begins collapsing', () => {
- expect(scrimOpacityForOffset(0, offsets, dismissOffset)).toBe(1);
+ expect(scrimOpacityForOffset(0, offsets, dismissOffset, null)).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);
+ expect(
+ scrimOpacityForOffset(80, offsets, dismissOffset, null),
+ ).toBeCloseTo(0.5);
+ expect(scrimOpacityForOffset(160, offsets, dismissOffset, null)).toBe(0);
});
});
});
diff --git a/packages/core/src/BottomSheet/snapOffsets.ts b/packages/core/src/BottomSheet/snapOffsets.ts
index deccbbdffc..7e6d1a776a 100644
--- a/packages/core/src/BottomSheet/snapOffsets.ts
+++ b/packages/core/src/BottomSheet/snapOffsets.ts
@@ -3,9 +3,9 @@
/**
* @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.
+ * @output Resolves snap points and converts them to translateY offsets.
+ * @position Internal to BottomSheet; consumed by useSheetGestures and
+ * BottomSheetPanel, tested by snapOffsets.test.ts.
*
* A detent is represented as an offset in px from the fully-open position
* (0 = fully open, larger = more collapsed). The panel may render that offset
@@ -14,6 +14,21 @@
* geometry can be unit-tested without a DOM.
*/
+/**
+ * A height the sheet can rest at, expressed as the sheet's VISIBLE height:
+ *
+ * - a number in `(0, 1]` — a fraction of the viewport (`0.5` is half the
+ * screen), so the stop tracks rotation and window resizes;
+ * - a `'<n>%'` string — the same thing spelled in CSS;
+ * - a `'<n>px'` string — an absolute height that does not scale.
+ *
+ * Anything else — a unitless string, `calc()`, `vh`, `rem`, a number outside
+ * `(0, 1]` — is ignored with a dev warning. Percentages resolve against the
+ * layout viewport (`window.innerHeight`), the same box the height budgets are
+ * written against, so the mobile keyboard never moves a stop.
+ */
+export type BottomSheetSnapPoint = number | string;
+
/**
* 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
@@ -22,12 +37,71 @@
*/
export const DETENT_DEDUP_PX = 48;
-/** Resolve snap points given as viewport fractions (0, 1] to px heights. */
-export function snapFractionsToHeights(
- fractions: ReadonlyArray<number>,
+/**
+ * Largest share of the fully open sheet the shortest stop may fill and still
+ * be a peek. Above it the stop is a working surface — it lays its content out
+ * and keeps a full scrim — so a two-stop sheet like `[0.5]` behaves like the
+ * half-height panel it asks for rather than like a glance.
+ */
+export const PEEK_MAX_HEIGHT_RATIO = 0.25;
+
+// A snap point string: a positive number with a `px` or `%` unit. Deliberately
+// narrow — every accepted unit has to be resolvable by arithmetic on the
+// viewport height, because this runs inside the drag loop. Units that need the
+// DOM to resolve (`rem`, `em`, `calc()`) would cost a layout per frame.
+const SNAP_POINT_PATTERN = /^(\d+(?:\.\d+)?|\.\d+)(px|%)$/i;
+
+/**
+ * Resolve one snap point to a visible height in px, or `null` when it is not a
+ * snap point this sheet can honor.
+ */
+function parseSnapPoint(
+ point: BottomSheetSnapPoint,
+ viewportPx: number,
+): number | null {
+ if (typeof point === 'number') {
+ // A bare number is a viewport fraction. Anything above 1 is a px value in
+ // disguise; the caller warns rather than guessing which was meant.
+ return Number.isFinite(point) && point > 0 && point <= 1
+ ? point * viewportPx
+ : null;
+ }
+ const match = SNAP_POINT_PATTERN.exec(point.trim());
+ if (match === null) {
+ return null;
+ }
+ const value = Number.parseFloat(match[1]);
+ if (!(value > 0)) {
+ return null;
+ }
+ return match[2].toLowerCase() === '%' ? (value / 100) * viewportPx : value;
+}
+
+/**
+ * Whether a snap point can be resolved at all. The viewport only scales the
+ * result, so validity is independent of it.
+ */
+export function isValidSnapPoint(point: BottomSheetSnapPoint): boolean {
+ return parseSnapPoint(point, 1) !== null;
+}
+
+/**
+ * Resolve snap points to candidate visible heights in px, dropping the ones
+ * this sheet cannot honor. Callers warn about those separately — this stays
+ * silent because it runs on every drag frame.
+ */
+export function resolveSnapPoints(
+ points: ReadonlyArray<BottomSheetSnapPoint>,
viewportPx: number,
): number[] {
- return fractions.filter(f => f > 0 && f <= 1).map(f => f * viewportPx);
+ const heights: number[] = [];
+ for (const point of points) {
+ const height = parseSnapPoint(point, viewportPx);
+ if (height !== null) {
+ heights.push(height);
+ }
+ }
+ return heights;
}
/**
@@ -81,46 +155,58 @@ export function nearestOffset(
export const MIN_PEEK_SCRIM_OPACITY = 0.3;
/**
- * Whether `offset` is the peek detent: the shortest stop, where the sheet is a
- * glance rather than a working surface. A sheet with no collapsed stop at all
- * has no peek — the same rule `scrimOpacityForOffset` thins the scrim by.
+ * The peek detent's offset, or `null` when this sheet has no peek.
+ *
+ * A peek is the shortest stop AND a sliver — at most `PEEK_MAX_HEIGHT_RATIO`
+ * of the fully open sheet. It is the one detent the sheet does NOT express as
+ * layout height: at a sliver there is nothing useful to lay out, and reflowing
+ * the content into it (then back out on the way up) is churn the user sees, so
+ * it keeps the full layout height and slides below the viewport instead. It is
+ * also the only stop that thins the scrim.
*
- * The peek is the one detent the sheet does NOT express as layout height: at a
- * sliver of viewport there is nothing useful to lay out, and reflowing the
- * content into it (then back out on the way up) is churn the user sees. It
- * keeps the full layout height and slides below the viewport instead.
+ * A sheet whose shortest stop is a working height — `[0.5]`, say — has no
+ * peek: half a screen of content deserves to be laid out at half a screen, and
+ * a scrim that thinned there would read as a dismissed sheet.
*/
-export function isPeekOffset(
- offset: number,
+export function peekOffsetFor(
offsets: ReadonlyArray<number>,
- tolerancePx: number = 0.5,
-): boolean {
- if (offsets.length < 2) {
- return false;
+ visibleSheetHeight: number,
+): number | null {
+ if (offsets.length < 2 || visibleSheetHeight <= 0) {
+ return null;
}
- return Math.abs(offset - offsets[offsets.length - 1]) <= tolerancePx;
+ const shortest = offsets[offsets.length - 1];
+ const heightAtShortest = visibleSheetHeight - shortest;
+ return heightAtShortest <= PEEK_MAX_HEIGHT_RATIO * visibleSheetHeight
+ ? shortest
+ : null;
}
/**
* Scrim opacity (1 = fully visible) for a drag/settle `offset`.
- * The scrim stays full while the sheet is at or above its second-shortest
- * detent, then fades as it collapses onto the shortest ("peek") detent — a
- * glance state that thins the backdrop to `MIN_PEEK_SCRIM_OPACITY` (not fully
- * gone, since the sheet is still modal) and holds there below it.
- * A single-detent sheet has no peek, so it instead fades all the way to 0
- * across the dismiss overshoot toward `dismissOffset` (the sheet is leaving).
+ *
+ * The scrim is full down to the shortest stop that is still a working surface,
+ * and only thins past it — onto a peek, where it holds at
+ * `MIN_PEEK_SCRIM_OPACITY` (a glance state, and the sheet is still modal), or
+ * out through the dismiss overshoot toward `dismissOffset`, where it clears
+ * completely because the sheet is leaving.
+ *
+ * So a sheet whose stops are all working heights keeps a full scrim at every
+ * one of them; only the sliver of a peek, or a sheet on its way out, dims less.
*/
export function scrimOpacityForOffset(
offset: number,
offsets: ReadonlyArray<number>,
dismissOffset: number,
+ peekOffset: number | null,
): number {
- const shortest = offsets[offsets.length - 1];
- const hasPeek = offsets.length >= 2;
- const fadeStart = hasPeek ? offsets[offsets.length - 2] : 0;
- const fadeEnd = hasPeek ? shortest : dismissOffset;
- // Peek is a resting state on a still-modal sheet, so keep a floor; the
- // dismiss overshoot is a sheet on its way out, so let it clear completely.
+ const hasPeek = peekOffset !== null;
+ // The last stop that is still a working surface — the peek's neighbor when
+ // there is a peek, otherwise the shortest stop itself.
+ const fadeStart = hasPeek
+ ? offsets[offsets.length - 2]
+ : offsets[offsets.length - 1];
+ const fadeEnd = hasPeek ? peekOffset : dismissOffset;
const floor = hasPeek ? MIN_PEEK_SCRIM_OPACITY : 0;
if (offset <= fadeStart) {
return 1;
diff --git a/packages/core/src/BottomSheet/useSheetGestures.test.ts b/packages/core/src/BottomSheet/useSheetGestures.test.ts
index 65c9b47661..0d500b6bb5 100644
--- a/packages/core/src/BottomSheet/useSheetGestures.test.ts
+++ b/packages/core/src/BottomSheet/useSheetGestures.test.ts
@@ -129,7 +129,9 @@ describe('useSheetGestures', () => {
expect(onDismiss).not.toHaveBeenCalled();
expect(hook.result.current.settledOffset).toBe(200);
expect(onSnap).toHaveBeenLastCalledWith(200);
- expect(onScrimOpacity).toHaveBeenLastCalledWith(0.3);
+ // The 200px stop is half the sheet — a working surface, not a peek — so
+ // the backdrop stays full there.
+ expect(onScrimOpacity).toHaveBeenLastCalledWith(1);
});
it('expands to the tallest detent on a fast upward flick', () => {
@@ -218,13 +220,62 @@ describe('useSheetGestures', () => {
expect(hook.result.current.settledLayoutOffset).toBe(0);
});
- it('treats the only collapsed stop as a peek, like the scrim does', () => {
+ it('re-anchors to the same stop when the snap heights change at rest', () => {
+ const onDismiss = vi.fn();
+ const hook = renderHook(
+ (props: UseSheetGesturesOptions) => useSheetGestures(props),
+ {
+ initialProps: {
+ isOpen: true,
+ onDismiss,
+ snapHeights: () => [200],
+ },
+ },
+ );
+ const t = makeTarget();
+
+ // Settle on the one collapsed stop: 400 - 200 = 200px of travel.
+ down(hook, 0, 0, t);
+ move(hook, 180, 700, t);
+ up(hook, 180, 1100, t);
+ act(() => hook.result.current.completeScrollAreaSettle());
+ expect(hook.result.current.settledOffset).toBe(200);
+
+ // A new resolver is a new set of stops. The sheet is resting on the one it
+ // names, so it follows: a 150px stop is 250px of travel. The resolver is
+ // read during render, not from a passive effect — the re-anchor runs in a
+ // layout effect, which would otherwise still see the previous one.
+ hook.rerender({
+ isOpen: true,
+ onDismiss,
+ snapHeights: () => [150],
+ });
+
+ expect(hook.result.current.settledOffset).toBe(250);
+ expect(hook.result.current.settledLayoutOffset).toBe(250);
+ });
+
+ it('resizes the scrolling area at a collapsed stop that is a working height', () => {
+ // A 200px stop on the 400px sheet is half of it: the scrolling area takes
+ // that travel as layout height rather than sliding the sheet away.
const {hook} = setup({snapHeights: () => [200]});
const t = makeTarget();
down(hook, 0, 0, t);
move(hook, 180, 700, t);
up(hook, 180, 1100, t);
expect(hook.result.current.settledOffset).toBe(200);
+ expect(hook.result.current.settledLayoutOffset).toBe(200);
+ });
+
+ it('treats the only collapsed stop as a peek when it is a sliver', () => {
+ // 60px of a 400px sheet is inside the quarter that makes a peek, so the
+ // sheet keeps its full layout height and slides below the viewport.
+ const {hook} = setup({snapHeights: () => [60]});
+ const t = makeTarget();
+ down(hook, 0, 0, t);
+ move(hook, 320, 700, t);
+ up(hook, 320, 1100, t);
+ expect(hook.result.current.settledOffset).toBe(340);
expect(hook.result.current.settledLayoutOffset).toBe(0);
});
@@ -297,20 +348,22 @@ describe('useSheetGestures', () => {
expect(onDismiss).not.toHaveBeenCalled();
expect(hook.result.current.settledOffset).toBe(200);
- expect(onScrimOpacity).toHaveBeenLastCalledWith(0.3);
+ // Rebounding restores the scrim the 200px stop rests under — full, since
+ // half a sheet is a working surface rather than a glance.
+ expect(onScrimOpacity).toHaveBeenLastCalledWith(1);
});
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
- // spans the mid detent (offset 100) to the peek detent (offset 200):
- // full at/above 100, thinned to the peek floor (0.3) at/below 200.
- const {hook} = setup({snapHeights: () => [200, 300], onScrimOpacity});
+ // Sheet 400, stops at 300 and a 60px sliver -> offsets [0, 100, 340]. The
+ // fade spans the mid detent (offset 100) to the peek (offset 340): full
+ // at/above 100, thinned to the peek floor (0.3) at/below 340.
+ const {hook} = setup({snapHeights: () => [60, 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 -> between 1 and 0.3 (~0.65)
- move(hook, 220, 1000, t); // offset 220, past the peek -> peek floor
+ move(hook, 220, 600, t); // offset 220, halfway -> between 1 and 0.3 (~0.65)
+ move(hook, 360, 1000, t); // offset 360, past the peek -> peek floor
const values = onScrimOpacity.mock.calls.map(c => Number(c[0]));
expect(values[0]).toBe(1);
expect(values[1]).toBeGreaterThan(0.55);
@@ -320,14 +373,14 @@ describe('useSheetGestures', () => {
it('thins the scrim to the peek floor when settled at the peek detent (still modal)', () => {
const onScrimOpacity = vi.fn();
- const {hook} = setup({snapHeights: () => [200, 300], onScrimOpacity});
+ const {hook} = setup({snapHeights: () => [60, 300], onScrimOpacity});
const t = makeTarget();
- // Slow drag down to the peek detent (offset 200).
+ // Slow drag down to the peek detent (offset 340).
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);
+ move(hook, 170, 400, t);
+ move(hook, 340, 900, t);
+ up(hook, 340, 1400, t);
+ expect(hook.result.current.settledOffset).toBe(340);
// Last reported opacity (on settle) is the peek floor, not fully hidden —
// the sheet is still modal, so the backdrop keeps a minimum dim.
const values = onScrimOpacity.mock.calls.map(c => Number(c[0]));
diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.ts
index afbda1169e..6eab9f3f8a 100644
--- a/packages/core/src/BottomSheet/useSheetGestures.ts
+++ b/packages/core/src/BottomSheet/useSheetGestures.ts
@@ -19,14 +19,16 @@
* the part the scrolling area gives up as layout height, and the remainder is
* a transform. Gestures and snaps only ever move the transform, so they stay
* on the compositor; layout height changes at rest, in one transition-free
- * render whose visible geometry is identical. The peek detent keeps the full
- * height and slides below the viewport instead of reflowing to a sliver.
+ * render whose visible geometry is identical. A peek detent — a stop that is
+ * only a sliver of the sheet — keeps the full height and slides below the
+ * viewport instead of reflowing to that sliver.
*
- * Those are pixels, and the detents behind them are viewport fractions, so a
- * sheet at rest re-resolves its detent on `resize` / `orientationchange` and
- * re-anchors to the new geometry without animating. The detent it returns to
- * is tracked by index: the pixels stop meaning the same thing when the
- * viewport changes, the stop the user chose does not.
+ * Those are pixels, and the stops behind them are relative to the viewport, so
+ * a sheet at rest re-resolves its detent on `resize` / `orientationchange`,
+ * and whenever the host swaps the snap points, and re-anchors to the new
+ * geometry without animating. The detent it returns to is tracked by index:
+ * the pixels stop meaning the same thing when the viewport changes, the stop
+ * the user chose does not.
*
* On touch, the scrolling body hands the gesture to the sheet at a scroll
* edge. Two shapes, because the browser only offers one of them a choice: a
@@ -66,11 +68,20 @@ import {
import {useMediaQuery} from '../hooks';
import {
computeDetentOffsets,
- isPeekOffset,
+ peekOffsetFor,
resolveSettleOffset,
scrimOpacityForOffset,
} from './snapOffsets';
+/**
+ * The stops a sheet of a given height rests at: offsets from fully-open in px,
+ * ascending, plus which of them (if any) is the peek.
+ */
+interface SheetDetents {
+ offsets: number[];
+ peekOffset: number | null;
+}
+
// 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.
@@ -205,6 +216,9 @@ export interface UseSheetGesturesOptions {
* (rotation, a resized desktop window, collapsing browser chrome). The fully
* open height is always the tallest detent. Omit for a single-height sheet
* (a drag then only dismisses or springs back).
+ *
+ * Keep the identity stable: a new function is read as new stops, and
+ * re-anchors a resting sheet to them.
*/
snapHeights?: () => number[];
/** Notified when the settled visible detent height (px) changes. */
@@ -292,7 +306,7 @@ export interface UseSheetGesturesResult {
/**
* How much of `settledOffset` is expressed as layout height rather than as a
* transform. Equals `settledOffset` at the resizing detents; 0 at fully open
- * and at the peek, which keep the sheet's full height (see isPeekOffset).
+ * and at the peek, which keep the sheet's full height (see peekOffsetFor).
*/
settledLayoutOffset: number;
}
@@ -339,7 +353,7 @@ export function useSheetGestures({
const [scrollPreservationInset, setScrollPreservationInset] = useState(0);
// How much of the settled travel is expressed as layout height. Equal to
// settledOffset for the resizing detents, and 0 at fully open and at the
- // peek (see isPeekOffset), which keep the full height and use a transform.
+ // peek (see peekOffsetFor), which keep the full height and use a transform.
const [settledLayoutOffset, setSettledLayoutOffset] = useState(0);
const settledLayoutOffsetRef = useRef(0);
// WHICH detent the sheet rests on, as an index into the resolved list. The
@@ -432,17 +446,22 @@ export function useSheetGestures({
const isOpenRef = useRef(isOpen);
isOpenRef.current = isOpen;
+ // The resolver is refreshed during render, not with the callbacks below: the
+ // layout effect that re-anchors on a change to it runs BEFORE passive
+ // effects, so a resolver parked in one would still be the previous set of
+ // stops by the time the re-anchor read it.
+ const snapHeightsRef = useRef(snapHeights);
+ snapHeightsRef.current = snapHeights;
+
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;
});
// Live drag bookkeeping (refs so pointermove doesn't churn renders).
@@ -562,20 +581,22 @@ export function useSheetGestures({
return sheetElRef.current?.getBoundingClientRect().height ?? 0;
}, []);
- // Detent translate offsets (px) from the tallest detent, ascending. Exclude
- // the border-box portion reserved below the viewport before comparing the
- // candidate visible heights; otherwise every snap point lands that many px
- // too low. Snap heights are resolved lazily so they track the viewport.
- const detentOffsets = useCallback((height: number): number[] => {
+ // Detent translate offsets (px) from the tallest detent, ascending, plus the
+ // peek among them. Exclude the border-box portion reserved below the
+ // viewport before comparing the candidate visible heights; otherwise every
+ // snap point lands that many px too low. Snap heights are resolved lazily so
+ // they track the viewport.
+ const resolveDetents = useCallback((height: number): SheetDetents => {
const visibleSheetHeight = visibleHeightForOffset(
height,
0,
offscreenBlockEndInsetRef.current,
);
- return computeDetentOffsets(
+ const offsets = computeDetentOffsets(
visibleSheetHeight,
snapHeightsRef.current?.() ?? [],
);
+ return {offsets, peekOffset: peekOffsetFor(offsets, visibleSheetHeight)};
}, []);
// The height the sheet WOULD have fully open, right now. While it rests at a
@@ -609,87 +630,105 @@ export function useSheetGestures({
//
// Re-resolve the SAME detent — by index, the one thing that survives the
// units changing — against the new geometry, and re-anchor without
- // animating: the viewport moved, not the user's finger, so there is no
+ // animating: the geometry moved, not the user's finger, so there is no
// gesture to continue and nothing to ease.
- useEffect(() => {
- if (!isOpen || typeof window === 'undefined') {
+ const reanchorToSettledDetent = useCallback(() => {
+ // A closed sheet re-anchors on its way back open; a live drag re-measures
+ // on its own, and a settle in flight owns the layout until it lands.
+ if (
+ !isOpenRef.current ||
+ dragStateRef.current != null ||
+ settlingLayoutOffsetRef.current != null
+ ) {
+ return;
+ }
+ const height = measureFullyOpenHeight();
+ if (height <= 0) {
+ return;
+ }
+ const {offsets, peekOffset} = resolveDetents(height);
+ const index = Math.min(settledDetentIndexRef.current, offsets.length - 1);
+ const target = offsets[index];
+ const targetLayoutOffset = target === peekOffset ? 0 : target;
+ const baseLayoutOffset = settledLayoutOffsetRef.current;
+ if (
+ height === sheetHeightRef.current &&
+ Math.abs(target - activeOffsetRef.current) <= 0.5 &&
+ Math.abs(targetLayoutOffset - baseLayoutOffset) <= 0.5
+ ) {
return;
}
- const handleViewportChange = () => {
- // A live drag re-measures on its own, and a settle in flight owns the
- // layout until it lands.
- if (
- dragStateRef.current != null ||
- settlingLayoutOffsetRef.current != null
- ) {
- return;
- }
- const height = measureFullyOpenHeight();
- if (height <= 0) {
- return;
- }
- const offsets = detentOffsets(height);
- const index = Math.min(settledDetentIndexRef.current, offsets.length - 1);
- const target = offsets[index];
- const targetLayoutOffset = isPeekOffset(target, offsets) ? 0 : target;
- const baseLayoutOffset = settledLayoutOffsetRef.current;
- if (
- height === sheetHeightRef.current &&
- Math.abs(target - activeOffsetRef.current) <= 0.5 &&
- Math.abs(targetLayoutOffset - baseLayoutOffset) <= 0.5
- ) {
- return;
- }
- sheetHeightRef.current = height;
- setSheetHeight(height);
- settledDetentIndexRef.current = index;
- prepareScrollAreaSettle(
- baseLayoutOffset,
- target,
- targetLayoutOffset,
+ sheetHeightRef.current = height;
+ // Re-anchoring is a measurement: the geometry it reads is only knowable
+ // after layout, so the state it corrects can only be set from an effect
+ // (or, on the resize path, from the listener). Both writes below are
+ // guarded by the equality check above, so a re-anchor that finds nothing
+ // to change sets nothing.
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- corrects settled geometry from a measurement
+ setSheetHeight(height);
+ settledDetentIndexRef.current = index;
+ prepareScrollAreaSettle(
+ baseLayoutOffset,
+ target,
+ targetLayoutOffset,
+ target,
+ baseLayoutOffset,
+ naturalEndGapFor(bodyNodeRef.current),
+ false,
+ );
+ recordSettledLayoutOffset(targetLayoutOffset);
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- corrects settled geometry from a measurement
+ setSettledOffset(target);
+ onSnapRef.current?.(
+ visibleHeightForOffset(height, target, offscreenBlockEndInsetRef.current),
+ );
+ const maxOffset = offsets[offsets.length - 1];
+ const shortestDetentHeight = visibleHeightForOffset(
+ height,
+ maxOffset,
+ offscreenBlockEndInsetRef.current,
+ );
+ onScrimOpacityRef.current?.(
+ scrimOpacityForOffset(
target,
- baseLayoutOffset,
- naturalEndGapFor(bodyNodeRef.current),
- false,
- );
- recordSettledLayoutOffset(targetLayoutOffset);
- setSettledOffset(target);
- onSnapRef.current?.(
- visibleHeightForOffset(
- height,
- target,
- offscreenBlockEndInsetRef.current,
- ),
- );
- const maxOffset = offsets[offsets.length - 1];
- const shortestDetentHeight = visibleHeightForOffset(
- height,
- maxOffset,
- offscreenBlockEndInsetRef.current,
- );
- onScrimOpacityRef.current?.(
- scrimOpacityForOffset(
- target,
- offsets,
- maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO,
- ),
- );
- };
- window.addEventListener('resize', handleViewportChange);
- window.addEventListener('orientationchange', handleViewportChange);
- return () => {
- window.removeEventListener('resize', handleViewportChange);
- window.removeEventListener('orientationchange', handleViewportChange);
- };
+ offsets,
+ maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO,
+ peekOffset,
+ ),
+ );
}, [
- detentOffsets,
- isOpen,
measureFullyOpenHeight,
prepareScrollAreaSettle,
recordSettledLayoutOffset,
+ resolveDetents,
]);
+ useEffect(() => {
+ if (!isOpen || typeof window === 'undefined') {
+ return;
+ }
+ window.addEventListener('resize', reanchorToSettledDetent);
+ window.addEventListener('orientationchange', reanchorToSettledDetent);
+ return () => {
+ window.removeEventListener('resize', reanchorToSettledDetent);
+ window.removeEventListener('orientationchange', reanchorToSettledDetent);
+ };
+ }, [isOpen, reanchorToSettledDetent]);
+
+ // The other input to the same geometry: the snap points themselves. A host
+ // that swaps them while the sheet rests has moved the stops out from under
+ // it, exactly as a rotation does, so re-anchor the same way. Skipped on the
+ // first run — the sheet is already anchored to the detents it opened with.
+ const hasAnchoredSnapHeightsRef = useRef(false);
+ useLayoutEffect(() => {
+ if (!hasAnchoredSnapHeightsRef.current) {
+ hasAnchoredSnapHeightsRef.current = true;
+ return;
+ }
+ reanchorToSettledDetent();
+ }, [reanchorToSettledDetent, snapHeights]);
+
const cancelDrag = useCallback(
(target?: HTMLElement) => {
const state = dragStateRef.current;
@@ -718,7 +757,7 @@ export function useSheetGestures({
// An interrupted drag returns to its previous resting detent. Restore
// the matching scrim opacity as well so the modal shell cannot remain
// dimmed with its sheet translated out of view.
- const offsets = detentOffsets(state.height);
+ const {offsets, peekOffset} = resolveDetents(state.height);
const maxOffset = offsets[offsets.length - 1];
const shortestDetentHeight = visibleHeightForOffset(
state.height,
@@ -728,10 +767,15 @@ export function useSheetGestures({
const dismissOffset =
maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
onScrimOpacityRef.current?.(
- scrimOpacityForOffset(state.baseOffset, offsets, dismissOffset),
+ scrimOpacityForOffset(
+ state.baseOffset,
+ offsets,
+ dismissOffset,
+ peekOffset,
+ ),
);
},
- [detentOffsets, prepareScrollAreaSettle],
+ [prepareScrollAreaSettle, resolveDetents],
);
useEffect(() => {
@@ -762,7 +806,7 @@ export function useSheetGestures({
layoutOffset: number,
naturalEndGap: number,
) => {
- const offsets = detentOffsets(height);
+ const {offsets, peekOffset} = resolveDetents(height);
const maxOffset = offsets[offsets.length - 1];
const shortestDetentHeight = visibleHeightForOffset(
height,
@@ -774,7 +818,7 @@ export function useSheetGestures({
const settleAt = (target: number) => {
// A peek keeps the full layout height and slides below the viewport;
// every taller detent resizes the scrolling area to what it shows.
- const targetLayoutOffset = isPeekOffset(target, offsets) ? 0 : target;
+ const targetLayoutOffset = target === peekOffset ? 0 : target;
prepareScrollAreaSettle(
baseLayoutOffset,
target,
@@ -797,7 +841,7 @@ export function useSheetGestures({
const dismissOffset =
maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
onScrimOpacityRef.current?.(
- scrimOpacityForOffset(target, offsets, dismissOffset),
+ scrimOpacityForOffset(target, offsets, dismissOffset, peekOffset),
);
if (target !== baseOffset) {
hapticTick();
@@ -866,7 +910,7 @@ export function useSheetGestures({
const target = resolveSettleOffset(offset, offsets, dir, baseOffset);
settleAt(target);
},
- [detentOffsets, prepareScrollAreaSettle, recordSettledLayoutOffset],
+ [prepareScrollAreaSettle, recordSettledLayoutOffset, resolveDetents],
);
const beginDrag = useCallback(
@@ -975,7 +1019,7 @@ export function useSheetGestures({
state.lastCoord = event.clientY;
state.lastTime = event.timeStamp;
}
- const offsets = detentOffsets(state.height);
+ const {offsets, peekOffset} = resolveDetents(state.height);
const raw = state.baseOffset + delta;
const maxDetentOffset = offsets[offsets.length - 1];
@@ -1017,10 +1061,10 @@ export function useSheetGestures({
const dismissOffset =
floorOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
onScrimOpacityRef.current?.(
- scrimOpacityForOffset(next, offsets, dismissOffset),
+ scrimOpacityForOffset(next, offsets, dismissOffset, peekOffset),
);
},
- [detentOffsets, updateScrollPreservationInset],
+ [resolveDetents, updateScrollPreservationInset],
);
const endDrag = useCallback(