An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): size the Bottom Sheet scroll area to the visible sheet (#5130)
Xinzi Zhou8e3d1b5606fe
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsxindex 64bbd41949..850b544d92 100644--- a/apps/storybook/stories/BottomSheet.stories.tsx+++ b/apps/storybook/stories/BottomSheet.stories.tsx@@ -338,7 +338,10 @@ export const HugHeightWithLongContent: Story = {<Heading level={3}>Release notes</Heading><Text type="supporting" color="secondary">The sheet hugs its content until it reaches 92% of the viewport,- then the content scrolls within the sheet.+ then the content scrolls within the sheet. Drag it to a snap+ point and the scrolling area resizes to the height you can+ actually see — except at the shortest peek, which slides below+ the viewport at full height rather than reflowing to a sliver.</Text><Divider />{Array.from({length: 12}, (_, i) => (diff --git a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs b/packages/lab/src/BottomSheet/BottomSheet.doc.mjsindex 6bf555f67c..3ee85e797f 100644--- a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs@@ -167,6 +167,17 @@ export const docs = {label="Share"height="hug"><ShareActions />+</BottomSheet>`,+ },+ {+ label: 'Long scrolling content',+ code: `const [isOpen, setIsOpen] = useState(false);+<BottomSheet+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ label="Release notes"+ height="hug">+ <ReleaseNotes /></BottomSheet>`,},{@@ -225,7 +236,7 @@ export const docs = {/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsDense = {description:- 'mobile touch sheet rising from the bottom edge (native <dialog>): grab handle, drag-to-resize snap points, Dialog-aligned dismissal purpose (info/form/required), fully-expanded Tall visual-viewport mobile-keyboard handling, named height scale, modal (default) or non-modal (hasScrim={false}) presentation',+ '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',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/lab/src/BottomSheet/BottomSheet.test.tsx b/packages/lab/src/BottomSheet/BottomSheet.test.tsxindex 44e3b382ff..5b501c7529 100644--- a/packages/lab/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/lab/src/BottomSheet/BottomSheet.test.tsx@@ -99,6 +99,16 @@ function rect({top, bottom}: {top: number; bottom: number}): DOMRect {};}+function resizeEntry(+ borderBoxHeight: number,+ contentBoxHeight = borderBoxHeight,+): ResizeObserverEntry {+ return {+ borderBoxSize: [{blockSize: borderBoxHeight, inlineSize: 100}],+ contentRect: rect({top: 0, bottom: contentBoxHeight}),+ } as ResizeObserverEntry;+}+function mockVisualViewport(height: number, offsetTop = 0) {const viewport = Object.assign(new EventTarget(), {height,@@ -601,6 +611,320 @@ describe('BottomSheet', () => {unmount();}});++ it('keeps the full layout height at the peek detent', () => {+ const observers = mockResizeObserverInstances();+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Release notes"+ 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,+ );+ });++ // Settle on the shortest 112px peek: offset 736 - 112 = 624.+ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 600});+ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 600});+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});++ // A glance state does not reflow the content into a sliver: the sheet+ // keeps its full layout height and slides below the viewport instead.+ expect(sheet.style.height).toBe('');+ expect(sheet.style.transform).toBe('translateY(624px)');+ expect(getBody().style.paddingBlockEnd).toBe('');++ // Dragging back up off the peek stays transform-only for the same+ // reason — there is no shortened layout to restore first.+ fireTimedPointer(getHandle(), 'pointerdown', {time: 3000, y: 600});+ fireTimedPointer(getHandle(), 'pointermove', {time: 4000, y: 400});+ expect(sheet.style.transform).toBe('translateY(424px)');+ expect(sheet.style.height).toBe('784px');+ expect(getBody().style.paddingBlockEnd).toBe('');++ // Releasing at the taller p50 detent resizes the scrolling area.+ fireTimedPointer(getHandle(), 'pointerup', {time: 5000, y: 400});+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});+ expect(sheet.style.height).toBe('448px');+ expect(sheet.style.transform).toBe('');+ });++ it('swaps height for transform without a transition when released on a detent', () => {+ const observers = mockResizeObserverInstances();+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Release notes"+ 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,+ );+ });++ // magnetize() lands a slow drag exactly on the p50 detent (offset 336),+ // so the release has no travel left to animate and reconciles at once.+ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 336});+ expect(sheet.style.transform).toBe('translateY(336px)');+ expect(sheet.style.height).toBe('784px');++ // Hold the reconciliation frame so the intermediate render is visible+ // to the assertions below.+ const reconciliationFrames: FrameRequestCallback[] = [];+ vi.mocked(requestAnimationFrame).mockImplementation(callback => {+ reconciliationFrames.push(callback);+ return reconciliationFrames.length;+ });+ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 336});++ // Height and transform swap roles in this one render. That is only+ // invisible with transitions off; live, the composited transform would+ // animate the whole 336px swap while the height jumped, and the sheet+ // would lurch away from the detent before coming back to it.+ expect(sheet.style.height).toBe('448px');+ expect(sheet.style.transform).toBe('');+ expect(sheet.style.transition).toBe('none');++ // Transitions come back for the next gesture.+ act(() => reconciliationFrames.splice(0).forEach(frame => frame(0)));+ expect(sheet.style.transition).toBe('');+ });++ it('uses transforms while dragging and resizes to the visible snapped height', () => {+ const observers = mockResizeObserverInstances();+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Release notes"+ height="tall">+ Content+ </BottomSheet>,+ );+ const sheet = getSheet();+ const sheetObserver = observers.find(instance =>+ instance.observed.has(sheet),+ );+ act(() => {+ sheetObserver?.callback(+ // A Tall sheet has 736px visible height in this 800px viewport plus+ // the 48px border-box reserve held below the viewport.+ [resizeEntry(784, 736)],+ sheetObserver as unknown as ResizeObserver,+ );+ });++ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 240});++ expect(sheet.style.transform).toBe('translateY(240px)');+ expect(sheet.style.height).toBe('784px');+ expect(sheet.style.transition).toBe('none');++ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 240});+ // Release remains transform-only until the snap finishes.+ // p50 is a visible 400px sheet: 784 - 48 - 400 = 336px offset.+ expect(sheet.style.transform).toBe('translateY(336px)');+ expect(sheet.style.height).toBe('784px');+ expect(sheet.style.transition).toBe('');+ const reconciliationFrames: FrameRequestCallback[] = [];+ vi.mocked(requestAnimationFrame).mockImplementation(callback => {+ reconciliationFrames.push(callback);+ return reconciliationFrames.length;+ });+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});+ expect(sheet.style.transform).toBe('');+ expect(sheet.style.height).toBe('448px');+ // The transform reset is transition-free so it cannot produce a second+ // fly-in animation after the snap has already reached its destination.+ expect(sheet.style.transition).toBe('none');+ expect(reconciliationFrames.length).toBeGreaterThan(0);+ act(() => reconciliationFrames.splice(0).forEach(frame => frame(0)));+ expect(sheet.style.transition).toBe('');++ // Ignore ResizeObserver frames from the height reconciliation. The+ // next drag must still use the original 784px border-box height.+ act(() => {+ sheetObserver?.callback(+ [resizeEntry(500, 452)],+ sheetObserver as unknown as ResizeObserver,+ );+ });+ fireTimedPointer(getHandle(), 'pointerdown', {time: 3000, y: 240});+ fireTimedPointer(getHandle(), 'pointermove', {time: 4000, y: 140});+ expect(sheet.style.transform).toBe('translateY(236px)');+ expect(sheet.style.height).toBe('784px');+ expect(getBody().style.paddingBlockEnd).toBe('336px');++ // Reversing below the settled point restores the settled height and+ // translates only the distance traveled from that detent. The temporary+ // scroll-preservation inset leaves with the temporary expanded layout.+ fireTimedPointer(getHandle(), 'pointermove', {time: 5000, y: 340});+ expect(sheet.style.transform).toBe('translateY(100px)');+ expect(sheet.style.height).toBe('448px');+ expect(getBody().style.paddingBlockEnd).toBe('');+ });++ it('reconciles the snapped height immediately when transitions are disabled', () => {+ const observers = mockResizeObserverInstances();+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Release notes"+ height="tall"+ style={{transition: 'none'}}>+ 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,+ );+ });++ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 240});+ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 240});++ expect(sheet.style.transform).toBe('');+ expect(sheet.style.height).toBe('448px');+ });++ it('restores the maximum height before an upward drag and reconciles at snap', () => {+ const observers = mockResizeObserverInstances();+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Release notes"+ 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,+ );+ });++ // Start at the middle 400px detent.+ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 240});+ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 240});+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});+ expect(sheet.style.height).toBe('448px');++ // The upward gesture renders the full 784px surface below the viewport+ // and translates it to preserve the visible top edge.+ fireTimedPointer(getHandle(), 'pointerdown', {time: 3000, y: 240});+ fireTimedPointer(getHandle(), 'pointermove', {time: 4000, y: 0});+ expect(sheet.style.transform).toBe('translateY(96px)');+ expect(sheet.style.height).toBe('784px');+ expect(getBody().style.paddingBlockEnd).toBe('336px');++ // Release first animates only the transform, keeping the source layout+ // and scroll range fixed for the entire snap.+ fireTimedPointer(getHandle(), 'pointerup', {time: 5000, y: 0});+ expect(sheet.style.transform).toBe('');+ expect(sheet.style.height).toBe('784px');+ expect(getBody().style.paddingBlockEnd).toBe('336px');++ // At transition end, height and preservation spacing reconcile in one+ // render with the same visible geometry.+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});+ expect(sheet.style.transform).toBe('');+ expect(sheet.style.height).toBe('');+ expect(getBody().style.paddingBlockEnd).toBe('336px');++ // Once ordinary scrolling brings the content back within its natural+ // range, the retained end padding is no longer needed and is discarded.+ const body = getBody();+ Object.defineProperties(body, {+ clientHeight: {configurable: true, value: 600},+ scrollHeight: {configurable: true, value: 1000},+ scrollTop: {configurable: true, value: 64, writable: true},+ });+ fireEvent.scroll(body);+ expect(body.style.paddingBlockEnd).toBe('');+ });++ it('keeps the settled height stable while dismissing', () => {+ const observers = mockResizeObserverInstances();+ mockVisualViewport(800);+ render(<ExitHarness />);+ const sheet = getSheet();+ const sheetObserver = observers.find(instance =>+ instance.observed.has(sheet),+ );+ act(() => {+ sheetObserver?.callback(+ [resizeEntry(784, 736)],+ sheetObserver as unknown as ResizeObserver,+ );+ });++ // First settle at the middle detent.+ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 240});+ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 240});+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});+ expect(sheet.style.height).toBe('448px');++ // A later dismiss stays transform-only and preserves that settled+ // scroll-area height throughout the exit.+ fireTimedPointer(getHandle(), 'pointerdown', {time: 3000, y: 240});+ fireTimedPointer(getHandle(), 'pointermove', {time: 4000, y: 1000});+ expect(sheet.style.transform).toBe('translateY(760px)');+ expect(sheet.style.height).toBe('448px');+ fireTimedPointer(getHandle(), 'pointerup', {time: 5000, y: 1000});+ expect(sheet.style.height).toBe('448px');++ act(() => {+ sheetObserver?.callback(+ [resizeEntry(200, 152)],+ sheetObserver as unknown as ResizeObserver,+ );+ });+ expect(sheet.style.height).toBe('448px');+ });});describe('mobile keyboard', () => {@@ -939,7 +1263,7 @@ describe('BottomSheet', () => {expect(sheetObserver).toBeDefined();act(() => {sheetObserver?.callback(- [{contentRect: rect({top: 0, bottom: 800})} as ResizeObserverEntry],+ [resizeEntry(784)],sheetObserver as unknown as ResizeObserver,);});@@ -947,7 +1271,11 @@ describe('BottomSheet', () => {fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 240});fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 240});- expect(sheet.style.transform).toBe('translateY(400px)');+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});+ // Settled at the p50 detent: 400px of visible sheet plus the 48px+ // border-box reserve held below the viewport.+ expect(sheet.style.transform).toBe('');+ expect(sheet.style.height).toBe('448px');vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(rect({top: 500, bottom: 1200}),@@ -969,7 +1297,9 @@ describe('BottomSheet', () => {'0px',);expect(body.scrollTop).toBe(0);- expect(sheet.style.transform).toBe('translateY(400px)');+ // The keyboard moved nothing: the sheet still rests at that detent.+ expect(sheet.style.transform).toBe('');+ expect(sheet.style.height).toBe('448px');});it.each([diff --git a/packages/lab/src/BottomSheet/BottomSheetPanel.tsx b/packages/lab/src/BottomSheet/BottomSheetPanel.tsxindex 0bf75f456d..25a8f8d8b4 100644--- a/packages/lab/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/lab/src/BottomSheet/BottomSheetPanel.tsx@@ -122,9 +122,11 @@ const styles = stylex.create({body: {flexGrow: 1,minHeight: 0,+ boxSizing: 'border-box',overflowY: 'auto',overscrollBehavior: 'none',touchAction: 'pan-y',+ paddingBlockEnd: 0,},tallKeyboardBody: {scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,@@ -338,9 +340,15 @@ export function BottomSheetPanel({dragOffset,settledOffset,isDragging,+ sheetHeight,+ scrollPreservationInset,+ settlingLayoutOffset,+ settledLayoutOffset,+ completeScrollAreaSettle,} = useSheetGestures({isOpen: isInteractive,canDismiss: canSwipeDismiss,+ offscreenBlockEndInset: OVERSCROLL_PADDING,onDismiss,snapHeights: defaultSnapHeights,onScrimOpacity,@@ -400,6 +408,20 @@ export function BottomSheetPanel({},);}, [motion]);+ // The snap is transform-only; the layout height reconciles when it lands.+ // waitForTransition — the same helper the motion states use — resolves that+ // even when no `transitionend` is coming: inline or computed+ // `transition: none`, a zero duration, and a timer backstop otherwise.+ useLayoutEffect(() => {+ if (settlingLayoutOffset == null) {+ return;+ }+ return waitForTransition(+ elementRef.current,+ 'transform',+ completeScrollAreaSettle,+ );+ }, [completeScrollAreaSettle, settlingLayoutOffset]);useEffect(() => {if (motion == null) {return;@@ -426,13 +448,48 @@ export function BottomSheetPanel({: typeof height === 'number'? `${height}px`: height;+ const hasMeasuredSheet = sheetHeight > 0;+ let gestureTransform = contentProps.style.transform;+ let resizedHeight: string | undefined;+ if (hasMeasuredSheet) {+ // The sheet's travel is split across two properties: `layoutOffset` is the+ // part the scrolling area gives up as layout height, and the remainder is+ // a compositor transform. Live gestures and snaps only ever move the+ // transform — the layout height changes at rest, in one reconciling render+ // whose visible geometry is identical (see useSheetGestures).+ // - dragging above the base restores the full height below the viewport+ // - a peek settles with layout 0, so it slides rather than reflowing+ const layoutOffset = isDragging+ ? dragOffset < settledOffset+ ? 0+ : settledLayoutOffset+ : (settlingLayoutOffset ?? settledLayoutOffset);+ const activeOffset = isDragging ? dragOffset : settledOffset;+ const translation = activeOffset - layoutOffset;++ // At layout 0 the sheet is its natural height, so leave that to CSS —+ // `hug` sheets must stay fit-content. While the sheet is in motion it is+ // pinned in px instead: content reflowing mid-gesture would move the+ // surface out from under the finger, or under the snap.+ const isTraveling = isDragging || settlingLayoutOffset != null;+ resizedHeight =+ layoutOffset > 0 || isTraveling+ ? `${Math.max(0, sheetHeight - Math.max(0, layoutOffset))}px`+ : undefined;+ gestureTransform =+ translation !== 0 ? `translateY(${translation}px)` : undefined;+ }const retainedTransform =alignmentOffset > 0- ? [contentProps.style.transform, `translateY(${alignmentOffset}px)`]+ ? [gestureTransform, `translateY(${alignmentOffset}px)`].filter(Boolean).join(' ')- : contentProps.style.transform;-+ : gestureTransform;+ const gestureStyle = {+ ...contentProps.style,+ transform: gestureTransform,+ height: resizedHeight,+ };return (<div{...props}@@ -452,10 +509,12 @@ export function BottomSheetPanel({{['--_sheet-budget' as string]: budget,...(isInteractive- ? contentProps.style+ ? gestureStyle: isRetained- ? {transform: retainedTransform}- : {}),+ ? {transform: retainedTransform, height: resizedHeight}+ : isClosing+ ? {height: resizedHeight}+ : {}),...style,},)}>@@ -471,6 +530,11 @@ export function BottomSheetPanel({height === 'tall' && styles.tallKeyboardBody,)}{...bodyProps}+ style={+ scrollPreservationInset > 0+ ? {paddingBlockEnd: `${scrollPreservationInset}px`}+ : undefined+ }ref={setBodyElement}>{children}</div>diff --git a/packages/lab/src/BottomSheet/snapOffsets.test.ts b/packages/lab/src/BottomSheet/snapOffsets.test.tsindex 24b672cc26..3ad92f2b46 100644--- a/packages/lab/src/BottomSheet/snapOffsets.test.ts+++ b/packages/lab/src/BottomSheet/snapOffsets.test.ts@@ -16,6 +16,7 @@ import {nearestOffset,resolveSettleOffset,scrimOpacityForOffset,+ isPeekOffset,DETENT_DEDUP_PX,} from './snapOffsets';@@ -99,6 +100,40 @@ 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);+ });++ 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 sheet has no collapsed stop', () => {+ expect(isPeekOffset(200, [0])).toBe(false);+ expect(isPeekOffset(0, [0])).toBe(false);+ });++ it('treats the only collapsed stop as the peek', () => {+ expect(isPeekOffset(200, [0, 200])).toBe(true);+ });++ 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,+ );+ });+});+describe('scrimOpacityForOffset', () => {describe('with a peek detent (>= 2 detents)', () => {const offsets = [0, 100, 200]; // full, mid, peekdiff --git a/packages/lab/src/BottomSheet/snapOffsets.ts b/packages/lab/src/BottomSheet/snapOffsets.tsindex f39b024df3..deccbbdffc 100644--- a/packages/lab/src/BottomSheet/snapOffsets.ts+++ b/packages/lab/src/BottomSheet/snapOffsets.ts@@ -7,11 +7,10 @@* @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+ * 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+ * as a translate or as a reduction in layout height. These+ * helpers turn snap points into the shared offset list; they are pure so the* geometry can be unit-tested without a DOM.*/@@ -33,12 +32,12 @@ export function snapFractionsToHeights(/*** 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.+ * candidate detent *visible heights* (px), return the resting 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.+ * height >= the sheet is already covered by the fully-open stop.* - 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.*/@@ -81,6 +80,27 @@ 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 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.+ */+export function isPeekOffset(+ offset: number,+ offsets: ReadonlyArray<number>,+ tolerancePx: number = 0.5,+): boolean {+ if (offsets.length < 2) {+ return false;+ }+ return Math.abs(offset - offsets[offsets.length - 1]) <= tolerancePx;+}+/*** Scrim opacity (1 = fully visible) for a drag/settle `offset`.* The scrim stays full while the sheet is at or above its second-shortestdiff --git a/packages/lab/src/BottomSheet/useSheetGestures.test.ts b/packages/lab/src/BottomSheet/useSheetGestures.test.tsindex 327b917865..0e49162380 100644--- a/packages/lab/src/BottomSheet/useSheetGestures.test.ts+++ b/packages/lab/src/BottomSheet/useSheetGestures.test.ts@@ -176,6 +176,74 @@ describe('useSheetGestures', () => {expect(hook.result.current.settledOffset).toBe(200);});+ it('excludes the offscreen block-end reserve from visible detent heights', () => {+ const onSnap = vi.fn();+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: 48,+ onSnap,+ });+ const t = makeTarget();++ // The 400px border box has 352px visible. A 200px visible detent therefore+ // rests at offset 152, not 200; the 48px reserve remains below the viewport.+ down(hook, 0, 0, t);+ move(hook, 150, 700, t);+ up(hook, 150, 1100, t);++ expect(hook.result.current.settledOffset).toBe(152);+ expect(onSnap).toHaveBeenLastCalledWith(200);+ });++ it('keeps the full layout height at the peek detent', () => {+ // Three detents on the 400px sheet: full (0), mid 240 (offset 160), and+ // the 80px peek (offset 320).+ const {hook} = setup({snapHeights: () => [80, 240]});+ const t = makeTarget();++ // Settle at the mid detent: the scrolling area takes that travel as+ // layout height.+ down(hook, 0, 0, t);+ move(hook, 150, 700, t);+ up(hook, 150, 1100, t);+ expect(hook.result.current.settledOffset).toBe(160);+ expect(hook.result.current.settledLayoutOffset).toBe(160);++ // Settle at the peek: a glance state keeps the sheet's full layout height+ // and slides it below the viewport, so no layout travel is reported.+ down(hook, 150, 2000, t);+ move(hook, 310, 2700, t);+ up(hook, 310, 3100, t);+ expect(hook.result.current.settledOffset).toBe(320);+ expect(hook.result.current.settledLayoutOffset).toBe(0);+ });++ it('treats the only collapsed stop as a peek, like the scrim does', () => {+ 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(0);+ });++ it('uses the visible shortest detent height for the dismiss overshoot', () => {+ const {hook, onDismiss} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: 48,+ });+ const t = makeTarget();++ // Visible full height is 352px, so the 200px stop is offset 152. Its 40%+ // dismiss overshoot ends at 232px; the hidden reserve must not extend it.+ down(hook, 0, 0, t);+ move(hook, 235, 1000, t);+ up(hook, 235, 2000, t);++ expect(onDismiss).toHaveBeenCalledTimes(1);+ });+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 modestdiff --git a/packages/lab/src/BottomSheet/useSheetGestures.ts b/packages/lab/src/BottomSheet/useSheetGestures.tsindex 3b204a166c..45f74958fb 100644--- a/packages/lab/src/BottomSheet/useSheetGestures.ts+++ b/packages/lab/src/BottomSheet/useSheetGestures.ts@@ -14,6 +14,13 @@* down). A fast flick up expands to the tallest detent. This is the core* behavior split the sheet needs: DRAG places, SWIPE closes.*+ * A settled detent is split across two properties: `settledLayoutOffset` is+ * 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.+ ** 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.@@ -30,15 +37,18 @@import {useCallback,useEffect,+ useLayoutEffect,useMemo,useRef,useState,type CSSProperties,type MouseEvent as ReactMouseEvent,type PointerEvent as ReactPointerEvent,+ type UIEvent as ReactUIEvent,} from 'react';import {computeDetentOffsets,+ isPeekOffset,resolveSettleOffset,scrimOpacityForOffset,} from './snapOffsets';@@ -57,9 +67,9 @@ 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.+// SYNC: must match OVERSCROLL_PADDING in BottomSheetPanel.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;// Short haptic tick on detent settle where supported. iOS Safari doesn't@@ -100,6 +110,27 @@ function magnetize(value: number, targets: number[]): number {return value + (nearestTarget - value) * pull;}+function preservationInsetForOffset(+ baseOffset: number,+ targetOffset: number,+ naturalEndGap: number,+): number {+ return Math.max(0, baseOffset - targetOffset - naturalEndGap);+}++function renderedBlockEndPadding(element: HTMLElement): number {+ const value = Number.parseFloat(getComputedStyle(element).paddingBlockEnd);+ return Number.isFinite(value) ? value : 0;+}++function visibleHeightForOffset(+ sheetHeight: number,+ offset: number,+ offscreenBlockEndInset: number,+): number {+ return Math.max(0, sheetHeight - offscreenBlockEndInset - offset);+}+export interface UseSheetGesturesOptions {/** Whether the owning sheet is open. Drag state resets when it closes. */isOpen: boolean;@@ -109,18 +140,24 @@ export interface UseSheetGesturesOptions {* @default true*/canDismiss?: boolean;+ /**+ * Portion of the measured sheet border box reserved below the viewport.+ * Excluded from detent heights so a 50vh snap has 50vh of visible sheet.+ * @default 0+ */+ offscreenBlockEndInset?: number;/** 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).+ * Resolver for candidate visible detent heights in px below the fully open+ * visible height. Called lazily at the start of each drag so the values stay+ * current (e.g. after rotation or virtual-keyboard opening) without a+ * persistent resize listener. The fully open height is always the tallest+ * detent. Omit for a single-height sheet (a drag then only dismisses or+ * springs back).*/snapHeights?: () => number[];- /** Notified when the settled detent height (px) changes. */+ /** Notified when the settled visible detent height (px) changes. */onSnap?: (heightPx: number) => void;/*** Called with the scrim opacity the sheet should show (1 = fully visible,@@ -154,6 +191,7 @@ export interface SheetBodyProps {onPointerMove: (event: ReactPointerEvent) => void;onPointerUp: (event: ReactPointerEvent) => void;onPointerCancel: (event: ReactPointerEvent) => void;+ onScroll: (event: ReactUIEvent<HTMLElement>) => void;}export interface UseSheetGesturesResult {@@ -179,6 +217,27 @@ export interface UseSheetGesturesResult {settledOffset: number;/** Whether a drag is currently in progress. */isDragging: boolean;+ /** Measured height of the fully expanded sheet. */+ sheetHeight: number;+ /** End padding that preserves the scroll position across height changes. */+ scrollPreservationInset: number;+ /** Layout offset retained until the transform-only snap finishes. */+ settlingLayoutOffset: number | null;+ /**+ * Reconciles the final layout once the transform-only snap finishes. The+ * panel decides WHEN a snap is over (it owns the element and its computed+ * transition), so completion cannot be driven from a `transitionend`+ * listener alone: with transitions disabled — inline `transition: none`, a+ * `0s` duration token, a test harness turning animation off — no event ever+ * arrives and the scroll area would keep its full height forever.+ */+ completeScrollAreaSettle: () => void;+ /**+ * 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).+ */+ settledLayoutOffset: number;}function prefersReducedMotion(): boolean {@@ -210,6 +269,7 @@ function prefersReducedMotion(): boolean {export function useSheetGestures({isOpen,canDismiss = true,+ offscreenBlockEndInset = 0,onDismiss,snapHeights,onSnap,@@ -218,6 +278,96 @@ export function useSheetGestures({const [dragOffset, setDragOffset] = useState(0);const [settledOffset, setSettledOffset] = useState(0);const [isDragging, setIsDragging] = useState(false);+ const [sheetHeight, setSheetHeight] = useState(0);+ 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.+ const [settledLayoutOffset, setSettledLayoutOffset] = useState(0);+ const settledLayoutOffsetRef = useRef(0);+ const [settlingLayoutOffset, setSettlingLayoutOffset] = useState<+ number | null+ >(null);+ const [isScrollAreaReconciling, setIsScrollAreaReconciling] = useState(false);+ const scrollPreservationInsetRef = useRef(0);+ const settlingLayoutOffsetRef = useRef<number | null>(null);+ const pendingScrollPreservationInsetRef = useRef<number | null>(null);+ const offscreenBlockEndInsetRef = useRef(offscreenBlockEndInset);+ offscreenBlockEndInsetRef.current = Math.max(0, offscreenBlockEndInset);+ const recordSettledLayoutOffset = useCallback((offset: number) => {+ const normalizedOffset = Math.max(0, offset);+ settledLayoutOffsetRef.current = normalizedOffset;+ setSettledLayoutOffset(normalizedOffset);+ }, []);+ const updateScrollPreservationInset = useCallback((nextInset: number) => {+ const normalizedInset = Math.max(0, nextInset);+ const hasChanged =+ Math.abs(normalizedInset - scrollPreservationInsetRef.current) > 0.5;+ if (!hasChanged) {+ return;+ }+ scrollPreservationInsetRef.current = normalizedInset;+ setScrollPreservationInset(normalizedInset);+ }, []);+ const completeScrollAreaSettle = useCallback(() => {+ // Resetting the transform at the same time as the final height swap must+ // not start a second transition. The layouts have identical visible+ // geometry, so reconcile them with transitions disabled for one frame.+ setIsScrollAreaReconciling(true);+ settlingLayoutOffsetRef.current = null;+ setSettlingLayoutOffset(null);+ const pendingInset = pendingScrollPreservationInsetRef.current;+ pendingScrollPreservationInsetRef.current = null;+ if (pendingInset != null) {+ updateScrollPreservationInset(pendingInset);+ }+ }, [updateScrollPreservationInset]);+ const prepareScrollAreaSettle = useCallback(+ (+ baseLayoutOffset: number,+ targetOffset: number,+ targetLayoutOffset: number,+ renderedOffset: number,+ layoutOffset: number,+ naturalEndGap: number,+ shouldAnimate: boolean,+ ) => {+ const targetInset = preservationInsetForOffset(+ baseLayoutOffset,+ targetLayoutOffset,+ naturalEndGap,+ );+ if (+ shouldAnimate &&+ Math.abs(renderedOffset - targetOffset) > 0.5 &&+ !prefersReducedMotion()+ ) {+ pendingScrollPreservationInsetRef.current = targetInset;+ settlingLayoutOffsetRef.current = layoutOffset;+ setSettlingLayoutOffset(layoutOffset);+ return;+ }+ pendingScrollPreservationInsetRef.current = null;+ settlingLayoutOffsetRef.current = null;+ setSettlingLayoutOffset(null);+ // Released on the detent, so there is no travel left to animate — but+ // the layout split may still differ from the one the drag rendered+ // with (magnetize() lands a slow drag exactly on a detent). Swapping+ // height for transform is only invisible while transitions are off:+ // with them live, the composited transform would animate the whole+ // swap while the layout height jumped, throwing the sheet the wrong+ // way. Reconcile in one transition-free frame instead.+ setIsScrollAreaReconciling(+ Math.abs(layoutOffset - targetLayoutOffset) > 0.5,+ );+ updateScrollPreservationInset(targetInset);+ },+ [updateScrollPreservationInset],+ );+ const activeOffsetRef = useRef(0);+ activeOffsetRef.current = isDragging ? dragOffset : settledOffset;+ const isOpenRef = useRef(isOpen);+ isOpenRef.current = isOpen;const onDismissRef = useRef(onDismiss);const canDismissRef = useRef(canDismiss);@@ -241,33 +391,75 @@ export function useSheetGestures({velocity: number;height: number;baseOffset: number;+ baseLayoutOffset: number;+ renderedOffset: number;+ layoutOffset: number;+ naturalEndGap: number;} | null>(null);// 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 bodyNodeRef = 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;- }+ useLayoutEffect(() => {+ if (!isScrollAreaReconciling) {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;- }+ // Force the transition-free transform reset to resolve before transitions+ // are restored. Otherwise both DOM updates can be coalesced and the reset+ // becomes an unintended fly-in animation from the bottom.+ void sheetElRef.current?.offsetHeight;+ const frame = requestAnimationFrame(() => {+ setIsScrollAreaReconciling(false);});- ro.observe(node);- observerRef.current = ro;+ return () => cancelAnimationFrame(frame);+ }, [isScrollAreaReconciling]);+ const recordSheetHeight = useCallback((renderedHeight: number) => {+ if (renderedHeight <= 0) {+ return;+ }+ // A resized or closing panel's observer reports intermediate heights+ // throughout its animation. Keep the last fully-expanded measurement+ // instead of feeding those transient values back into the rendered height.+ if (!isOpenRef.current || activeOffsetRef.current > 0) {+ return;+ }+ sheetHeightRef.current = renderedHeight;+ setSheetHeight(previousHeight =>+ previousHeight === renderedHeight ? previousHeight : renderedHeight,+ );}, []);+ const sheetRef = useCallback(+ (node: HTMLElement | null) => {+ observerRef.current?.disconnect();+ observerRef.current = null;+ sheetElRef.current = node;+ if (!node || typeof ResizeObserver === 'undefined') {+ if (node) {+ recordSheetHeight(node.getBoundingClientRect().height);+ }+ return;+ }+ recordSheetHeight(node.getBoundingClientRect().height);+ const ro = new ResizeObserver(entries => {+ const entry = entries[0];+ if (entry) {+ // Keep this measurement in the same border-box coordinate space as+ // getBoundingClientRect(). contentRect excludes the sheet's reserved+ // bottom padding and would make the first resized drag jump shorter.+ const borderBoxHeight = entry.borderBoxSize?.[0]?.blockSize;+ recordSheetHeight(+ borderBoxHeight ?? entry.target.getBoundingClientRect().height,+ );+ }+ });+ ro.observe(node);+ observerRef.current = ro;+ },+ [recordSheetHeight],+ );useEffect(() => () => observerRef.current?.disconnect(), []);// Reset to the tallest detent each time the sheet re-opens.@@ -276,8 +468,15 @@ export function useSheetGestures({setDragOffset(0);setSettledOffset(0);setIsDragging(false);+ setIsScrollAreaReconciling(false);+ recordSettledLayoutOffset(0);+ scrollPreservationInsetRef.current = 0;+ settlingLayoutOffsetRef.current = null;+ pendingScrollPreservationInsetRef.current = null;+ setScrollPreservationInset(0);+ setSettlingLayoutOffset(null);}- }, [isOpen]);+ }, [isOpen, recordSettledLayoutOffset]);// 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@@ -289,12 +488,20 @@ export function useSheetGestures({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.+ // 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[] => {- return computeDetentOffsets(height, snapHeightsRef.current?.() ?? []);+ const visibleSheetHeight = visibleHeightForOffset(+ height,+ 0,+ offscreenBlockEndInsetRef.current,+ );+ return computeDetentOffsets(+ visibleSheetHeight,+ snapHeightsRef.current?.() ?? [],+ );}, []);const cancelDrag = useCallback(@@ -312,20 +519,33 @@ export function useSheetGestures({}setDragOffset(state.baseOffset);setIsDragging(false);+ prepareScrollAreaSettle(+ state.baseLayoutOffset,+ state.baseOffset,+ state.baseLayoutOffset,+ state.renderedOffset,+ state.layoutOffset,+ state.naturalEndGap,+ true,+ );// 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 maxOffset = offsets[offsets.length - 1];- const shortestDetentHeight = state.height - maxOffset;+ const shortestDetentHeight = visibleHeightForOffset(+ state.height,+ maxOffset,+ offscreenBlockEndInsetRef.current,+ );const dismissOffset =maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;onScrimOpacityRef.current?.(scrimOpacityForOffset(state.baseOffset, offsets, dismissOffset),);},- [detentOffsets],+ [detentOffsets, prepareScrollAreaSettle],);useEffect(() => {@@ -351,15 +571,42 @@ export function useSheetGestures({dir: number,travel: number,baseOffset: number,+ baseLayoutOffset: number,+ renderedOffset: number,+ layoutOffset: number,+ naturalEndGap: number,) => {const offsets = detentOffsets(height);const maxOffset = offsets[offsets.length - 1];- const shortestDetentHeight = height - maxOffset;+ const shortestDetentHeight = visibleHeightForOffset(+ height,+ maxOffset,+ offscreenBlockEndInsetRef.current,+ );const speed = Math.abs(velocity);const isFlick = speed > FLICK_VELOCITY && travel > FLICK_MIN_DISTANCE;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;+ prepareScrollAreaSettle(+ baseLayoutOffset,+ target,+ targetLayoutOffset,+ renderedOffset,+ layoutOffset,+ naturalEndGap,+ true,+ );+ recordSettledLayoutOffset(targetLayoutOffset);setSettledOffset(target);- onSnapRef.current?.(height - target);+ onSnapRef.current?.(+ visibleHeightForOffset(+ height,+ target,+ offscreenBlockEndInsetRef.current,+ ),+ );const dismissOffset =maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;onScrimOpacityRef.current?.(@@ -372,6 +619,15 @@ export function useSheetGestures({if (dir > 0 && isFlick) {if (canDismissRef.current) {+ prepareScrollAreaSettle(+ baseLayoutOffset,+ baseOffset,+ baseLayoutOffset,+ baseLayoutOffset,+ baseLayoutOffset,+ naturalEndGap,+ false,+ );onDismissRef.current();} else {settleAt(maxOffset);@@ -381,14 +637,36 @@ export function useSheetGestures({// Fast upward flick = expand to the tallest detent (the sheet's full// provided height).if (dir < 0 && isFlick) {+ prepareScrollAreaSettle(+ baseLayoutOffset,+ 0,+ 0,+ renderedOffset,+ layoutOffset,+ naturalEndGap,+ true,+ );+ recordSettledLayoutOffset(0);+ setDragOffset(0);setSettledOffset(0);- onSnapRef.current?.(height);+ onSnapRef.current?.(+ visibleHeightForOffset(height, 0, offscreenBlockEndInsetRef.current),+ );onScrimOpacityRef.current?.(1);hapticTick();return;}if (offset > maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO) {if (canDismissRef.current) {+ prepareScrollAreaSettle(+ baseLayoutOffset,+ baseOffset,+ baseLayoutOffset,+ baseLayoutOffset,+ baseLayoutOffset,+ naturalEndGap,+ false,+ );onDismissRef.current();} else {settleAt(maxOffset);@@ -400,7 +678,7 @@ export function useSheetGestures({const target = resolveSettleOffset(offset, offsets, dir, baseOffset);settleAt(target);},- [detentOffsets],+ [detentOffsets, prepareScrollAreaSettle, recordSettledLayoutOffset],);const beginDrag = useCallback(@@ -411,6 +689,13 @@ export function useSheetGestures({// pointer-down position (not the promotion point), so the first frame's// delta reflects the full pull distance.const start = startCoord ?? event.clientY;+ const body = bodyNodeRef.current;+ const renderedInset = body ? renderedBlockEndPadding(body) : 0;+ const naturalMaxScrollTop = body+ ? Math.max(0, body.scrollHeight - body.clientHeight - renderedInset)+ : 0;+ const naturalEndGap = body ? naturalMaxScrollTop - body.scrollTop : 0;+ const baseLayoutOffset = settledLayoutOffsetRef.current;dragStateRef.current = {pointerId: event.pointerId,startCoord: start,@@ -419,13 +704,24 @@ export function useSheetGestures({velocity: 0,height: sheetHeight,baseOffset: settledOffset,+ baseLayoutOffset,+ renderedOffset: settledOffset,+ layoutOffset: baseLayoutOffset,+ naturalEndGap,};+ updateScrollPreservationInset(+ preservationInsetForOffset(+ baseLayoutOffset,+ baseLayoutOffset,+ naturalEndGap,+ ),+ );// Seed dragOffset at the resting detent so flipping isDragging doesn't// jump the sheet to fully-open for one frame.setDragOffset(settledOffset);setIsDragging(true);},- [settledOffset],+ [settledOffset, updateScrollPreservationInset],);const handlePointerDown = useCallback(@@ -490,20 +786,37 @@ export function useSheetGestures({// Between detents: magnetically ease toward a nearby one.next = magnetize(raw, offsets);}+ // Dragging above the base restores the full layout height below the+ // viewport; otherwise keep whatever layout the base detent settled with+ // (0 at a peek, so a peek drag stays transform-only).+ const layoutOffset = next < state.baseOffset ? 0 : state.baseLayoutOffset;+ state.renderedOffset = next;+ state.layoutOffset = layoutOffset;setDragOffset(next);+ updateScrollPreservationInset(+ preservationInsetForOffset(+ state.baseLayoutOffset,+ layoutOffset,+ state.naturalEndGap,+ ),+ );// 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 shortestDetentHeight = visibleHeightForOffset(+ state.height,+ floorOffset,+ offscreenBlockEndInsetRef.current,+ );const dismissOffset =floorOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;onScrimOpacityRef.current?.(scrimOpacityForOffset(next, offsets, dismissOffset),);},- [detentOffsets],+ [detentOffsets, updateScrollPreservationInset],);const endDrag = useCallback(@@ -526,6 +839,10 @@ export function useSheetGestures({dir,Math.abs(delta),state.baseOffset,+ state.baseLayoutOffset,+ state.renderedOffset,+ state.layoutOffset,+ state.naturalEndGap,);},[settleFromDrag],@@ -594,7 +911,6 @@ export function useSheetGestures({// 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;@@ -746,6 +1062,37 @@ export function useSheetGestures({const reducedMotion = useMemo(() => prefersReducedMotion(), [isOpen]);+ const reconcileScrollPreservationInset = useCallback(+ (body: HTMLElement) => {+ if (scrollPreservationInsetRef.current <= 0) {+ return;+ }+ const renderedInset = renderedBlockEndPadding(body);+ const naturalMaxScrollTop = Math.max(+ 0,+ body.scrollHeight - body.clientHeight - renderedInset,+ );+ const requiredInset = Math.max(0, body.scrollTop - naturalMaxScrollTop);+ if (requiredInset < scrollPreservationInsetRef.current - 0.5) {+ updateScrollPreservationInset(requiredInset);+ }+ },+ [updateScrollPreservationInset],+ );++ const handleBodyScroll = useCallback(+ (event: ReactUIEvent<HTMLElement>) => {+ if (+ dragStateRef.current != null ||+ settlingLayoutOffsetRef.current != null+ ) {+ return;+ }+ reconcileScrollPreservationInset(event.currentTarget);+ },+ [reconcileScrollPreservationInset],+ );+// While dragging, follow the finger; otherwise rest at the settled detent.const activeOffset = isDragging ? dragOffset : settledOffset;@@ -754,12 +1101,15 @@ export function useSheetGestures({style: {transform:activeOffset !== 0 ? `translateY(${activeOffset}px)` : undefined,- transition: isDragging || reducedMotion ? 'none' : undefined,+ transition:+ isDragging || isScrollAreaReconciling || reducedMotion+ ? 'none'+ : undefined,touchAction: 'none',overscrollBehavior: 'contain',},}),- [activeOffset, isDragging, reducedMotion],+ [activeOffset, isDragging, isScrollAreaReconciling, reducedMotion],);const handleProps = useMemo<SheetHandleProps>(@@ -790,12 +1140,14 @@ export function useSheetGestures({onPointerMove: handleBodyPointerMove,onPointerUp: handleBodyEnd,onPointerCancel: handleBodyEnd,+ onScroll: handleBodyScroll,}),[bodyRef,handleBodyEnd,handleBodyPointerDown,handleBodyPointerMove,+ handleBodyScroll,handleContextMenu,handleLostPointerCapture,],@@ -809,5 +1161,10 @@ export function useSheetGestures({dragOffset,settledOffset,isDragging,+ sheetHeight,+ scrollPreservationInset,+ settlingLayoutOffset,+ settledLayoutOffset,+ completeScrollAreaSettle,};}