An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a BottomSheet pulled past its top stretches on every pull, on the iOS rubber band (#8109)
Christopher Chedeau63592ed62d97
diff --git a/.changeset/bottom-sheet-pull-stretch.md b/.changeset/bottom-sheet-pull-stretch.mdnew file mode 100644index 0000000000..a2e1ec45fb--- /dev/null+++ b/.changeset/bottom-sheet-pull-stretch.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet: a finger's pull up past the top stretches the sheet on every pull, on iOS's rubber band, with no 48 px cap, unless the caller sizes or styles the sheet (an inline block size, any `xstyle` or class name), which keeps it. The sheet keeps enough of its surface below the screen that the page never shows. A pull on the content stretches it too once the content has no room left to scroll: at once for content that fits, and after a long list reaches its end. A mouse or a pen keeps its current stretch.++@vjeuxdiff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsxindex e71f25fd23..cfc1437b93 100644--- a/apps/storybook/stories/BottomSheet.stories.tsx+++ b/apps/storybook/stories/BottomSheet.stories.tsx@@ -590,6 +590,71 @@ export const HugHeight: Story = {},};+/**+ * A sheet whose height the caller sets. It keeps a 48 px surface below the+ * screen, so a pull past the top stretches it at most that far.+ */+export const CallerHeight: Story = {+ name: 'Caller height (500 px)',+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <Button label="Open 500 px sheet" onClick={() => setIsOpen(true)} />+ <BottomSheet+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ label="Caller height"+ style={{height: 500}}>+ <Section padding={4}>+ <VStack gap={4}>+ <Heading level={3}>Caller height</Heading>+ <Text type="supporting" color="secondary">+ The caller sets this sheet's height to 500 px.+ </Text>+ <Button label="Done" onClick={() => setIsOpen(false)} />+ </VStack>+ </Section>+ </BottomSheet>+ </>+ );+ },+};++const callerHeightStyles = stylex.create({+ sheet: {height: 500},+});++export const CallerHeightXstyle: Story = {+ name: 'Caller height through xstyle (500 px)',+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <Button+ label="Open 500 px xstyle sheet"+ onClick={() => setIsOpen(true)}+ />+ <BottomSheet+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ label="Caller height through xstyle"+ xstyle={callerHeightStyles.sheet}>+ <Section padding={4}>+ <VStack gap={4}>+ <Heading level={3}>Caller height through xstyle</Heading>+ <Text type="supporting" color="secondary">+ The caller sets this sheet's height to 500 px through xstyle.+ </Text>+ <Button label="Done" onClick={() => setIsOpen(false)} />+ </VStack>+ </Section>+ </BottomSheet>+ </>+ );+ },+};+export const HugHeightWithLongContent: Story = {name: 'Hug height — Long content',render: () => {diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex 34d3dcbb78..bd805a3380 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -358,7 +358,10 @@ a measured, sourced difference exists.the area sits at its edge and the drag moves toward that edge, thesurrounding surface (a sheet) takes the drag; otherwise the area keeps it forthe whole gesture and rubber-bands at its edge. The drag MUST NOT change- hands midway, in either direction. This amends `spec:AST-025` FR14 (scroll+ hands midway, in either direction, with one exception (DEC-28). At a+ sheet's tallest detent, a pull that carries its content past its end+ continues as the sheet's stretch, and a reversal hands it back to the+ content (`component:BottomSheet` FR18). This amends `spec:AST-025` FR14 (scrollchaining by default) for touch presentations on every touch platform.- **FR15 — Recognizers arbitrate like UIKit's.** Recognizers that see thesame touch sequence MUST be exclusive by default: the first to recognize@@ -809,7 +812,13 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and- `component:BottomSheet`: a `form` or `required` sheet rubber-bands past itsresting place under a finger as under a trackpad (FR3, FR43), with the samestretch for the same travel; a mouse wheel scrolls its content and never- moves it. Implementation gap: a finger drags it one for one below rest.+ moves it. Past its tallest detent, every finger's pull stretches it on FR3's+ rubber band with no hold, over a reserve deep enough for the whole stretch+ and the release. A pull on its content does so once the content cannot+ scroll that way (`component:BottomSheet` FR18). Past its tallest detent, a+ mouse and a pen keep FR18's resisted stretch of at most 48 px, an exception+ to FR43's same rubber band (`spec:AST-017` FR59). Implementation gap: a+ finger drags it one for one below rest.- The shared pager (Carousel's paging presentation, Lightbox's viewer): atrackpad swipe follows FR43's pager rule in Lightbox's viewer and inCarousel's paging presentation, under every pointer (`component:Lightbox`@@ -1307,6 +1316,18 @@ checks there.Rejected: a physical Android phone as a gate or as a follow-up check.+### DEC-28 — Sheet stretch at the tallest detent++**Reference:** `spec:AST-094/DEC-28`+**Decider:** the owner, `2026-11-03`++Decided by the owner in a feel check on a phone: at a sheet's tallest detent,+a pull that carries its content past its end continues as the sheet's+stretch, and a reversal hands it back (FR14's one exception).++Rejected: keeping the whole gesture with the content (the strict nested-scroll+rule).+## Open questions- **OQ1 — Scroll view bounce-back curve.** What curve brings a scroll viewdiff --git a/docs/specs/components/BottomSheet/BottomSheet.spec.md b/docs/specs/components/BottomSheet/BottomSheet.spec.mdindex 638b2e891a..adabfb4af7 100644--- a/docs/specs/components/BottomSheet/BottomSheet.spec.md+++ b/docs/specs/components/BottomSheet/BottomSheet.spec.md@@ -17,9 +17,11 @@ verified_by:packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsx,packages/core/src/BottomSheet/BottomSheetStacking.test.tsx,packages/core/src/BottomSheet/BottomSheetReplace.test.tsx,+ packages/core/src/BottomSheet/useSheetGestures.test.ts,packages/core/src/Toast/ToastViewport.modalHost.test.tsx,packages/core/src/BottomSheet/__tests__/BottomSheetNativeModal.a11y.browser.spec.ts,packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts,+ packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.ts,apps/storybook/stories/BottomSheet.stories.tsx,scripts/check-knowledge.mjs,]@@ -164,6 +166,7 @@ remain documented in `BottomSheet.doc.mjs`.| FR15 | Under `prefers-reduced-motion: reduce` the recede, the return from receded, a push's entrance, a pop's exit and the replace handoff — and a `BottomSheetSwitcher` step's, which shares the sheet panel's motion — follow `design:reduced-motion`, keyed on its queries (`prefers-reduced-motion: reduce`, with `pointer: coarse` for the cross-fade): no transform motion runs (DR1) — a covered sheet appears in its receded place and size the frame the push lands and returns the same way, the entering sheet appears in its final place, the retained sheet does not align down; on a coarse pointer the entering sheet fades in and the leaving or retained sheet fades out where it is, opacity only, in 200 ms or less (DR2); a dismissal the release of a touch drag started (a swipe past the dismiss line) fades out in place the same way on every pointer (DR2's drag-release clause); on any other pointer every other change is immediate (DR3); the handoff's steps run in the released order, so the retained sheet is hidden and its dialog closed once its fade ends. The constant page dim through a push, a pop and a handoff (FR6) holds as it does with motion. | DEC-2; `design:reduced-motion` || FR16 | An open modal sheet is a focus region through Core's shared focus-region module (`component:Dialog/DEC-2`): in the top sheet, Tab from the last tabbable control moves focus to the first and Shift+Tab from the first moves focus to the last, so focus never leaves the sheet for the browser's own interface. A covered or closing sheet does not answer Tab, and a non-modal sheet contains nothing (FR11). A switcher step (the deprecated BottomSheetSwitcher) is the exception to DEC-2, as `component:Dialog` DEC-2 states. | `component:Dialog/DEC-2` || FR17 | A BottomSheet open on the server, by its own `isOpen` or as a `BottomSheetSwitcher`'s active sheet, renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed sheet) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 |+| FR18 | A finger's pull up past the tallest detent stretches the sheet on `spec:AST-094` FR3's rubber band, the same on every pull, with no hold. The sheet's surface reaches below the screen far enough for the whole stretch and the release, so the page under it never shows. A pull on the sheet's body stretches it as a pull on the grabber does, once the content has no room left to scroll that way: content that fits stretches at once, and a long list scrolls to its end first, then holds still while the sheet stretches. At every detent, a list that reaches its end mid-pull holds still while the sheet takes the rest of the pull. A sheet the caller sizes or styles keeps 48 px below the screen, and its stretch stops there. An inline block size, any `xstyle` and any class name count, because the sheet cannot read their rules. A mouse or a pen keeps its own resisted stretch, at most 48 px (`spec:AST-017` FR59). | DEC-3; `spec:AST-094` FR3 |### Allowed variation@@ -210,7 +213,7 @@ remain documented in `BottomSheet.doc.mjs`.fires no native `close`.- A same-update close and open is tested against FR10 in that order ofconditions; the first failing condition makes it a push and a pop.-- No new height or gesture precedence rule is introduced.+- No new height rule is introduced. Its one gesture precedence rule is `spec:AST-094` FR14's named exception: at the tallest detent, a pull that carries the content past its end continues as the sheet's stretch (FR18).### Performance and resources@@ -384,6 +387,7 @@ a decision that they must remain unthemeable.| FR13–FR14 | Toast viewport hosting suite (jsdom, native dialog methods and popover state stubbed); real-browser hit-testing of a toast raised from the top sheet, from a Dialog opened from a sheet after an inner sheet closed, from a sheet re-shown by a reversal, and over a non-modal sheet | a lone sheet; a stack of two; sheet → Dialog → sheet → close the inner sheet; a reversal and a reopen during exit, with the stale native `close`; a non-modal sheet shown after the viewport; a modal switcher flow alone, through a handoff and its close; a flow stacked over a standalone sheet and a standalone sheet over a flow; a non-modal flow | A toast renders in a covered or inert sheet, a Dialog opened from a sheet loses the toast to the sheet beneath it, a re-shown sheet loses its outlet to the stale `close`, a toast raised from a switcher step lands behind the flow or in its retained step, or a toast paints beneath a non-modal sheet. | `audit:BottomSheet/behavior` || FR16 | `BottomSheet.test.tsx` focus-region suite | Modal and non-modal sheets; Tab and Shift+Tab at the sheet's edge | Tab from the last control leaves a modal sheet, or a non-modal sheet captures Tab | `audit:BottomSheet/accessibility` || FR17 | `BottomSheet.ssr.test.tsx`; `BottomSheetSwitcher.test.tsx` flow that mounts open | Open on the server; hydration; a closed sheet's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:BottomSheet/accessibility` |+| FR18 | `useSheetGestures.test.ts` stretch suites; `BottomSheetPanel.test.tsx` reserve cases; `BottomSheetDrag.a11y.chromium.spec.ts` | Three finger pulls past the top; short content pulled up on its body at five points, the first pull and every one after it; a long list pulled past its end; a mouse pull and a pen pull | A capped or held stretch, a pull that stretches less than the one before it, a body pull on short content that moves nothing, a long list that never stretches the sheet once at its end or rubber-bands itself while the sheet stretches, or a reserve under 40% of the viewport on a device with a touch pointer fails, unless the caller sizes or styles the sheet (48 px). | `audit:BottomSheet/behavior` |Existing tests directly assert the Sheet panel target, Content area placement,Handle structure, and scrim behavior. Source and public target metadata confirm@@ -447,6 +451,25 @@ sheet is unaffected and one state value already says what a flow means.Rejected: a page-level `z-index` on a non-modal sheet to order a replace,because `spec:AST-027` forbids a new band; the top layer orders it.+### DEC-3 — A pull past the top stretches on every pull++**Reference:** `component:BottomSheet/DEC-3`+**Decider:** the component owner, 2026-11-02++A pull up past the tallest detent stretches the sheet on the rubber band every+time, with no cap and no hold, and the page under the sheet never shows: the+surface the sheet keeps below the screen is deep enough for the whole stretch+and the release (FR18). A pull on the sheet's body counts as a pull on the+sheet once its content has no room left to scroll that way. So short content+stretches on the first pull and on every pull after it, and a long list scrolls+to its end before the sheet stretches. The evidence is an owner screen+recording on an iPhone, 2026-11-02, in which most body pulls on short content+moved nothing.+Rejected: a stretch capped at a 48 px reserve, because it holds still partway+through a pull.+Rejected: a second mechanism for upward pulls, because the existing pull path+already carries them; it only gave too many of them to the content.+## Open questions- **OQ1 — Should Content area, Handle, or Scrim gain a stable public themingdiff --git a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsxindex 15d56ad79a..78eb837dc4 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx@@ -8,6 +8,7 @@* @position Internal presentation tests shared by standalone and switcher modes*/+import * as stylex from '@stylexjs/stylex';import {act, fireEvent, render, screen} from '@testing-library/react';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {@@ -42,6 +43,23 @@ afterEach(() => {vi.unstubAllGlobals();});+// A device with a touch pointer: only `(any-pointer: coarse)` matches.+function stubTouchPointer() {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query === '(any-pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+}+function renderPanel(state: BottomSheetPanelState,callbacks: {@@ -74,7 +92,151 @@ function getPanel(): HTMLElement {return panel;}+const callerSizeStyles = stylex.create({+ height: {height: 500},+ maxHeight: {maxHeight: 500},+ color: {color: 'rebeccapurple'},+});+describe('BottomSheetPanel', () => {+ it('keeps 40% of the viewport of its surface below the screen, for the whole stretch past the top', () => {+ stubTouchPointer();+ renderPanel({kind: 'open', entering: false});+ // A finger's rubber band over a sheet as tall as the viewport shows at+ // most 35.5% of the viewport.+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe(+ `${Math.ceil(window.innerHeight * 0.4)}px`,+ );+ });++ it('keeps the smallest reserve, 48 px, under a height the caller sets, on a device with a touch pointer', () => {+ // Nothing extends a caller's height by the reserve, so a deeper one would+ // hide that much more of the sheet below the screen.+ stubTouchPointer();+ render(+ <BottomSheetPanel+ label="Sheet details"+ state={{kind: 'open', entering: false}}+ height="hug"+ style={{...panelTransitionStyle, height: 500}}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ Panel content+ </BottomSheetPanel>,+ );+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');+ });++ it('keeps the smallest reserve, 48 px, under a size the caller sets through xstyle, on a device with a touch pointer', () => {+ stubTouchPointer();+ render(+ <BottomSheetPanel+ label="Sheet details"+ state={{kind: 'open', entering: false}}+ height="hug"+ style={panelTransitionStyle}+ xstyle={callerSizeStyles.height}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ Panel content+ </BottomSheetPanel>,+ );+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');+ });++ it('keeps the smallest reserve, 48 px, under a maximum size in an xstyle array, on a device with a touch pointer', () => {+ stubTouchPointer();+ render(+ <BottomSheetPanel+ label="Sheet details"+ state={{kind: 'open', entering: false}}+ height="hug"+ style={panelTransitionStyle}+ xstyle={[callerSizeStyles.color, callerSizeStyles.maxHeight]}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ Panel content+ </BottomSheetPanel>,+ );+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');+ });++ it('keeps the smallest reserve, 48 px, under a class name the caller passes, on a device with a touch pointer', () => {+ // A class name's rules can size the sheet, and nothing can read them.+ stubTouchPointer();+ render(+ <BottomSheetPanel+ label="Sheet details"+ state={{kind: 'open', entering: false}}+ height="hug"+ className="caller-sheet"+ style={panelTransitionStyle}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ Panel content+ </BottomSheetPanel>,+ );+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');+ });++ it('keeps the smallest reserve, 48 px, under any xstyle, whose rules nothing can read, on a device with a touch pointer', () => {+ stubTouchPointer();+ render(+ <BottomSheetPanel+ label="Sheet details"+ state={{kind: 'open', entering: false}}+ height="hug"+ style={panelTransitionStyle}+ xstyle={callerSizeStyles.color}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ Panel content+ </BottomSheetPanel>,+ );+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');+ });++ it('keeps the viewport reserve under an empty xstyle and a style that does not size the sheet, on a device with a touch pointer', () => {+ stubTouchPointer();+ render(+ <BottomSheetPanel+ label="Sheet details"+ state={{kind: 'open', entering: false}}+ height="hug"+ style={{...panelTransitionStyle, color: 'rebeccapurple'}}+ xstyle={[false, undefined]}+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ Panel content+ </BottomSheetPanel>,+ );+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).not.toBe(+ '48px',+ );+ });++ it('keeps the smallest reserve, 48 px, on a device with no touch pointer', () => {+ renderPanel({kind: 'open', entering: false});+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');+ });++ it('follows the viewport with its reserve while it is presented', () => {+ const viewportHeight = window.innerHeight;+ stubTouchPointer();+ renderPanel({kind: 'open', entering: false});+ try {+ act(() => {+ window.innerHeight = 1000;+ window.dispatchEvent(new Event('resize'));+ });+ expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe(+ '400px',+ );+ } finally {+ window.innerHeight = viewportHeight;+ }+ });+it('reports entrance completion only for the surface transform', () => {const onMotionStart = vi.fn();const onMotionComplete = vi.fn();diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex 7f4b8da13b..653eba94aa 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -26,6 +26,7 @@ import {useLayoutEffect,useMemo,useRef,+ useSyncExternalStore,type ReactNode,} from 'react';import * as stylex from '@stylexjs/stylex';@@ -60,6 +61,7 @@ import {paddingStyles,spacingStepToToken,} from '../Layout/padding.stylex';+import {subscribeInput} from '../utils/inputStream';import type {SpacingStep} from '../utils/types';import {isValidSnapPoint,@@ -82,8 +84,20 @@ const HEIGHT_BUDGETS = {export type BottomSheetHeight = keyof typeof HEIGHT_BUDGETS;export type {BottomSheetSnapPoint};-// SYNC: must match OVERSCROLL_MAX in useSheetGestures.ts.-const OVERSCROLL_PADDING = 48;+// The reserve: how far the sheet's surface reaches below the screen, so a+// pull past the top never shows the page under it.+// SYNC: OVERSCROLL_MAX in useSheetGestures.ts must not exceed MIN_RESERVE.+const MIN_RESERVE = 48;+// A finger can pull past the top by at most the viewport's height. The rubber+// band over a sheet as tall as the viewport then shows 35.5% of it.+const RESERVE_VIEWPORT_SHARE = 0.4;++function sheetReserve(viewportHeight: number): number {+ return Math.max(+ MIN_RESERVE,+ Math.ceil(viewportHeight * RESERVE_VIEWPORT_SHARE),+ );+}const MOBILE_KEYBOARD_BOTTOM_CLEARANCE = 48;const TRANSITION_BACKSTOP_BUFFER_MS = 50;// The floating handle bar's height. The bar is out of flow, so this is not@@ -92,6 +106,22 @@ const TRANSITION_BACKSTOP_BUFFER_MS = 50;// padding already provides.const HANDLE_BAR_HEIGHT = spacingVars['--spacing-6'];+const BLOCK_SIZE_PROPERTIES = [+ 'height',+ 'minHeight',+ 'maxHeight',+ 'blockSize',+ 'minBlockSize',+ 'maxBlockSize',+] as const;++/** Whether StyleX styles hold any style: they can nest in arrays. */+function hasStyles(xstyle: unknown): boolean {+ return Array.isArray(xstyle)+ ? xstyle.some(hasStyles)+ : xstyle != null && typeof xstyle === 'object';+}+// Measure the viewport that the height budgets use. They are `dvh`, which// the virtual keyboard does not shrink, so `visualViewport` would differ by// the keyboard's height. `useMobileKeyboard` handles the keyboard and does@@ -100,6 +130,14 @@ function layoutViewportHeight(): number {return typeof window === 'undefined' ? 0 : window.innerHeight;}+function subscribeToResize(onChange: () => void): () => void {+ return subscribeInput(window, 'resize', onChange);+}++function subscribeToNothing(): () => void {+ return () => {};+}+/*** 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.@@ -159,8 +197,8 @@ const styles = stylex.create({boxShadow: shadowVars['--shadow-high'],outline: 'none',overflow: 'hidden',- paddingBlockEnd: `calc(env(safe-area-inset-bottom, 0px) + ${OVERSCROLL_PADDING}px)`,- marginBlockEnd: `${-OVERSCROLL_PADDING}px`,+ paddingBlockEnd: `calc(env(safe-area-inset-bottom, 0px) + var(--_sheet-reserve, ${MIN_RESERVE}px))`,+ marginBlockEnd: `calc(-1 * var(--_sheet-reserve, ${MIN_RESERVE}px))`,// Under reduced motion no transform runs. On a coarse primary pointer the// entrance is an opacity cross-fade of at most 200 ms. A fine pointer gets// the change at once (the 0.01s collapse).@@ -340,11 +378,11 @@ const styles = stylex.create({},}),budget: {- height: `calc(var(--_sheet-budget) + ${OVERSCROLL_PADDING}px)`,+ height: `calc(var(--_sheet-budget) + var(--_sheet-reserve, ${MIN_RESERVE}px))`,},hugHeight: {height: 'fit-content',- maxHeight: `calc(${HEIGHT_BUDGETS.hug} + ${OVERSCROLL_PADDING}px)`,+ maxHeight: `calc(${HEIGHT_BUDGETS.hug} + var(--_sheet-reserve, ${MIN_RESERVE}px))`,},});@@ -649,6 +687,24 @@ export function BottomSheetPanel({// A caller's height owns the element's height: the drag never writes it.const consumerHeight = style?.height;+ // StyleX styles and a class name can size the sheet too. Their rules are+ // only class names here, so any of them counts as a size.+ const isSizedByCaller =+ BLOCK_SIZE_PROPERTIES.some(property => style?.[property] != null) ||+ hasStyles(xstyle) ||+ (className != null && className !== '');+ // Only a finger stretches the sheet past MIN_RESERVE, so a device with no+ // touch pointer keeps the smallest reserve. So does a sheet the caller+ // sizes, which nothing extends by the reserve; the stretch stops at it.+ const hasTouchPointer = useMediaQuery('(any-pointer: coarse)');+ const tracksViewport = isPresented && hasTouchPointer && !isSizedByCaller;+ const viewportHeight = useSyncExternalStore(+ tracksViewport ? subscribeToResize : subscribeToNothing,+ () => (tracksViewport ? layoutViewportHeight() : 0),+ () => 0,+ );+ const reserve =+ viewportHeight > 0 ? sheetReserve(viewportHeight) : MIN_RESERVE;const {contentProps,handleProps,@@ -668,7 +724,7 @@ export function BottomSheetPanel({isOpen: isInteractive,isOpenRequested: isOpenRequested ?? isInteractive,canDismiss: isSwipeDismissAllowed,- offscreenBlockEndInset: OVERSCROLL_PADDING,+ offscreenBlockEndInset: reserve,onDismiss,snapHeights,onTravelStart: () => {@@ -931,6 +987,7 @@ export function BottomSheetPanel({className,{['--_sheet-budget' as string]: budget,+ ['--_sheet-reserve' as string]: `${reserve}px`,...(isInteractive? gestureStyle: isRetained || isClosingdiff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.tsindex 29847c2958..5401d07331 100644--- a/packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.ts+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.ts@@ -9,7 +9,12 @@* @position Chromium proof for useSheetGestures' live transform path*/-import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';import {DEFAULT_STORYBOOK_DIR,serveStorybook,@@ -185,3 +190,142 @@ test('a drag writes the transform per move and renders nothing between', async (.toMatch(/^(none|matrix\(1, 0, 0, 1, 0, 0\))$/);await expect(page.getByRole('dialog', {name: 'Nearby places'})).toBeVisible();});++async function openStory(+ page: Page,+ story: string,+ opener: string,+ label: string,+) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-bottomsheet--${story}&viewMode=story`,+ );+ await page.getByRole('button', {name: opener}).click();+ const dialog = page.getByRole('dialog', {name: label});+ await expect(dialog).toBeVisible();+ const sheet = dialog.locator('.astryx-bottom-sheet').first();+ await expect(sheet).toBeVisible();+ await page.waitForTimeout(600); // the entrance+ return {dialog, sheet, rest: await topOf(sheet)};+}++async function topOf(sheet: Locator): Promise<number> {+ return sheet.evaluate(el => el.getBoundingClientRect().top);+}++/**+ * One finger pull of `distance` px up from `from`, held still before it lifts.+ * Returns how far above `rest` the sheet's top was during the hold, after the+ * sheet has come back to rest.+ */+async function pullUp(+ page: Page,+ sheet: Locator,+ rest: number,+ from: {x: number; y: number},+ distance: number,+): Promise<number> {+ const cdp = await page.context().newCDPSession(page);+ const steps = 12;+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [from],+ });+ for (let i = 1; i <= steps; i += 1) {+ await page.waitForTimeout(16);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{x: from.x, y: from.y - (distance * i) / steps}],+ });+ }+ await page.waitForTimeout(120);+ const stretch = rest - (await topOf(sheet));+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await expect+ .poll(async () => Math.abs((await topOf(sheet)) - rest), {timeout: 2_000})+ .toBeLessThan(0.5);+ await cdp.detach();+ return stretch;+}++test('a pull up on the body of a sheet whose content fits stretches it on every pull', async ({+ page,+}) => {+ const {dialog, sheet, rest} = await openStory(+ page,+ 'showcase',+ 'Open sheet',+ 'Filters',+ );+ const box = async (name: string) => {+ const found = await dialog+ .getByText(name, {exact: true})+ .first()+ .boundingBox();+ if (found == null) {+ throw new Error(`no box for ${name}`);+ }+ return found;+ };+ // Five places on the content, none on the grabber.+ const heading = await box('Filters');+ const inStock = await box('In stock');+ const onSale = await box('On sale');+ const freeShipping = await box('Free shipping');+ const points = [+ {x: heading.x + 10, y: heading.y + heading.height / 2},+ {x: inStock.x + inStock.width / 2, y: inStock.y + inStock.height / 2},+ {x: 300, y: onSale.y + onSale.height / 2},+ {x: freeShipping.x + 4, y: freeShipping.y + freeShipping.height / 2},+ {x: 195, y: freeShipping.y + freeShipping.height + 12},+ ];+ for (const point of points) {+ // The content does not scroll, so every pull stretches the sheet.+ expect(await pullUp(page, sheet, rest, point, 100)).toBeGreaterThan(20);+ }+ await expect(dialog).toBeVisible();+});++test('a long list scrolls to its end, then the sheet stretches with the rest of the pull', async ({+ page,+}) => {+ const {sheet, rest} = await openStory(+ page,+ 'snap-points',+ 'Open nearby places',+ 'Nearby places',+ );+ // The list rests 40 px short of its end.+ const max = await sheet.evaluate(el => {+ const list = [...el.querySelectorAll<HTMLElement>('*')].find(+ node =>+ node.scrollHeight > node.clientHeight + 1 &&+ /(auto|scroll)/.test(getComputedStyle(node).overflowY),+ );+ if (list == null) {+ throw new Error('no scrolling list');+ }+ list.dataset.c17List = '';+ list.scrollTop = list.scrollHeight - list.clientHeight - 40;+ return list.scrollHeight - list.clientHeight;+ });+ const list = sheet.locator('[data-c17-list]');+ const listBox = await list.boundingBox();+ if (listBox == null) {+ throw new Error('no list box');+ }+ const stretch = await pullUp(+ page,+ sheet,+ rest,+ {x: listBox.x + listBox.width / 2, y: listBox.y + listBox.height * 0.75},+ 200,+ );+ expect(await list.evaluate(el => el.scrollTop)).toBeGreaterThanOrEqual(+ max - 1,+ );+ expect(stretch).toBeGreaterThan(10);+});diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetPinchZoom.a11y.chromium.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetPinchZoom.a11y.chromium.spec.tsindex d962478aca..430f7f7d3a 100644--- a/packages/core/src/BottomSheet/__tests__/BottomSheetPinchZoom.a11y.chromium.spec.ts+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetPinchZoom.a11y.chromium.spec.ts@@ -230,7 +230,13 @@ test('one finger still drags the handle and scrolls the body, without zooming',await openSheet(page);const body = sheet.locator('[role="group"]').first();const before = await body.evaluate(el => el.scrollTop);- const startY = box.y + box.height - 100;+ // The sheet's box reaches below the screen, so start from the content's+ // visible end.+ const bodyBox = await body.boundingBox();+ if (bodyBox == null) {+ throw new Error('no body box');+ }+ const startY = bodyBox.y + bodyBox.height - 100;await cdp.send('Input.dispatchTouchEvent', {type: 'touchStart',touchPoints: [{x, y: startY}],diff --git a/packages/core/src/BottomSheet/useSheetGestures.test.ts b/packages/core/src/BottomSheet/useSheetGestures.test.tsindex e975e9626a..14278143d2 100644--- a/packages/core/src/BottomSheet/useSheetGestures.test.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.test.ts@@ -11,6 +11,7 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {act, renderHook} from '@testing-library/react';+import {rubberBand} from '../motion/rubberBand';import {isInsideNestedLayer,useSheetGestures,@@ -18,6 +19,9 @@ import {} from './useSheetGestures';const SHEET_HEIGHT = 400;+// A touch device's reserve below the screen, deeper than the whole band over+// the sheet's visible 240 px.+const TOUCH_RESERVE = 160;// A fake pointer event object good enough for the handlers, which only read// pointerId, clientY, timeStamp, preventDefault, and currentTarget's capture +@@ -29,11 +33,13 @@ function pointerEvent(pointerId = 1,button = 0,isPrimary = true,+ pointerType?: string,) {return {pointerId,button,isPrimary,+ pointerType,clientY,timeStamp,currentTarget: target,@@ -107,6 +113,34 @@ function up(hook: Hook, y: number, t: number, target: HTMLElement) {);}+// A handle pull of `pull` px up from y 400, held still, then lifted, by a+// pointer of `pointerType`. Returns the stretch at the hold.+function handlePull(+ hook: Hook,+ target: HTMLElement,+ pull: number,+ t0: number,+ pointerType: string,+): number {+ const event = (y: number, t: number) =>+ pointerEvent(y, t, target, 1, 0, true, pointerType);+ act(() => hook.result.current.sheetRef(target));+ act(() => hook.result.current.handleProps.onPointerDown(event(400, t0)));+ act(() =>+ hook.result.current.handleProps.onPointerMove(+ event(400 - pull / 2, t0 + 200),+ ),+ );+ act(() =>+ hook.result.current.handleProps.onPointerMove(event(400 - pull, t0 + 400)),+ );+ const stretch = -liveOffset(hook);+ act(() =>+ hook.result.current.handleProps.onPointerUp(event(400 - pull, t0 + 900)),+ );+ return stretch;+}+describe('isInsideNestedLayer', () => {it("is true for a target inside a <dialog> rendered within the body, and false for the body's own content", () => {const body = document.createElement('div');@@ -725,6 +759,49 @@ describe('useSheetGestures', () => {expect(off).toBeGreaterThan(-80); // resisted, so smaller in magnitude});+ it('stretches a finger pulling up past the top on the rubber band, the same on every pull, with no cap', () => {+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: TOUCH_RESERVE,+ });+ const t = makeTarget();+ const stretches = [0, 1, 2].map(i =>+ handlePull(hook, t, 300, i * 2000, 'touch'),+ );+ // The band runs over the sheet's visible height: 400 px less its reserve+ // below the screen.+ const expected = rubberBand(300, SHEET_HEIGHT - TOUCH_RESERVE);+ expect(expected).toBeGreaterThan(48);+ for (const stretch of stretches) {+ expect(stretch).toBeCloseTo(expected, 6);+ }+ expect(hook.result.current.settledOffset).toBe(0);+ });++ it('never stretches a finger past the reserve below the screen', () => {+ // A touch device's reserve covers the whole band. Where the reserve is+ // short, the stretch stops at it, so the page never shows.+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: 20,+ });+ const t = makeTarget();+ expect(rubberBand(1000, 380)).toBeGreaterThan(20);+ expect(handlePull(hook, t, 1000, 0, 'touch')).toBe(20);+ });++ it('keeps a mouse or a pen pulling up past the top on its own stretch, capped at 48 px', () => {+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: 48,+ });+ const t = makeTarget();+ expect(handlePull(hook, t, 80, 0, 'mouse')).toBeCloseTo(28, 6);+ expect(handlePull(hook, t, 300, 2000, 'mouse')).toBe(48);+ expect(handlePull(hook, t, 80, 4000, 'pen')).toBeCloseTo(28, 6);+ expect(handlePull(hook, t, 300, 6000, 'pen')).toBe(48);+ });+it('dismisses a single-height sheet on a slow drag past the floor', () => {const {hook, onDismiss} = setup(); // no snapHeightsconst t = makeTarget();@@ -840,17 +917,23 @@ describe('useSheetGestures', () => {document.body.appendChild(sheet);return el;}- function touch(el: HTMLElement, type: string, y: number, id = 1) {+ function touch(+ el: HTMLElement,+ type: string,+ y: number,+ id = 1,+ touchType = 'direct',+ ) {const ev = new Event(type, {bubbles: true, cancelable: true});// jsdom lacks TouchEvent; attach the fields the handler reads.Object.defineProperty(ev, 'changedTouches', {- value: [{identifier: id, clientY: y}],+ value: [{identifier: id, clientY: y, touchType}],});Object.defineProperty(ev, 'touches', {value:type === 'touchend' || type === 'touchcancel'? []- : [{identifier: id, clientY: y}],+ : [{identifier: id, clientY: y, touchType}],});Object.defineProperty(ev, 'currentTarget', {value: el});el.dispatchEvent(ev);@@ -899,11 +982,11 @@ describe('useSheetGestures', () => {expect(liveOffset(hook)).toBe(150);});- it('leaves a bottom pull-up with the scroller at the tallest detent', () => {- // Regression: the sheet is already fully expanded, so an upward pull has- // nowhere to expand to. Promoting it produced a rubber-band the release- // threw straight back, and stole the gesture from the scroller.- const {hook} = setup({snapHeights: () => [200]});+ it('stretches the sheet with a pull up past a list already at its end, at the tallest detent, without claiming the touch', () => {+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: TOUCH_RESERVE,+ });const el = makeScroller({scrollTop: 600,clientHeight: 200,@@ -913,12 +996,22 @@ describe('useSheetGestures', () => {act(() => hook.result.current.bodyProps.ref(el));expect(hook.result.current.settledOffset).toBe(0);+ let first: Event | undefined;+ let past: Event | undefined;act(() => {touch(el, 'touchstart', 300);- touch(el, 'touchmove', 250); // pull up+ first = touch(el, 'touchmove', 250); // the pull starts at the end+ past = touch(el, 'touchmove', 150);});- expect(hook.result.current.isDragging).toBe(false);- expect(hook.result.current.dragOffset).toBe(0);+ // The rest of the pull past the end stretches the sheet. The list keeps+ // its touch, so a reversal can scroll it back.+ expect(hook.result.current.isDragging).toBe(true);+ expect(-liveOffset(hook)).toBeCloseTo(+ rubberBand(100, SHEET_HEIGHT - TOUCH_RESERVE),+ 6,+ );+ expect(first?.defaultPrevented).toBe(false);+ expect(past?.defaultPrevented).toBe(false);});it('does not preventDefault a bottom pull-up at the tallest detent', () => {@@ -946,6 +1039,72 @@ describe('useSheetGestures', () => {expect(hook.result.current.isDragging).toBe(false);});+ it('stretches the sheet on every pull up at the tallest detent when its content fits', () => {+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: TOUCH_RESERVE,+ });+ // Nothing to scroll: the content fits its box.+ const el = makeScroller({+ scrollTop: 0,+ clientHeight: 200,+ scrollHeight: 200,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));+ expect(hook.result.current.settledOffset).toBe(0);+ for (let i = 0; i < 3; i += 1) {+ let pull: Event | undefined;+ act(() => {+ touch(el, 'touchstart', 300);+ touch(el, 'touchmove', 250);+ pull = touch(el, 'touchmove', 150);+ });+ // The content has no scroll to give the pull, so the sheet takes it.+ expect(pull?.defaultPrevented).toBe(true);+ // 150 px past the top, on the rubber band over the visible height.+ expect(-liveOffset(hook)).toBeCloseTo(+ rubberBand(150, SHEET_HEIGHT - TOUCH_RESERVE),+ 6,+ );+ act(() => {+ touch(el, 'touchend', 150);+ });+ expect(hook.result.current.isDragging).toBe(false);+ expect(hook.result.current.settledOffset).toBe(0);+ }+ });++ it("keeps a stylus pulling up on the body at the tallest detent on a pen's stretch, capped at 48 px", () => {+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: TOUCH_RESERVE,+ });+ const el = makeScroller({+ scrollTop: 0,+ clientHeight: 200,+ scrollHeight: 200,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));+ // An Apple Pencil raises touch events marked `stylus`.+ act(() => {+ touch(el, 'touchstart', 300, 1, 'stylus');+ touch(el, 'touchmove', 260, 1, 'stylus');+ touch(el, 'touchmove', 220, 1, 'stylus');+ });+ expect(-liveOffset(hook)).toBeCloseTo(28, 6);+ act(() => {+ touch(el, 'touchmove', 0, 1, 'stylus');+ });+ expect(-liveOffset(hook)).toBe(48);+ act(() => {+ touch(el, 'touchend', 0, 1, 'stylus');+ });+ expect(hook.result.current.isDragging).toBe(false);+ expect(hook.result.current.settledOffset).toBe(0);+ });+it('finishes the active drag when another ended touch is listed first', () => {const {hook} = setup({snapHeights: () => [200]});const el = makeScroller({@@ -1486,10 +1645,13 @@ describe('useSheetGestures', () => {expect(hook.result.current.settledOffset).toBe(200);});- it('leaves the mid-gesture pull to the content at the tallest detent', () => {- // Same #5161 rule as the touchstart-armed edge: with no taller detent- // there is nothing to expand into, so the scroller keeps the gesture.- const {hook} = setup({snapHeights: () => [200]});+ it("stretches the sheet with the rest of a pull past a long list's end at the tallest detent", () => {+ // The list scrolls to its end first. The rest of the pull stretches the+ // sheet, and the list keeps its touch.+ const {hook} = setup({+ snapHeights: () => [200],+ offscreenBlockEndInset: TOUCH_RESERVE,+ });const el = makeScroller({scrollTop: 300,clientHeight: 200,@@ -1506,11 +1668,65 @@ describe('useSheetGestures', () => {touch(el, 'touchmove', 200);past = touch(el, 'touchmove', 100);});- expect(hook.result.current.isDragging).toBe(false);- expect(hook.result.current.dragOffset).toBe(0);+ expect(hook.result.current.isDragging).toBe(true);+ expect(-liveOffset(hook)).toBeCloseTo(+ rubberBand(100, SHEET_HEIGHT - TOUCH_RESERVE),+ 6,+ );expect(past?.defaultPrevented).toBe(false);});+ it('holds a list still at its end while the sheet takes the rest of the pull, and lets it go on lift', () => {+ // iOS rubber-bands a scroller past its end, even under `contain`. The+ // list and the sheet must not both move.+ const {hook} = setup({snapHeights: () => [200]});+ const el = makeScroller({+ scrollTop: 300,+ clientHeight: 200,+ scrollHeight: 800,+ });+ act(() => hook.result.current.sheetRef(el));+ act(() => hook.result.current.bodyProps.ref(el));++ act(() => {+ touch(el, 'touchstart', 500);+ touch(el, 'touchmove', 400); // still scrolling+ });+ expect(el.style.overscrollBehaviorY).toBe('');++ act(() => {+ el.scrollTop = 600;+ touch(el, 'touchmove', 200); // the content ended here+ touch(el, 'touchmove', 100);+ });+ expect(hook.result.current.isDragging).toBe(true);+ expect(el.style.overscrollBehaviorY).toBe('none');++ act(() => {+ touch(el, 'touchend', 100);+ });+ expect(el.style.overscrollBehaviorY).toBe('');+ });++ it('lets the list go when the finger comes back to the content end', () => {+ const {hook} = setup({snapHeights: () => [200]});+ const el = midDetentScroller(hook, 300);+ act(() => {+ touch(el, 'touchstart', 500);+ el.scrollTop = 600;+ touch(el, 'touchmove', 200); // the content ended here+ touch(el, 'touchmove', 150);+ });+ expect(el.style.overscrollBehaviorY).toBe('none');++ act(() => {+ touch(el, 'touchmove', 210); // back below the anchor+ });+ // The list scrolls again from here, with its own bounce.+ expect(hook.result.current.isDragging).toBe(false);+ expect(el.style.overscrollBehaviorY).toBe('');+ });+it('does not hand off while the content can still scroll', () => {const {hook} = setup({snapHeights: () => [200]});const el = midDetentScroller(hook, 0);diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.tsindex 3efa88c583..6229653a0b 100644--- a/packages/core/src/BottomSheet/useSheetGestures.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.ts@@ -64,6 +64,8 @@ import {type UIEvent as ReactUIEvent,} from 'react';+import {rubberBand} from '../motion/rubberBand';+import {scroll} from '../motion/uikit/scroll';import {computeDetentOffsets,peekOffsetFor,@@ -112,12 +114,19 @@ function isSyntheticTouch(event: ReactPointerEvent): boolean {return (event as SyntheticTouchPointer).syntheticTouch === true;}-// 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).+type StylusTouch = Touch & {touchType?: string};++// An Apple Pencil raises touch events too, marked `stylus`. Its drag is a+// pen's, as on the grabber, where WebKit reports it as a pen.+function touchPointerType(touch: Touch): string {+ return (touch as StylusTouch).touchType === 'stylus' ? 'pen' : 'touch';+}++// A mouse's stretch past fully open: a resisted fraction of the drag, capped+// at OVERSCROLL_MAX.const OVERSCROLL_RESISTANCE = 0.35;-// 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.+// SYNC: must not exceed MIN_RESERVE in BottomSheetPanel.tsx, the smallest+// reserve the sheet keeps below the screen.const OVERSCROLL_MAX = 48;// Travel past the point where a scrolling gesture ran out of content before it// hands the sheet the rest of the pull. Small enough to feel continuous with@@ -308,6 +317,36 @@ function chainAtBottom(chain: ReadonlyArray<HTMLElement>): boolean {return chain.every(elementAtBottom);}+function chainScrolls(chain: ReadonlyArray<HTMLElement>): boolean {+ return chain.some(element => element.scrollHeight - element.clientHeight > 1);+}++/**+ * iOS rubber-bands a scroller past its end even under `overscroll-behavior:+ * contain`. While the content sits at its end mid-pull, `none` holds it still,+ * so only the sheet moves. Returns the undo.+ */+function holdAtEnd(chain: ReadonlyArray<HTMLElement>): () => void {+ const previous = chain.map(element => element.style.overscrollBehaviorY);+ for (const element of chain) {+ element.style.overscrollBehaviorY = 'none';+ }+ return () => {+ chain.forEach((element, index) => {+ element.style.overscrollBehaviorY = previous[index];+ });+ };+}++function releaseContentHold(+ armed: {releaseContentHold: (() => void) | null} | null,+): void {+ if (armed?.releaseContentHold != null) {+ armed.releaseContentHold();+ armed.releaseContentHold = null;+ }+}+function visibleHeightForOffset(sheetHeight: number,offset: number,@@ -690,6 +729,8 @@ export function useSheetGestures({samples: {t: number; y: number}[];velocity: number;height: number;+ /** The surface kept below the screen when the drag began. */+ reserve: number;baseOffset: number;baseLayoutOffset: number;renderedOffset: number;@@ -1171,7 +1212,7 @@ export function useSheetGestures({const baseLayoutOffset = settledLayoutOffsetRef.current;dragStateRef.current = {syntheticTouch,- pointerType: syntheticTouch ? 'touch' : event.pointerType,+ pointerType: event.pointerType,pointerId: event.pointerId,startCoord: start,lastCoord: event.clientY,@@ -1179,6 +1220,7 @@ export function useSheetGestures({samples: [{t: event.timeStamp, y: event.clientY}],velocity: 0,height: sheetHeight,+ reserve: offscreenBlockEndInsetRef.current,baseOffset: settledOffset,baseLayoutOffset,renderedOffset: settledOffset,@@ -1279,8 +1321,19 @@ export function useSheetGestures({const maxDetentOffset = offsets[offsets.length - 1];let next: number;if (raw < 0) {- // Up past fully-open: damped + capped rubber-band; springs back on release.- next = Math.max(-OVERSCROLL_MAX, raw * OVERSCROLL_RESISTANCE);+ // A touch device's reserve covers the whole stretch. The clamp binds+ // only where the reserve is short.+ next =+ state.pointerType === 'touch'+ ? Math.max(+ -state.reserve,+ rubberBand(+ raw,+ state.height - state.reserve,+ scroll.rubberBand.coefficient,+ ),+ )+ : Math.max(-OVERSCROLL_MAX, raw * OVERSCROLL_RESISTANCE);} else if (raw > maxDetentOffset) {// In the dismiss zone: no magnet, so it doesn't fight a drag-to-close.next = raw;@@ -1482,6 +1535,8 @@ export function useSheetGestures({// armed at `touchstart`. That drag never cancelled the native scroll, so// it has to yield again if the finger comes back down.promotedAtContentEnd: boolean;+ // Null while no hold is set.+ releaseContentHold: (() => void) | null;} | null>(null);const previousTouchHandlersRef = useRef<{start: (e: TouchEvent) => void;@@ -1495,6 +1550,7 @@ export function useSheetGestures({// the gesture; the sheet returns to its detent.const yieldToPinch = useCallback((target?: HTMLElement) => {+ releaseContentHold(touchDragRef.current);touchDragRef.current = null;armedBodyRef.current = null;cancelDrag(target);@@ -1522,6 +1578,7 @@ export function useSheetGestures({({syntheticTouch: true,pointerId: touch.identifier,+ pointerType: touchPointerType(touch),clientY: touch.clientY,timeStamp: Date.now(),currentTarget: target,@@ -1542,21 +1599,21 @@ export function useSheetGestures({// scroll, but it is tracked all the same: the scroller can run out of// content while the finger is still down (see onTouchMove). A touch// inside a layer this sheet hosts is that layer's, never tracked here.+ releaseContentHold(touchDragRef.current);if (!touch || isInsideNestedLayer(event.target, body)) {touchDragRef.current = null;return;}const scrollers = scrollChainUnder(event.target, body);const top = chainAtTop(scrollers);- // The bottom edge hands off so the sheet can EXPAND, so it is only a- // handoff when a taller detent exists. Already at the tallest, an- // upward pull has nowhere to travel: promoting it would trade the- // user's scroll for a rubber-band the release throws straight back, and- // — because promotion preventDefault()s the rest of the gesture — would- // strand the scroller for as long as the finger stays down, so reversing- // downward to scroll back would collapse the sheet instead. Leave the- // gesture with the content.- const bottom = chainAtBottom(scrollers) && activeOffsetRef.current > 0;+ // Claiming a pull up from its first move blocks the content's scroll for+ // the whole touch. So it is claimed here only below the tallest detent,+ // or over content that cannot scroll. At the tallest detent, a list at+ // its end keeps its touch. Its pull reaches the sheet through the+ // content-end hand-off below, and a reversal hands it back.+ const bottom =+ chainAtBottom(scrollers) &&+ (activeOffsetRef.current > 0 || !chainScrolls(scrollers));touchDragRef.current = {id: touch.identifier,startY: touch.clientY,@@ -1565,6 +1622,7 @@ export function useSheetGestures({bottom,contentEndY: null,promotedAtContentEnd: false,+ releaseContentHold: null,};};@@ -1594,6 +1652,7 @@ export function useSheetGestures({// at once; a later pull past the end promotes again.armed.contentEndY = null;armed.promotedAtContentEnd = false;+ releaseContentHold(armed);cancelDragRef.current(scroller);return;}@@ -1627,6 +1686,7 @@ export function useSheetGestures({chainAtBottom(armed.scrollers);if (pullDownAtTop || pullUpAtBottom) {event.preventDefault();+ releaseContentHold(armed);touchDragRef.current = null;beginDragRef.current(asPointer(t, scroller),@@ -1646,13 +1706,14 @@ export function useSheetGestures({// cannot see this, and re-arming for a preventDefault() promotion would// be useless anyway: once the browser has committed the gesture to// scrolling, every remaining touchmove is non-cancelable. Nothing needs- // cancelling either — the scroller is clamped at its maximum, so further- // upward travel scrolls nothing. Anchor at the point where the content+ // cancelling either: the hold clamps the scroller at its maximum, so+ // further upward travel scrolls nothing. Anchor at the point where the content// ran out and give the sheet everything past it, so the pull continues// into the sheet with no jump and no lost scrolling.- if (activeOffsetRef.current > 0 && chainAtBottom(armed.scrollers)) {+ if (chainAtBottom(armed.scrollers)) {if (armed.contentEndY == null) {armed.contentEndY = t.clientY;+ armed.releaseContentHold ??= holdAtEnd(armed.scrollers);} else if (armed.contentEndY - t.clientY >= CONTENT_END_HANDOFF_SLOP) {armed.promotedAtContentEnd = true;beginDragRef.current(@@ -1664,10 +1725,12 @@ export function useSheetGestures({}} else {armed.contentEndY = null;+ releaseContentHold(armed);}};const onTouchEnd = (event: TouchEvent) => {+ releaseContentHold(touchDragRef.current);touchDragRef.current = null;const pointerId = dragStateRef.current?.pointerId;if (pointerId == null) {