@astryxdesign/core 0.4.3 → 0.4.4-canary.0f4d45f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +79 -45
  3. package/dist/Banner/Banner.d.ts +3 -0
  4. package/dist/Banner/Banner.d.ts.map +1 -1
  5. package/dist/Banner/Banner.js +13 -3
  6. package/dist/BottomSheet/BottomSheet.d.ts +66 -0
  7. package/dist/BottomSheet/BottomSheet.d.ts.map +1 -0
  8. package/dist/BottomSheet/BottomSheet.js +392 -0
  9. package/dist/BottomSheet/BottomSheetPanel.d.ts +60 -0
  10. package/dist/BottomSheet/BottomSheetPanel.d.ts.map +1 -0
  11. package/dist/BottomSheet/BottomSheetPanel.js +398 -0
  12. package/dist/BottomSheet/BottomSheetSwitcher.d.ts +61 -0
  13. package/dist/BottomSheet/BottomSheetSwitcher.d.ts.map +1 -0
  14. package/dist/BottomSheet/BottomSheetSwitcher.js +410 -0
  15. package/dist/BottomSheet/BottomSheetSwitcherContext.d.ts +21 -0
  16. package/dist/BottomSheet/BottomSheetSwitcherContext.d.ts.map +1 -0
  17. package/dist/BottomSheet/BottomSheetSwitcherContext.js +13 -0
  18. package/dist/BottomSheet/index.d.ts +11 -0
  19. package/dist/BottomSheet/index.d.ts.map +1 -0
  20. package/dist/BottomSheet/index.js +12 -0
  21. package/dist/BottomSheet/snapOffsets.d.ts +72 -0
  22. package/dist/BottomSheet/snapOffsets.d.ts.map +1 -0
  23. package/dist/BottomSheet/snapOffsets.js +130 -0
  24. package/dist/BottomSheet/useMobileKeyboard.d.ts +35 -0
  25. package/dist/BottomSheet/useMobileKeyboard.d.ts.map +1 -0
  26. package/dist/BottomSheet/useMobileKeyboard.js +373 -0
  27. package/dist/BottomSheet/useSheetGestures.d.ts +180 -0
  28. package/dist/BottomSheet/useSheetGestures.d.ts.map +1 -0
  29. package/dist/BottomSheet/useSheetGestures.js +989 -0
  30. package/dist/Chat/ChatComposerInput.d.ts.map +1 -1
  31. package/dist/Chat/ChatComposerInput.js +3 -4
  32. package/dist/ComplexSelector/ComplexSelector.d.ts.map +1 -1
  33. package/dist/ComplexSelector/ComplexSelector.js +12 -6
  34. package/dist/ContextMenu/ContextMenu.d.ts.map +1 -1
  35. package/dist/ContextMenu/ContextMenu.js +4 -2
  36. package/dist/DateInput/DateInput.d.ts.map +1 -1
  37. package/dist/DateInput/DateInput.js +9 -1
  38. package/dist/DateTimeInput/DateTimeInput.d.ts.map +1 -1
  39. package/dist/DateTimeInput/DateTimeInput.js +31 -1
  40. package/dist/Dialog/Dialog.d.ts.map +1 -1
  41. package/dist/Dialog/Dialog.js +2 -1
  42. package/dist/Field/InputClearButton.d.ts +2 -1
  43. package/dist/Field/InputClearButton.d.ts.map +1 -1
  44. package/dist/Field/InputClearButton.js +6 -1
  45. package/dist/Lightbox/Lightbox.d.ts.map +1 -1
  46. package/dist/Lightbox/Lightbox.js +9 -3
  47. package/dist/MobileNav/MobileNav.d.ts +12 -0
  48. package/dist/MobileNav/MobileNav.d.ts.map +1 -1
  49. package/dist/MobileNav/MobileNav.js +102 -30
  50. package/dist/MultiSelector/MultiSelector.d.ts.map +1 -1
  51. package/dist/MultiSelector/MultiSelector.js +21 -7
  52. package/dist/NumberInput/NumberInput.d.ts.map +1 -1
  53. package/dist/NumberInput/NumberInput.js +9 -1
  54. package/dist/PowerSearch/PowerSearchEditPopover.js +1 -1
  55. package/dist/Selector/Selector.d.ts.map +1 -1
  56. package/dist/Selector/Selector.js +14 -3
  57. package/dist/StatusDot/StatusDot.d.ts +43 -3
  58. package/dist/StatusDot/StatusDot.d.ts.map +1 -1
  59. package/dist/StatusDot/StatusDot.js +42 -5
  60. package/dist/Switch/Switch.d.ts.map +1 -1
  61. package/dist/Switch/Switch.js +5 -1
  62. package/dist/Table/plugins/rowExpansion/useTableRowExpansion.d.ts.map +1 -1
  63. package/dist/Table/plugins/rowExpansion/useTableRowExpansion.js +7 -2
  64. package/dist/TimeInput/TimeInput.d.ts.map +1 -1
  65. package/dist/TimeInput/TimeInput.js +8 -1
  66. package/dist/Tokenizer/Tokenizer.js +11 -5
  67. package/dist/Tooltip/useTooltip.d.ts.map +1 -1
  68. package/dist/Tooltip/useTooltip.js +4 -1
  69. package/dist/Typeahead/BaseTypeahead.d.ts.map +1 -1
  70. package/dist/Typeahead/BaseTypeahead.js +5 -3
  71. package/dist/Typeahead/Typeahead.d.ts.map +1 -1
  72. package/dist/Typeahead/Typeahead.js +10 -1
  73. package/dist/astryx.css +21 -0
  74. package/dist/hooks/index.d.ts +8 -1
  75. package/dist/hooks/index.d.ts.map +1 -1
  76. package/dist/hooks/index.js +8 -1
  77. package/dist/hooks/useFocusTrap.d.ts +0 -11
  78. package/dist/hooks/useFocusTrap.d.ts.map +1 -1
  79. package/dist/hooks/useFocusTrap.js +1 -11
  80. package/dist/hooks/useInputStatusIcon.d.ts.map +1 -1
  81. package/dist/hooks/useInputStatusIcon.js +1 -0
  82. package/dist/index.d.ts +1 -0
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +1 -0
  85. package/dist/theme/defineTheme.d.ts +22 -4
  86. package/dist/theme/defineTheme.d.ts.map +1 -1
  87. package/dist/theme/expandColorScale.d.ts +17 -2
  88. package/dist/theme/expandColorScale.d.ts.map +1 -1
  89. package/dist/theme/expandColorScale.js +63 -33
  90. package/dist/utils/ime.d.ts +5 -0
  91. package/dist/utils/ime.d.ts.map +1 -0
  92. package/dist/utils/ime.js +63 -0
  93. package/dist/utils/index.d.ts +1 -0
  94. package/dist/utils/index.d.ts.map +1 -1
  95. package/dist/utils/index.js +2 -1
  96. package/locales/af-ZA.json +958 -0
  97. package/locales/ar-SA.json +998 -0
  98. package/locales/ca-ES.json +974 -0
  99. package/locales/cs-CZ.json +990 -0
  100. package/locales/da-DK.json +966 -0
  101. package/locales/de-DE.json +966 -0
  102. package/locales/el-GR.json +990 -0
  103. package/locales/en.json +48 -0
  104. package/locales/es-ES.json +978 -0
  105. package/locales/fi-FI.json +990 -0
  106. package/locales/fr-FR.json +928 -0
  107. package/locales/he-IL.json +990 -0
  108. package/locales/hu-HU.json +990 -0
  109. package/locales/it-IT.json +978 -0
  110. package/locales/ja-JP.json +998 -0
  111. package/locales/ko-KR.json +990 -0
  112. package/locales/nl-NL.json +954 -0
  113. package/locales/no-NO.json +978 -0
  114. package/locales/pl-PL.json +982 -0
  115. package/locales/pseudo.json +36 -0
  116. package/locales/pt-BR.json +982 -0
  117. package/locales/pt-PT.json +982 -0
  118. package/locales/ro-RO.json +982 -0
  119. package/locales/ru-RU.json +990 -0
  120. package/locales/sr-SP.json +990 -0
  121. package/locales/sv-SE.json +986 -0
  122. package/locales/tr-TR.json +990 -0
  123. package/locales/uk-UA.json +990 -0
  124. package/locales/vi-VN.json +986 -0
  125. package/locales/zh-CN.json +998 -0
  126. package/locales/zh-TW.json +998 -0
  127. package/package.json +9 -8
  128. package/src/Banner/Banner.doc.mjs +3 -3
  129. package/src/Banner/Banner.test.tsx +40 -0
  130. package/src/Banner/Banner.tsx +27 -2
  131. package/src/BottomSheet/BottomSheet.doc.mjs +266 -0
  132. package/src/BottomSheet/BottomSheet.test.tsx +2114 -0
  133. package/src/BottomSheet/BottomSheet.tsx +545 -0
  134. package/src/BottomSheet/BottomSheetPanel.test.tsx +240 -0
  135. package/src/BottomSheet/BottomSheetPanel.tsx +547 -0
  136. package/src/BottomSheet/BottomSheetSwitcher.doc.mjs +219 -0
  137. package/src/BottomSheet/BottomSheetSwitcher.test.tsx +850 -0
  138. package/src/BottomSheet/BottomSheetSwitcher.tsx +628 -0
  139. package/src/BottomSheet/BottomSheetSwitcherContext.ts +51 -0
  140. package/src/BottomSheet/index.ts +15 -0
  141. package/src/BottomSheet/snapOffsets.test.ts +187 -0
  142. package/src/BottomSheet/snapOffsets.ts +159 -0
  143. package/src/BottomSheet/useMobileKeyboard.ts +499 -0
  144. package/src/BottomSheet/useSheetGestures.test.ts +1059 -0
  145. package/src/BottomSheet/useSheetGestures.ts +1459 -0
  146. package/src/Chat/ChatComposerInput.tsx +3 -4
  147. package/src/ComplexSelector/ComplexSelector.tsx +12 -5
  148. package/src/ContextMenu/ContextMenu.tsx +4 -2
  149. package/src/DateInput/DateInput.test.tsx +21 -0
  150. package/src/DateInput/DateInput.tsx +9 -1
  151. package/src/DateTimeInput/DateTimeInput.doc.mjs +4 -0
  152. package/src/DateTimeInput/DateTimeInput.test.tsx +137 -0
  153. package/src/DateTimeInput/DateTimeInput.tsx +39 -2
  154. package/src/Dialog/Dialog.tsx +2 -1
  155. package/src/Field/Field.doc.mjs +1 -0
  156. package/src/Field/InputClearButton.test.tsx +25 -0
  157. package/src/Field/InputClearButton.tsx +4 -1
  158. package/src/FileInput/FileInput.test.tsx +53 -9
  159. package/src/Lightbox/Lightbox.test.tsx +49 -28
  160. package/src/Lightbox/Lightbox.tsx +7 -3
  161. package/src/MobileNav/MobileNav.tsx +128 -37
  162. package/src/MobileNav/MobileNavCloseEdgeCases.test.tsx +426 -0
  163. package/src/MobileNav/MobileNavCloseTiming.test.ts +58 -0
  164. package/src/MobileNav/MobileNavCloseVisibility.test.tsx +172 -0
  165. package/src/MultiSelector/MultiSelector.test.tsx +195 -51
  166. package/src/MultiSelector/MultiSelector.tsx +22 -8
  167. package/src/NumberInput/NumberInput.test.tsx +18 -0
  168. package/src/NumberInput/NumberInput.tsx +9 -1
  169. package/src/PowerSearch/PowerSearchEditPopover.tsx +1 -1
  170. package/src/Selector/Selector.test.tsx +85 -26
  171. package/src/Selector/Selector.tsx +13 -4
  172. package/src/StatusDot/StatusDot.doc.mjs +13 -0
  173. package/src/StatusDot/StatusDot.test.tsx +115 -8
  174. package/src/StatusDot/StatusDot.tsx +74 -9
  175. package/src/Switch/Switch.test.tsx +16 -0
  176. package/src/Switch/Switch.tsx +7 -0
  177. package/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx +20 -2
  178. package/src/TimeInput/TimeInput.test.tsx +23 -0
  179. package/src/TimeInput/TimeInput.tsx +8 -0
  180. package/src/Tokenizer/Tokenizer.test.tsx +50 -32
  181. package/src/Tokenizer/Tokenizer.tsx +5 -5
  182. package/src/Tooltip/useTooltip.tsx +4 -1
  183. package/src/Typeahead/BaseTypeahead.tsx +10 -3
  184. package/src/Typeahead/Typeahead.test.tsx +116 -7
  185. package/src/Typeahead/Typeahead.tsx +10 -1
  186. package/src/__tests__/stubMatchMedia.test.ts +79 -0
  187. package/src/__tests__/stubMatchMedia.ts +95 -0
  188. package/src/hooks/index.ts +9 -5
  189. package/src/hooks/useFocusTrap.ts +1 -14
  190. package/src/hooks/useInputStatusIcon.test.tsx +19 -0
  191. package/src/hooks/useInputStatusIcon.tsx +7 -0
  192. package/src/index.ts +1 -0
  193. package/src/theme/defineTheme.ts +22 -4
  194. package/src/theme/expandColorScale.test.ts +138 -0
  195. package/src/theme/expandColorScale.ts +89 -44
  196. package/src/utils/ime.test.ts +32 -0
  197. package/src/utils/ime.ts +69 -0
  198. package/src/utils/index.ts +2 -0
  199. package/dist/astryx.umd.js +0 -147
  200. package/dist/astryx.umd.js.map +0 -7
@@ -0,0 +1,1459 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ /**
6
+ * @file useSheetGestures.ts
7
+ * @input Uses React (useCallback, useEffect, useMemo, useRef, useState) and
8
+ * the core useMediaQuery hook
9
+ * @output Exports useSheetGestures hook and its option/result types
10
+ * @position Internal to BottomSheet; not exported from the core entry point
11
+ *
12
+ * Drag + snap machinery for the bottom sheet. Tracks a pointer drag down the
13
+ * block axis, translates the sliding surface live, and on release either
14
+ * settles to the nearest snap detent (a slow drag) or dismisses (a fast flick
15
+ * down). A fast flick up expands to the tallest detent. This is the core
16
+ * behavior split the sheet needs: DRAG places, SWIPE closes.
17
+ *
18
+ * A settled detent is split across two properties: `settledLayoutOffset` is
19
+ * the part the scrolling area gives up as layout height, and the remainder is
20
+ * a transform. Gestures and snaps only ever move the transform, so they stay
21
+ * on the compositor; layout height changes at rest, in one transition-free
22
+ * render whose visible geometry is identical. The peek detent keeps the full
23
+ * height and slides below the viewport instead of reflowing to a sliver.
24
+ *
25
+ * Those are pixels, and the detents behind them are viewport fractions, so a
26
+ * sheet at rest re-resolves its detent on `resize` / `orientationchange` and
27
+ * re-anchors to the new geometry without animating. The detent it returns to
28
+ * is tracked by index: the pixels stop meaning the same thing when the
29
+ * viewport changes, the stop the user chose does not.
30
+ *
31
+ * On touch, the scrolling body hands the gesture to the sheet at a scroll
32
+ * edge. Two shapes, because the browser only offers one of them a choice: a
33
+ * finger that lands on an edge and pulls away from it promotes by cancelling
34
+ * the first, still-cancelable touchmove; a finger that scrolls INTO the end of
35
+ * the content mid-gesture cannot, since the browser has committed the gesture
36
+ * to scrolling and every remaining event is non-cancelable. The second shape
37
+ * needs no cancelling — the scroller is clamped at its end, so there is
38
+ * nothing left to scroll — and instead anchors at the point where the content
39
+ * ran out and drives the sheet from the travel beyond it.
40
+ *
41
+ * Kept private to BottomSheet: a dismiss edge + detents on a bottom-anchored
42
+ * surface are inherently sheet concepts. It is not a general primitive and is
43
+ * intentionally not exported.
44
+ *
45
+ * SSR-safe: no window/document access at module scope; all measurement
46
+ * happens inside handlers. Respects prefers-reduced-motion by skipping the
47
+ * settle transition.
48
+ *
49
+ * SYNC: When modified, update these files to stay in sync:
50
+ * - /packages/core/src/BottomSheet/useSheetGestures.test.ts
51
+ */
52
+
53
+ import {
54
+ useCallback,
55
+ useEffect,
56
+ useLayoutEffect,
57
+ useMemo,
58
+ useRef,
59
+ useState,
60
+ type CSSProperties,
61
+ type MouseEvent as ReactMouseEvent,
62
+ type PointerEvent as ReactPointerEvent,
63
+ type RefObject,
64
+ type UIEvent as ReactUIEvent,
65
+ } from 'react';
66
+ import {useMediaQuery} from '../hooks';
67
+ import {
68
+ computeDetentOffsets,
69
+ isPeekOffset,
70
+ resolveSettleOffset,
71
+ scrimOpacityForOffset,
72
+ } from './snapOffsets';
73
+
74
+ // A flick (fast throw) dismisses (down) or expands (up) regardless of where
75
+ // it ends. Requires both a speed and a distance floor so a small nudge
76
+ // doesn't trigger it.
77
+ const FLICK_VELOCITY = 1.2; // px/ms
78
+ const FLICK_MIN_DISTANCE = 48; // px traveled during the gesture
79
+ // On a slow drag below the shortest detent, dismiss once dragged past it by
80
+ // more than this fraction of that detent's height; otherwise snap back to it.
81
+ const DISMISS_OVERSHOOT_RATIO = 0.4;
82
+ // Within this many px of a detent, the live drag is magnetically eased toward
83
+ // it so it "clicks" into place instead of hovering just off the mark.
84
+ const MAGNET_RANGE = 40;
85
+ // The touch path drives the sheet through the same machinery the pointer path
86
+ // uses, by handing it a pointer-shaped object built from a `Touch`. On iOS
87
+ // Safari that object is indistinguishable from the real thing: WebKit raises
88
+ // PointerEvents for a finger under the SAME numeric id it puts in
89
+ // `Touch.identifier`, so such a drag is keyed to a live pointer and the
90
+ // handlers that guard a mouse drag fire against it. Mark the synthetic object
91
+ // so they can tell the two apart.
92
+ type SyntheticTouchPointer = ReactPointerEvent & {syntheticTouch?: true};
93
+
94
+ function isSyntheticTouch(event: ReactPointerEvent): boolean {
95
+ return (event as SyntheticTouchPointer).syntheticTouch === true;
96
+ }
97
+
98
+ // Rubber-band factor for dragging up past fully-open, capped at OVERSCROLL_MAX
99
+ // (the sheet reserves that much bottom padding for the lift to reveal).
100
+ const OVERSCROLL_RESISTANCE = 0.35;
101
+ // SYNC: must match OVERSCROLL_PADDING in BottomSheetPanel.tsx (the reserved
102
+ // bottom padding the lift reveals). Kept as a local const rather than a shared
103
+ // import so it can be used inside stylex.create there.
104
+ const OVERSCROLL_MAX = 48;
105
+ // Travel past the point where a scrolling gesture ran out of content before it
106
+ // hands the sheet the rest of the pull. Small enough to feel continuous with
107
+ // the scroll, large enough that a swipe merely coming to rest on the last pixel
108
+ // doesn't start a drag on jitter.
109
+ const CONTENT_END_HANDOFF_SLOP = 4;
110
+
111
+ // Short haptic tick on detent settle where supported. iOS Safari doesn't
112
+ // expose navigator.vibrate, so this is a no-op there; skipped under
113
+ // reduced-motion.
114
+ function hapticTick(): void {
115
+ if (
116
+ typeof navigator === 'undefined' ||
117
+ typeof navigator.vibrate !== 'function'
118
+ ) {
119
+ return;
120
+ }
121
+ if (prefersReducedMotion()) {
122
+ return;
123
+ }
124
+ navigator.vibrate(8);
125
+ }
126
+
127
+ // Pull a value toward the nearest of `targets` when within MAGNET_RANGE, easing
128
+ // the last stretch so the surface settles crisply onto a detent while dragging.
129
+ function magnetize(value: number, targets: number[]): number {
130
+ let nearestTarget = targets[0];
131
+ let nearestDist = Math.abs(value - nearestTarget);
132
+ for (const t of targets) {
133
+ const d = Math.abs(value - t);
134
+ if (d < nearestDist) {
135
+ nearestDist = d;
136
+ nearestTarget = t;
137
+ }
138
+ }
139
+ if (nearestDist >= MAGNET_RANGE) {
140
+ return value;
141
+ }
142
+ // Ease-in over the range: pull grows as you approach (t^2), so the click
143
+ // feels magnetic near the detent but doesn't fight a deliberate drag-through.
144
+ const t = nearestDist / MAGNET_RANGE;
145
+ const pull = 1 - t * t;
146
+ return value + (nearestTarget - value) * pull;
147
+ }
148
+
149
+ function preservationInsetForOffset(
150
+ baseOffset: number,
151
+ targetOffset: number,
152
+ naturalEndGap: number,
153
+ ): number {
154
+ return Math.max(0, baseOffset - targetOffset - naturalEndGap);
155
+ }
156
+
157
+ function renderedBlockEndPadding(element: HTMLElement): number {
158
+ const value = Number.parseFloat(getComputedStyle(element).paddingBlockEnd);
159
+ return Number.isFinite(value) ? value : 0;
160
+ }
161
+
162
+ // How much further the body could scroll on its own, ignoring the padding the
163
+ // hook adds to preserve scroll position across a height change.
164
+ function naturalEndGapFor(body: HTMLElement | null): number {
165
+ if (!body) {
166
+ return 0;
167
+ }
168
+ const renderedInset = renderedBlockEndPadding(body);
169
+ const naturalMaxScrollTop = Math.max(
170
+ 0,
171
+ body.scrollHeight - body.clientHeight - renderedInset,
172
+ );
173
+ return naturalMaxScrollTop - body.scrollTop;
174
+ }
175
+
176
+ function visibleHeightForOffset(
177
+ sheetHeight: number,
178
+ offset: number,
179
+ offscreenBlockEndInset: number,
180
+ ): number {
181
+ return Math.max(0, sheetHeight - offscreenBlockEndInset - offset);
182
+ }
183
+
184
+ export interface UseSheetGesturesOptions {
185
+ /** Whether the owning sheet is open. Drag state resets when it closes. */
186
+ isOpen: boolean;
187
+ /**
188
+ * Whether a downward swipe may dismiss the sheet. When false, a gesture
189
+ * past the dismiss threshold settles at the shortest detent instead.
190
+ * @default true
191
+ */
192
+ canDismiss?: boolean;
193
+ /**
194
+ * Portion of the measured sheet border box reserved below the viewport.
195
+ * Excluded from detent heights so a 50vh snap has 50vh of visible sheet.
196
+ * @default 0
197
+ */
198
+ offscreenBlockEndInset?: number;
199
+ /** Called on a swipe-to-close (fast downward flick, or drag past the floor). */
200
+ onDismiss: () => void;
201
+ /**
202
+ * Resolver for candidate visible detent heights in px below the fully open
203
+ * visible height. Called at the start of each drag, and again whenever the
204
+ * viewport changes while the sheet rests, so the detents track the window
205
+ * (rotation, a resized desktop window, collapsing browser chrome). The fully
206
+ * open height is always the tallest detent. Omit for a single-height sheet
207
+ * (a drag then only dismisses or springs back).
208
+ */
209
+ snapHeights?: () => number[];
210
+ /** Notified when the settled visible detent height (px) changes. */
211
+ onSnap?: (heightPx: number) => void;
212
+ /**
213
+ * Called with the scrim opacity the sheet should show (1 = fully visible,
214
+ * 0 = hidden) as the drag moves and on settle. Full while the sheet is at
215
+ * or above its mid detent, fading to 0 as it collapses onto the shortest
216
+ * "peek" detent — thinning to a faint glance state without fully clearing — and
217
+ * on the dismiss overshoot. Lets the owner mirror it onto the scrim.
218
+ */
219
+ onScrimOpacity?: (opacity: number) => void;
220
+ }
221
+
222
+ export interface SheetContentProps {
223
+ style: CSSProperties;
224
+ }
225
+
226
+ export interface SheetHandleProps {
227
+ style: CSSProperties;
228
+ onContextMenu: (event: ReactMouseEvent) => void;
229
+ onLostPointerCapture: (event: ReactPointerEvent) => void;
230
+ onPointerDown: (event: ReactPointerEvent) => void;
231
+ onPointerMove: (event: ReactPointerEvent) => void;
232
+ onPointerUp: (event: ReactPointerEvent) => void;
233
+ onPointerCancel: (event: ReactPointerEvent) => void;
234
+ }
235
+
236
+ export interface SheetBodyProps {
237
+ ref: (node: HTMLElement | null) => void;
238
+ onContextMenu: (event: ReactMouseEvent) => void;
239
+ onLostPointerCapture: (event: ReactPointerEvent) => void;
240
+ onPointerDown: (event: ReactPointerEvent) => void;
241
+ onPointerMove: (event: ReactPointerEvent) => void;
242
+ onPointerUp: (event: ReactPointerEvent) => void;
243
+ onPointerCancel: (event: ReactPointerEvent) => void;
244
+ onScroll: (event: ReactUIEvent<HTMLElement>) => void;
245
+ }
246
+
247
+ export interface UseSheetGesturesResult {
248
+ /**
249
+ * Callback ref for the sheet surface. The hook observes it (ResizeObserver)
250
+ * to keep the fully-open height current, so detents stay correct across
251
+ * rotation / viewport changes without re-measuring mid-drag.
252
+ */
253
+ sheetRef: (node: HTMLElement | null) => void;
254
+ /** Spread on the sliding surface: live translate + touch-action guard. */
255
+ contentProps: SheetContentProps;
256
+ /** Spread on the grab-handle element: pointer drag handlers. */
257
+ handleProps: SheetHandleProps;
258
+ /**
259
+ * Spread on the scrollable body. An overscroll-at-top pull-down starts a
260
+ * sheet drag (a larger, more forgiving target when the content isn't itself
261
+ * scrolling); normal scrolling passes through untouched.
262
+ */
263
+ bodyProps: SheetBodyProps;
264
+ /**
265
+ * The body element `bodyProps.ref` is attached to. The hook tracks the node
266
+ * anyway (it owns the non-passive touch listeners on it), so a host that
267
+ * also needs the element reads it here rather than wrapping `bodyProps.ref`
268
+ * in a second callback ref.
269
+ */
270
+ bodyElementRef: RefObject<HTMLElement | null>;
271
+ /** Current live drag translate in px (0 = fully expanded, larger = collapsed). */
272
+ dragOffset: number;
273
+ /** Translate of the resting detent in px (0 = tallest detent). */
274
+ settledOffset: number;
275
+ /** Whether a drag is currently in progress. */
276
+ isDragging: boolean;
277
+ /** Measured height of the fully expanded sheet. */
278
+ sheetHeight: number;
279
+ /** End padding that preserves the scroll position across height changes. */
280
+ scrollPreservationInset: number;
281
+ /** Layout offset retained until the transform-only snap finishes. */
282
+ settlingLayoutOffset: number | null;
283
+ /**
284
+ * Reconciles the final layout once the transform-only snap finishes. The
285
+ * panel decides WHEN a snap is over (it owns the element and its computed
286
+ * transition), so completion cannot be driven from a `transitionend`
287
+ * listener alone: with transitions disabled — inline `transition: none`, a
288
+ * `0s` duration token, a test harness turning animation off — no event ever
289
+ * arrives and the scroll area would keep its full height forever.
290
+ */
291
+ completeScrollAreaSettle: () => void;
292
+ /**
293
+ * How much of `settledOffset` is expressed as layout height rather than as a
294
+ * transform. Equals `settledOffset` at the resizing detents; 0 at fully open
295
+ * and at the peek, which keep the sheet's full height (see isPeekOffset).
296
+ */
297
+ settledLayoutOffset: number;
298
+ }
299
+
300
+ function prefersReducedMotion(): boolean {
301
+ if (typeof window === 'undefined' || !window.matchMedia) {
302
+ return false;
303
+ }
304
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
305
+ }
306
+
307
+ /**
308
+ * Drag + snap machinery for the bottom sheet. Returns props to spread on the
309
+ * grab handle and the sliding surface, plus live drag state. A slow drag
310
+ * settles to the nearest detent; a fast downward flick dismisses; a fast
311
+ * upward flick expands to the tallest detent.
312
+ *
313
+ * @example
314
+ * ```
315
+ * const {contentProps, handleProps} = useSheetGestures({
316
+ * isOpen,
317
+ * onDismiss: () => onOpenChange(false),
318
+ * snapHeights: () => [240, 0.5 * (window.visualViewport?.height ?? 0)],
319
+ * });
320
+ * <div {...contentProps}>
321
+ * <div {...handleProps} />
322
+ * {children}
323
+ * </div>
324
+ * ```
325
+ */
326
+ export function useSheetGestures({
327
+ isOpen,
328
+ canDismiss = true,
329
+ offscreenBlockEndInset = 0,
330
+ onDismiss,
331
+ snapHeights,
332
+ onSnap,
333
+ onScrimOpacity,
334
+ }: UseSheetGesturesOptions): UseSheetGesturesResult {
335
+ const [dragOffset, setDragOffset] = useState(0);
336
+ const [settledOffset, setSettledOffset] = useState(0);
337
+ const [isDragging, setIsDragging] = useState(false);
338
+ const [sheetHeight, setSheetHeight] = useState(0);
339
+ const [scrollPreservationInset, setScrollPreservationInset] = useState(0);
340
+ // How much of the settled travel is expressed as layout height. Equal to
341
+ // settledOffset for the resizing detents, and 0 at fully open and at the
342
+ // peek (see isPeekOffset), which keep the full height and use a transform.
343
+ const [settledLayoutOffset, setSettledLayoutOffset] = useState(0);
344
+ const settledLayoutOffsetRef = useRef(0);
345
+ // WHICH detent the sheet rests on, as an index into the resolved list. The
346
+ // offsets themselves are pixels derived from the viewport, so they stop
347
+ // meaning the same thing the moment the viewport changes; the index survives
348
+ // that and lets a resize re-resolve the same stop against the new geometry.
349
+ const settledDetentIndexRef = useRef(0);
350
+ const [settlingLayoutOffset, setSettlingLayoutOffset] = useState<
351
+ number | null
352
+ >(null);
353
+ const [isScrollAreaReconciling, setIsScrollAreaReconciling] = useState(false);
354
+ const scrollPreservationInsetRef = useRef(0);
355
+ const settlingLayoutOffsetRef = useRef<number | null>(null);
356
+ const pendingScrollPreservationInsetRef = useRef<number | null>(null);
357
+ const offscreenBlockEndInsetRef = useRef(offscreenBlockEndInset);
358
+ offscreenBlockEndInsetRef.current = Math.max(0, offscreenBlockEndInset);
359
+ const recordSettledLayoutOffset = useCallback((offset: number) => {
360
+ const normalizedOffset = Math.max(0, offset);
361
+ settledLayoutOffsetRef.current = normalizedOffset;
362
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- layout offset is recorded from measurement effects
363
+ setSettledLayoutOffset(normalizedOffset);
364
+ }, []);
365
+ const updateScrollPreservationInset = useCallback((nextInset: number) => {
366
+ const normalizedInset = Math.max(0, nextInset);
367
+ const hasChanged =
368
+ Math.abs(normalizedInset - scrollPreservationInsetRef.current) > 0.5;
369
+ if (!hasChanged) {
370
+ return;
371
+ }
372
+ scrollPreservationInsetRef.current = normalizedInset;
373
+ setScrollPreservationInset(normalizedInset);
374
+ }, []);
375
+ const completeScrollAreaSettle = useCallback(() => {
376
+ // Resetting the transform at the same time as the final height swap must
377
+ // not start a second transition. The layouts have identical visible
378
+ // geometry, so reconcile them with transitions disabled for one frame.
379
+ setIsScrollAreaReconciling(true);
380
+ settlingLayoutOffsetRef.current = null;
381
+ setSettlingLayoutOffset(null);
382
+ const pendingInset = pendingScrollPreservationInsetRef.current;
383
+ pendingScrollPreservationInsetRef.current = null;
384
+ if (pendingInset != null) {
385
+ updateScrollPreservationInset(pendingInset);
386
+ }
387
+ }, [updateScrollPreservationInset]);
388
+ const prepareScrollAreaSettle = useCallback(
389
+ (
390
+ baseLayoutOffset: number,
391
+ targetOffset: number,
392
+ targetLayoutOffset: number,
393
+ renderedOffset: number,
394
+ layoutOffset: number,
395
+ naturalEndGap: number,
396
+ shouldAnimate: boolean,
397
+ ) => {
398
+ const targetInset = preservationInsetForOffset(
399
+ baseLayoutOffset,
400
+ targetLayoutOffset,
401
+ naturalEndGap,
402
+ );
403
+ if (
404
+ shouldAnimate &&
405
+ Math.abs(renderedOffset - targetOffset) > 0.5 &&
406
+ !prefersReducedMotion()
407
+ ) {
408
+ pendingScrollPreservationInsetRef.current = targetInset;
409
+ settlingLayoutOffsetRef.current = layoutOffset;
410
+ setSettlingLayoutOffset(layoutOffset);
411
+ return;
412
+ }
413
+ pendingScrollPreservationInsetRef.current = null;
414
+ settlingLayoutOffsetRef.current = null;
415
+ setSettlingLayoutOffset(null);
416
+ // Released on the detent, so there is no travel left to animate — but
417
+ // the layout split may still differ from the one the drag rendered
418
+ // with (magnetize() lands a slow drag exactly on a detent). Swapping
419
+ // height for transform is only invisible while transitions are off:
420
+ // with them live, the composited transform would animate the whole
421
+ // swap while the layout height jumped, throwing the sheet the wrong
422
+ // way. Reconcile in one transition-free frame instead.
423
+ setIsScrollAreaReconciling(
424
+ Math.abs(layoutOffset - targetLayoutOffset) > 0.5,
425
+ );
426
+ updateScrollPreservationInset(targetInset);
427
+ },
428
+ [updateScrollPreservationInset],
429
+ );
430
+ const activeOffsetRef = useRef(0);
431
+ activeOffsetRef.current = isDragging ? dragOffset : settledOffset;
432
+ const isOpenRef = useRef(isOpen);
433
+ isOpenRef.current = isOpen;
434
+
435
+ const onDismissRef = useRef(onDismiss);
436
+ const canDismissRef = useRef(canDismiss);
437
+ const onSnapRef = useRef(onSnap);
438
+ const onScrimOpacityRef = useRef(onScrimOpacity);
439
+ const snapHeightsRef = useRef(snapHeights);
440
+ useEffect(() => {
441
+ onDismissRef.current = onDismiss;
442
+ canDismissRef.current = canDismiss;
443
+ onSnapRef.current = onSnap;
444
+ onScrimOpacityRef.current = onScrimOpacity;
445
+ snapHeightsRef.current = snapHeights;
446
+ });
447
+
448
+ // Live drag bookkeeping (refs so pointermove doesn't churn renders).
449
+ const dragStateRef = useRef<{
450
+ // Whether the touch path drives this drag. Such a drag holds no pointer
451
+ // capture and takes its events from `touchmove`, so every real-pointer
452
+ // handler has to leave it alone.
453
+ syntheticTouch: boolean;
454
+ pointerId: number;
455
+ startCoord: number;
456
+ lastCoord: number;
457
+ lastTime: number;
458
+ velocity: number;
459
+ height: number;
460
+ baseOffset: number;
461
+ baseLayoutOffset: number;
462
+ renderedOffset: number;
463
+ layoutOffset: number;
464
+ naturalEndGap: number;
465
+ } | null>(null);
466
+
467
+ // Fully-open height, tracked by a ResizeObserver (see sheetRef) so detents
468
+ // stay correct across rotation / viewport changes without re-measuring.
469
+ const sheetHeightRef = useRef(0);
470
+ const sheetElRef = useRef<HTMLElement | null>(null);
471
+ const bodyNodeRef = useRef<HTMLElement | null>(null);
472
+ const observerRef = useRef<ResizeObserver | null>(null);
473
+ useLayoutEffect(() => {
474
+ if (!isScrollAreaReconciling) {
475
+ return;
476
+ }
477
+ // Force the transition-free transform reset to resolve before transitions
478
+ // are restored. Otherwise both DOM updates can be coalesced and the reset
479
+ // becomes an unintended fly-in animation from the bottom.
480
+ void sheetElRef.current?.offsetHeight;
481
+ const frame = requestAnimationFrame(() => {
482
+ setIsScrollAreaReconciling(false);
483
+ });
484
+ return () => cancelAnimationFrame(frame);
485
+ }, [isScrollAreaReconciling]);
486
+ const recordSheetHeight = useCallback((renderedHeight: number) => {
487
+ if (renderedHeight <= 0) {
488
+ return;
489
+ }
490
+ // A resized or closing panel's observer reports intermediate heights
491
+ // throughout its animation. Keep the last fully-expanded measurement
492
+ // instead of feeding those transient values back into the rendered height.
493
+ if (!isOpenRef.current || activeOffsetRef.current > 0) {
494
+ return;
495
+ }
496
+ sheetHeightRef.current = renderedHeight;
497
+ setSheetHeight(previousHeight =>
498
+ previousHeight === renderedHeight ? previousHeight : renderedHeight,
499
+ );
500
+ }, []);
501
+ const sheetRef = useCallback(
502
+ (node: HTMLElement | null) => {
503
+ observerRef.current?.disconnect();
504
+ observerRef.current = null;
505
+ sheetElRef.current = node;
506
+ if (!node || typeof ResizeObserver === 'undefined') {
507
+ if (node) {
508
+ recordSheetHeight(node.getBoundingClientRect().height);
509
+ }
510
+ return;
511
+ }
512
+ recordSheetHeight(node.getBoundingClientRect().height);
513
+ const ro = new ResizeObserver(entries => {
514
+ const entry = entries[0];
515
+ if (entry) {
516
+ // Keep this measurement in the same border-box coordinate space as
517
+ // getBoundingClientRect(). contentRect excludes the sheet's reserved
518
+ // bottom padding and would make the first resized drag jump shorter.
519
+ const borderBoxHeight = entry.borderBoxSize?.[0]?.blockSize;
520
+ recordSheetHeight(
521
+ borderBoxHeight ?? entry.target.getBoundingClientRect().height,
522
+ );
523
+ }
524
+ });
525
+ ro.observe(node);
526
+ observerRef.current = ro;
527
+ },
528
+ [recordSheetHeight],
529
+ );
530
+ useEffect(() => () => observerRef.current?.disconnect(), []);
531
+
532
+ // Reset to the tallest detent each time the sheet re-opens.
533
+ useEffect(() => {
534
+ if (isOpen) {
535
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
536
+ setDragOffset(0);
537
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
538
+ setSettledOffset(0);
539
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
540
+ setIsDragging(false);
541
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
542
+ setIsScrollAreaReconciling(false);
543
+ recordSettledLayoutOffset(0);
544
+ settledDetentIndexRef.current = 0;
545
+ scrollPreservationInsetRef.current = 0;
546
+ settlingLayoutOffsetRef.current = null;
547
+ pendingScrollPreservationInsetRef.current = null;
548
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
549
+ setScrollPreservationInset(0);
550
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
551
+ setSettlingLayoutOffset(null);
552
+ }
553
+ }, [isOpen, recordSettledLayoutOffset]);
554
+
555
+ // The fully-open height for detent math. Prefer the ResizeObserver-locked
556
+ // value; fall back to a live measure of the tracked sheet element if the
557
+ // observer hasn't reported yet.
558
+ const measureHeight = useCallback((): number => {
559
+ if (sheetHeightRef.current > 0) {
560
+ return sheetHeightRef.current;
561
+ }
562
+ return sheetElRef.current?.getBoundingClientRect().height ?? 0;
563
+ }, []);
564
+
565
+ // Detent translate offsets (px) from the tallest detent, ascending. Exclude
566
+ // the border-box portion reserved below the viewport before comparing the
567
+ // candidate visible heights; otherwise every snap point lands that many px
568
+ // too low. Snap heights are resolved lazily so they track the viewport.
569
+ const detentOffsets = useCallback((height: number): number[] => {
570
+ const visibleSheetHeight = visibleHeightForOffset(
571
+ height,
572
+ 0,
573
+ offscreenBlockEndInsetRef.current,
574
+ );
575
+ return computeDetentOffsets(
576
+ visibleSheetHeight,
577
+ snapHeightsRef.current?.() ?? [],
578
+ );
579
+ }, []);
580
+
581
+ // The height the sheet WOULD have fully open, right now. While it rests at a
582
+ // resizing detent the element carries a pixel height computed for whatever
583
+ // the viewport was then, so measuring it directly just reads that stale
584
+ // number back. Drop the inline height for the measurement and put it back in
585
+ // the same synchronous block — the browser cannot paint in between, so this
586
+ // is invisible — and the natural CSS budget is what gets measured.
587
+ const measureFullyOpenHeight = useCallback((): number => {
588
+ const element = sheetElRef.current;
589
+ if (!element) {
590
+ return sheetHeightRef.current;
591
+ }
592
+ const inlineHeight = element.style.height;
593
+ if (inlineHeight === '') {
594
+ return element.getBoundingClientRect().height;
595
+ }
596
+ element.style.height = '';
597
+ const height = element.getBoundingClientRect().height;
598
+ element.style.height = inlineHeight;
599
+ return height;
600
+ }, []);
601
+
602
+ // Detents are viewport fractions, but a settled sheet holds them as pixels:
603
+ // an offset to translate by, and a layout height to render. Both are read
604
+ // once, at gesture time. Without this, a viewport change leaves the sheet
605
+ // frozen at the old pixel geometry — a "half height" sheet showing 75% of a
606
+ // shorter window, a peek detent whose slide-down is taller than the whole
607
+ // window (so the sheet leaves the screen while its dialog stays modal), and
608
+ // a stale fully-open height for the next drag to overshoot past.
609
+ //
610
+ // Re-resolve the SAME detent — by index, the one thing that survives the
611
+ // units changing — against the new geometry, and re-anchor without
612
+ // animating: the viewport moved, not the user's finger, so there is no
613
+ // gesture to continue and nothing to ease.
614
+ useEffect(() => {
615
+ if (!isOpen || typeof window === 'undefined') {
616
+ return;
617
+ }
618
+ const handleViewportChange = () => {
619
+ // A live drag re-measures on its own, and a settle in flight owns the
620
+ // layout until it lands.
621
+ if (
622
+ dragStateRef.current != null ||
623
+ settlingLayoutOffsetRef.current != null
624
+ ) {
625
+ return;
626
+ }
627
+ const height = measureFullyOpenHeight();
628
+ if (height <= 0) {
629
+ return;
630
+ }
631
+ const offsets = detentOffsets(height);
632
+ const index = Math.min(settledDetentIndexRef.current, offsets.length - 1);
633
+ const target = offsets[index];
634
+ const targetLayoutOffset = isPeekOffset(target, offsets) ? 0 : target;
635
+ const baseLayoutOffset = settledLayoutOffsetRef.current;
636
+ if (
637
+ height === sheetHeightRef.current &&
638
+ Math.abs(target - activeOffsetRef.current) <= 0.5 &&
639
+ Math.abs(targetLayoutOffset - baseLayoutOffset) <= 0.5
640
+ ) {
641
+ return;
642
+ }
643
+
644
+ sheetHeightRef.current = height;
645
+ setSheetHeight(height);
646
+ settledDetentIndexRef.current = index;
647
+ prepareScrollAreaSettle(
648
+ baseLayoutOffset,
649
+ target,
650
+ targetLayoutOffset,
651
+ target,
652
+ baseLayoutOffset,
653
+ naturalEndGapFor(bodyNodeRef.current),
654
+ false,
655
+ );
656
+ recordSettledLayoutOffset(targetLayoutOffset);
657
+ setSettledOffset(target);
658
+ onSnapRef.current?.(
659
+ visibleHeightForOffset(
660
+ height,
661
+ target,
662
+ offscreenBlockEndInsetRef.current,
663
+ ),
664
+ );
665
+ const maxOffset = offsets[offsets.length - 1];
666
+ const shortestDetentHeight = visibleHeightForOffset(
667
+ height,
668
+ maxOffset,
669
+ offscreenBlockEndInsetRef.current,
670
+ );
671
+ onScrimOpacityRef.current?.(
672
+ scrimOpacityForOffset(
673
+ target,
674
+ offsets,
675
+ maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO,
676
+ ),
677
+ );
678
+ };
679
+ window.addEventListener('resize', handleViewportChange);
680
+ window.addEventListener('orientationchange', handleViewportChange);
681
+ return () => {
682
+ window.removeEventListener('resize', handleViewportChange);
683
+ window.removeEventListener('orientationchange', handleViewportChange);
684
+ };
685
+ }, [
686
+ detentOffsets,
687
+ isOpen,
688
+ measureFullyOpenHeight,
689
+ prepareScrollAreaSettle,
690
+ recordSettledLayoutOffset,
691
+ ]);
692
+
693
+ const cancelDrag = useCallback(
694
+ (target?: HTMLElement) => {
695
+ const state = dragStateRef.current;
696
+ if (state == null) {
697
+ return;
698
+ }
699
+
700
+ // Clear first: releasePointerCapture() may synchronously dispatch
701
+ // lostpointercapture, which must observe that this drag is already done.
702
+ dragStateRef.current = null;
703
+ if (target?.hasPointerCapture?.(state.pointerId)) {
704
+ target.releasePointerCapture(state.pointerId);
705
+ }
706
+ setDragOffset(state.baseOffset);
707
+ setIsDragging(false);
708
+ prepareScrollAreaSettle(
709
+ state.baseLayoutOffset,
710
+ state.baseOffset,
711
+ state.baseLayoutOffset,
712
+ state.renderedOffset,
713
+ state.layoutOffset,
714
+ state.naturalEndGap,
715
+ true,
716
+ );
717
+
718
+ // An interrupted drag returns to its previous resting detent. Restore
719
+ // the matching scrim opacity as well so the modal shell cannot remain
720
+ // dimmed with its sheet translated out of view.
721
+ const offsets = detentOffsets(state.height);
722
+ const maxOffset = offsets[offsets.length - 1];
723
+ const shortestDetentHeight = visibleHeightForOffset(
724
+ state.height,
725
+ maxOffset,
726
+ offscreenBlockEndInsetRef.current,
727
+ );
728
+ const dismissOffset =
729
+ maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
730
+ onScrimOpacityRef.current?.(
731
+ scrimOpacityForOffset(state.baseOffset, offsets, dismissOffset),
732
+ );
733
+ },
734
+ [detentOffsets, prepareScrollAreaSettle],
735
+ );
736
+
737
+ useEffect(() => {
738
+ const handleWindowBlur = () => cancelDrag();
739
+ const handleVisibilityChange = () => {
740
+ if (document.visibilityState === 'hidden') {
741
+ cancelDrag();
742
+ }
743
+ };
744
+ window.addEventListener('blur', handleWindowBlur);
745
+ document.addEventListener('visibilitychange', handleVisibilityChange);
746
+ return () => {
747
+ window.removeEventListener('blur', handleWindowBlur);
748
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
749
+ };
750
+ }, [cancelDrag]);
751
+
752
+ const settleFromDrag = useCallback(
753
+ (
754
+ offset: number,
755
+ velocity: number,
756
+ height: number,
757
+ dir: number,
758
+ travel: number,
759
+ baseOffset: number,
760
+ baseLayoutOffset: number,
761
+ renderedOffset: number,
762
+ layoutOffset: number,
763
+ naturalEndGap: number,
764
+ ) => {
765
+ const offsets = detentOffsets(height);
766
+ const maxOffset = offsets[offsets.length - 1];
767
+ const shortestDetentHeight = visibleHeightForOffset(
768
+ height,
769
+ maxOffset,
770
+ offscreenBlockEndInsetRef.current,
771
+ );
772
+ const speed = Math.abs(velocity);
773
+ const isFlick = speed > FLICK_VELOCITY && travel > FLICK_MIN_DISTANCE;
774
+ const settleAt = (target: number) => {
775
+ // A peek keeps the full layout height and slides below the viewport;
776
+ // every taller detent resizes the scrolling area to what it shows.
777
+ const targetLayoutOffset = isPeekOffset(target, offsets) ? 0 : target;
778
+ prepareScrollAreaSettle(
779
+ baseLayoutOffset,
780
+ target,
781
+ targetLayoutOffset,
782
+ renderedOffset,
783
+ layoutOffset,
784
+ naturalEndGap,
785
+ true,
786
+ );
787
+ recordSettledLayoutOffset(targetLayoutOffset);
788
+ settledDetentIndexRef.current = Math.max(0, offsets.indexOf(target));
789
+ setSettledOffset(target);
790
+ onSnapRef.current?.(
791
+ visibleHeightForOffset(
792
+ height,
793
+ target,
794
+ offscreenBlockEndInsetRef.current,
795
+ ),
796
+ );
797
+ const dismissOffset =
798
+ maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
799
+ onScrimOpacityRef.current?.(
800
+ scrimOpacityForOffset(target, offsets, dismissOffset),
801
+ );
802
+ if (target !== baseOffset) {
803
+ hapticTick();
804
+ }
805
+ };
806
+
807
+ if (dir > 0 && isFlick) {
808
+ if (canDismissRef.current) {
809
+ prepareScrollAreaSettle(
810
+ baseLayoutOffset,
811
+ baseOffset,
812
+ baseLayoutOffset,
813
+ baseLayoutOffset,
814
+ baseLayoutOffset,
815
+ naturalEndGap,
816
+ false,
817
+ );
818
+ onDismissRef.current();
819
+ } else {
820
+ settleAt(maxOffset);
821
+ }
822
+ return;
823
+ }
824
+ // Fast upward flick = expand to the tallest detent (the sheet's full
825
+ // provided height).
826
+ if (dir < 0 && isFlick) {
827
+ prepareScrollAreaSettle(
828
+ baseLayoutOffset,
829
+ 0,
830
+ 0,
831
+ renderedOffset,
832
+ layoutOffset,
833
+ naturalEndGap,
834
+ true,
835
+ );
836
+ recordSettledLayoutOffset(0);
837
+ settledDetentIndexRef.current = 0;
838
+ setDragOffset(0);
839
+ setSettledOffset(0);
840
+ onSnapRef.current?.(
841
+ visibleHeightForOffset(height, 0, offscreenBlockEndInsetRef.current),
842
+ );
843
+ onScrimOpacityRef.current?.(1);
844
+ hapticTick();
845
+ return;
846
+ }
847
+ if (offset > maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO) {
848
+ if (canDismissRef.current) {
849
+ prepareScrollAreaSettle(
850
+ baseLayoutOffset,
851
+ baseOffset,
852
+ baseLayoutOffset,
853
+ baseLayoutOffset,
854
+ baseLayoutOffset,
855
+ naturalEndGap,
856
+ false,
857
+ );
858
+ onDismissRef.current();
859
+ } else {
860
+ settleAt(maxOffset);
861
+ }
862
+ return;
863
+ }
864
+ // Settle to the nearest detent in the drag direction (never back past
865
+ // the starting detent), de-duped and direction-clamped by the util.
866
+ const target = resolveSettleOffset(offset, offsets, dir, baseOffset);
867
+ settleAt(target);
868
+ },
869
+ [detentOffsets, prepareScrollAreaSettle, recordSettledLayoutOffset],
870
+ );
871
+
872
+ const beginDrag = useCallback(
873
+ (event: ReactPointerEvent, sheetHeight: number, startCoord?: number) => {
874
+ const target = event.currentTarget as HTMLElement;
875
+ const syntheticTouch = isSyntheticTouch(event);
876
+ // Never capture for a touch drag. The id came from `Touch.identifier`,
877
+ // which on iOS names a live pointer: the capture succeeds, WebKit takes
878
+ // it straight back for its own gesture handling, and the
879
+ // `lostpointercapture` a millisecond later cancels the drag that just
880
+ // started. Touch drags need no capture — the listener is on the
881
+ // scroller itself.
882
+ if (!syntheticTouch) {
883
+ target.setPointerCapture?.(event.pointerId);
884
+ }
885
+ // `startCoord` lets a body-overscroll drag anchor at the original
886
+ // pointer-down position (not the promotion point), so the first frame's
887
+ // delta reflects the full pull distance.
888
+ const start = startCoord ?? event.clientY;
889
+ const naturalEndGap = naturalEndGapFor(bodyNodeRef.current);
890
+ const baseLayoutOffset = settledLayoutOffsetRef.current;
891
+ dragStateRef.current = {
892
+ syntheticTouch,
893
+ pointerId: event.pointerId,
894
+ startCoord: start,
895
+ lastCoord: event.clientY,
896
+ lastTime: event.timeStamp,
897
+ velocity: 0,
898
+ height: sheetHeight,
899
+ baseOffset: settledOffset,
900
+ baseLayoutOffset,
901
+ renderedOffset: settledOffset,
902
+ layoutOffset: baseLayoutOffset,
903
+ naturalEndGap,
904
+ };
905
+ updateScrollPreservationInset(
906
+ preservationInsetForOffset(
907
+ baseLayoutOffset,
908
+ baseLayoutOffset,
909
+ naturalEndGap,
910
+ ),
911
+ );
912
+ // Seed dragOffset at the resting detent so flipping isDragging doesn't
913
+ // jump the sheet to fully-open for one frame.
914
+ setDragOffset(settledOffset);
915
+ setIsDragging(true);
916
+ },
917
+ [settledOffset, updateScrollPreservationInset],
918
+ );
919
+
920
+ const handlePointerDown = useCallback(
921
+ (event: ReactPointerEvent) => {
922
+ if (event.button !== 0 || !event.isPrimary) {
923
+ return;
924
+ }
925
+ // The handle has no native focus action. Prevent pointer-down from
926
+ // moving focus off a form control on a tap; once the pointer actually
927
+ // moves, BottomSheet dismisses the keyboard as sheet travel begins.
928
+ event.preventDefault();
929
+ beginDrag(event, measureHeight());
930
+ },
931
+ [beginDrag, measureHeight],
932
+ );
933
+
934
+ const handleContextMenu = useCallback(
935
+ (event: ReactMouseEvent) => {
936
+ if (dragStateRef.current == null) {
937
+ return;
938
+ }
939
+ event.preventDefault();
940
+ cancelDrag(event.currentTarget as HTMLElement);
941
+ },
942
+ [cancelDrag],
943
+ );
944
+
945
+ const handleLostPointerCapture = useCallback(
946
+ (event: ReactPointerEvent) => {
947
+ // A touch drag never took capture, so this is WebKit reclaiming its own
948
+ // pointer for the finger doing the dragging — not the drag losing its
949
+ // grip.
950
+ if (dragStateRef.current?.syntheticTouch) {
951
+ return;
952
+ }
953
+ if (dragStateRef.current?.pointerId === event.pointerId) {
954
+ cancelDrag();
955
+ }
956
+ },
957
+ [cancelDrag],
958
+ );
959
+
960
+ const handlePointerMove = useCallback(
961
+ (event: ReactPointerEvent) => {
962
+ const state = dragStateRef.current;
963
+ if (!state || state.pointerId !== event.pointerId) {
964
+ return;
965
+ }
966
+ // Same finger, real pointer event: the touch path already drove this
967
+ // move. Let it own the drag rather than driving it twice.
968
+ if (state.syntheticTouch && !isSyntheticTouch(event)) {
969
+ return;
970
+ }
971
+ const delta = event.clientY - state.startCoord;
972
+ const dt = event.timeStamp - state.lastTime;
973
+ if (dt > 0) {
974
+ state.velocity = (event.clientY - state.lastCoord) / dt;
975
+ state.lastCoord = event.clientY;
976
+ state.lastTime = event.timeStamp;
977
+ }
978
+ const offsets = detentOffsets(state.height);
979
+
980
+ const raw = state.baseOffset + delta;
981
+ const maxDetentOffset = offsets[offsets.length - 1];
982
+ let next: number;
983
+ if (raw < 0) {
984
+ // Up past fully-open: damped + capped rubber-band; springs back on release.
985
+ next = Math.max(-OVERSCROLL_MAX, raw * OVERSCROLL_RESISTANCE);
986
+ } else if (raw > maxDetentOffset) {
987
+ // In the dismiss zone: no magnet, so it doesn't fight a drag-to-close.
988
+ next = raw;
989
+ } else {
990
+ // Between detents: magnetically ease toward a nearby one.
991
+ next = magnetize(raw, offsets);
992
+ }
993
+ // Dragging above the base restores the full layout height below the
994
+ // viewport; otherwise keep whatever layout the base detent settled with
995
+ // (0 at a peek, so a peek drag stays transform-only).
996
+ const layoutOffset = next < state.baseOffset ? 0 : state.baseLayoutOffset;
997
+ state.renderedOffset = next;
998
+ state.layoutOffset = layoutOffset;
999
+ setDragOffset(next);
1000
+ updateScrollPreservationInset(
1001
+ preservationInsetForOffset(
1002
+ state.baseLayoutOffset,
1003
+ layoutOffset,
1004
+ state.naturalEndGap,
1005
+ ),
1006
+ );
1007
+
1008
+ // Mirror the scrim to the live drag: full at/above the mid detent,
1009
+ // fading to hidden as it collapses onto the peek detent and through the
1010
+ // dismiss overshoot.
1011
+ const floorOffset = offsets[offsets.length - 1];
1012
+ const shortestDetentHeight = visibleHeightForOffset(
1013
+ state.height,
1014
+ floorOffset,
1015
+ offscreenBlockEndInsetRef.current,
1016
+ );
1017
+ const dismissOffset =
1018
+ floorOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
1019
+ onScrimOpacityRef.current?.(
1020
+ scrimOpacityForOffset(next, offsets, dismissOffset),
1021
+ );
1022
+ },
1023
+ [detentOffsets, updateScrollPreservationInset],
1024
+ );
1025
+
1026
+ const endDrag = useCallback(
1027
+ (event: ReactPointerEvent) => {
1028
+ const state = dragStateRef.current;
1029
+ if (!state || state.pointerId !== event.pointerId) {
1030
+ return;
1031
+ }
1032
+ // `pointercancel` fires for the finger the moment WebKit claims the
1033
+ // gesture; ending a touch drag on it settles the sheet mid-pull. The
1034
+ // touchend handler is what finishes a touch drag.
1035
+ if (state.syntheticTouch && !isSyntheticTouch(event)) {
1036
+ return;
1037
+ }
1038
+ const target = event.currentTarget as HTMLElement;
1039
+ const delta = event.clientY - state.startCoord;
1040
+ const offset = Math.max(0, state.baseOffset + delta);
1041
+ const dir = delta === 0 ? 0 : delta > 0 ? 1 : -1;
1042
+ dragStateRef.current = null;
1043
+ if (!state.syntheticTouch) {
1044
+ target.releasePointerCapture?.(event.pointerId);
1045
+ }
1046
+ setIsDragging(false);
1047
+ settleFromDrag(
1048
+ offset,
1049
+ state.velocity,
1050
+ state.height || 1,
1051
+ dir,
1052
+ Math.abs(delta),
1053
+ state.baseOffset,
1054
+ state.baseLayoutOffset,
1055
+ state.renderedOffset,
1056
+ state.layoutOffset,
1057
+ state.naturalEndGap,
1058
+ );
1059
+ },
1060
+ [settleFromDrag],
1061
+ );
1062
+
1063
+ // Pointer path for the body at-top pull-down (desktop / mouse). Touch uses
1064
+ // the non-passive listener below, since pointer events are cancelled once a
1065
+ // native pan starts.
1066
+ const armedBodyRef = useRef<{
1067
+ pointerId: number;
1068
+ startCoord: number;
1069
+ scroller: HTMLElement;
1070
+ } | null>(null);
1071
+
1072
+ const handleBodyPointerDown = useCallback((event: ReactPointerEvent) => {
1073
+ if (event.button !== 0 || !event.isPrimary) {
1074
+ return;
1075
+ }
1076
+ const scroller = event.currentTarget as HTMLElement;
1077
+ if (scroller.scrollTop > 0) {
1078
+ armedBodyRef.current = null;
1079
+ return;
1080
+ }
1081
+ armedBodyRef.current = {
1082
+ pointerId: event.pointerId,
1083
+ startCoord: event.clientY,
1084
+ scroller,
1085
+ };
1086
+ }, []);
1087
+
1088
+ const handleBodyPointerMove = useCallback(
1089
+ (event: ReactPointerEvent) => {
1090
+ if (dragStateRef.current) {
1091
+ handlePointerMove(event);
1092
+ return;
1093
+ }
1094
+ const armed = armedBodyRef.current;
1095
+ if (!armed || armed.pointerId !== event.pointerId) {
1096
+ return;
1097
+ }
1098
+ const delta = event.clientY - armed.startCoord;
1099
+ if (delta > 0 && armed.scroller.scrollTop <= 0) {
1100
+ // Downward pull at the top: promote to a sheet drag, anchored at the
1101
+ // original pointer-down position so the pull distance carries over.
1102
+ armedBodyRef.current = null;
1103
+ beginDrag(event, measureHeight(), armed.startCoord);
1104
+ handlePointerMove(event);
1105
+ } else if (delta < 0) {
1106
+ // Upward move = the user is scrolling; disarm so we don't hijack it.
1107
+ armedBodyRef.current = null;
1108
+ }
1109
+ },
1110
+ [beginDrag, handlePointerMove, measureHeight],
1111
+ );
1112
+
1113
+ const handleBodyEnd = useCallback(
1114
+ (event: ReactPointerEvent) => {
1115
+ armedBodyRef.current = null;
1116
+ // The pointerup/pointercancel for a finger already driving a touch drag
1117
+ // arrives here carrying that drag's own id; touchend ends those.
1118
+ if (dragStateRef.current?.syntheticTouch) {
1119
+ return;
1120
+ }
1121
+ if (dragStateRef.current) {
1122
+ endDrag(event);
1123
+ }
1124
+ },
1125
+ [endDrag],
1126
+ );
1127
+
1128
+ // Non-passive touchmove is the reliable scroll<->drag handoff on touch:
1129
+ // preventDefault() at a scroll edge stops the native scroll and drives the
1130
+ // sheet drag through the pointer math (Touch adapted to the fields it reads).
1131
+ //
1132
+ // Every touch on the body is tracked, not only the ones that begin at an
1133
+ // edge: a gesture that starts mid-content and scrolls to the end has to hand
1134
+ // off too, and by then it is far too late to arm from `touchstart`.
1135
+ const touchDragRef = useRef<{
1136
+ id: number;
1137
+ startY: number;
1138
+ top: boolean;
1139
+ bottom: boolean;
1140
+ // Where the finger was when the scroller ran out of content, or null while
1141
+ // it can still scroll. A mid-gesture handoff drives the sheet from travel
1142
+ // BEYOND this point, so the part of the swipe that legitimately scrolled
1143
+ // doesn't move the sheet as well.
1144
+ contentEndY: number | null;
1145
+ // Whether the drag in flight was promoted from `contentEndY` rather than
1146
+ // armed at `touchstart`. That drag never cancelled the native scroll, so
1147
+ // it has to yield again if the finger comes back down.
1148
+ promotedAtContentEnd: boolean;
1149
+ } | null>(null);
1150
+ const previousTouchHandlersRef = useRef<{
1151
+ start: (e: TouchEvent) => void;
1152
+ move: (e: TouchEvent) => void;
1153
+ end: (e: TouchEvent) => void;
1154
+ } | null>(null);
1155
+
1156
+ const beginDragRef = useRef(beginDrag);
1157
+ const cancelDragRef = useRef(cancelDrag);
1158
+ const pointerMoveRef = useRef(handlePointerMove);
1159
+ const endDragRef = useRef(endDrag);
1160
+ const measureHeightRef = useRef(measureHeight);
1161
+ useEffect(() => {
1162
+ beginDragRef.current = beginDrag;
1163
+ cancelDragRef.current = cancelDrag;
1164
+ pointerMoveRef.current = handlePointerMove;
1165
+ endDragRef.current = endDrag;
1166
+ measureHeightRef.current = measureHeight;
1167
+ });
1168
+
1169
+ const bodyRef = useCallback((node: HTMLElement | null) => {
1170
+ const asPointer = (touch: Touch, target: HTMLElement) =>
1171
+ ({
1172
+ syntheticTouch: true,
1173
+ pointerId: touch.identifier,
1174
+ clientY: touch.clientY,
1175
+ timeStamp: Date.now(),
1176
+ currentTarget: target,
1177
+ setPointerCapture: () => {},
1178
+ releasePointerCapture: () => {},
1179
+ }) as unknown as ReactPointerEvent;
1180
+
1181
+ const atTop = (el: HTMLElement) => el.scrollTop <= 0;
1182
+ const atBottom = (el: HTMLElement) =>
1183
+ el.scrollTop + el.clientHeight >= el.scrollHeight - 1;
1184
+
1185
+ const onTouchStart = (event: TouchEvent) => {
1186
+ const scroller = event.currentTarget as HTMLElement;
1187
+ const touch = event.changedTouches[0];
1188
+ // Record where the gesture began and whether it began at a scroll edge.
1189
+ // At the top, a pull DOWN hands off (collapse); at the bottom, a pull UP
1190
+ // hands off (expand). A gesture that starts mid-content is an ordinary
1191
+ // scroll, but it is tracked all the same: the scroller can run out of
1192
+ // content while the finger is still down (see onTouchMove).
1193
+ if (!touch) {
1194
+ touchDragRef.current = null;
1195
+ return;
1196
+ }
1197
+ const top = atTop(scroller);
1198
+ // The bottom edge hands off so the sheet can EXPAND, so it is only a
1199
+ // handoff when a taller detent exists. Already at the tallest, an
1200
+ // upward pull has nowhere to travel: promoting it would trade the
1201
+ // user's scroll for a rubber-band the release throws straight back, and
1202
+ // — because promotion preventDefault()s the rest of the gesture — would
1203
+ // strand the scroller for as long as the finger stays down, so reversing
1204
+ // downward to scroll back would collapse the sheet instead. Leave the
1205
+ // gesture with the content.
1206
+ const bottom = atBottom(scroller) && activeOffsetRef.current > 0;
1207
+ touchDragRef.current = {
1208
+ id: touch.identifier,
1209
+ startY: touch.clientY,
1210
+ top,
1211
+ bottom,
1212
+ contentEndY: null,
1213
+ promotedAtContentEnd: false,
1214
+ };
1215
+ };
1216
+
1217
+ const onTouchMove = (event: TouchEvent) => {
1218
+ const scroller = event.currentTarget as HTMLElement;
1219
+ const armed = touchDragRef.current;
1220
+ if (dragStateRef.current) {
1221
+ const t = [...event.changedTouches].find(
1222
+ x => x.identifier === dragStateRef.current?.pointerId,
1223
+ );
1224
+ if (!t) {
1225
+ return;
1226
+ }
1227
+ if (armed?.promotedAtContentEnd && armed.contentEndY != null) {
1228
+ if (t.clientY >= armed.contentEndY) {
1229
+ // Back at the point where the content ran out. This drag never
1230
+ // cancelled the native scroll — it couldn't, the events were no
1231
+ // longer cancelable — so the scroller is about to move again. Hand
1232
+ // the gesture back rather than driving the sheet and the content
1233
+ // at once; a later pull past the end promotes again.
1234
+ armed.contentEndY = null;
1235
+ armed.promotedAtContentEnd = false;
1236
+ cancelDragRef.current(scroller);
1237
+ return;
1238
+ }
1239
+ // Deliberately NOT preventDefault()ed: the scroller is clamped at
1240
+ // its end, so there is no scrolling left to cancel, and claiming the
1241
+ // gesture would strand the content for as long as the finger is down.
1242
+ pointerMoveRef.current(asPointer(t, scroller));
1243
+ return;
1244
+ }
1245
+ event.preventDefault();
1246
+ pointerMoveRef.current(asPointer(t, scroller));
1247
+ return;
1248
+ }
1249
+ if (!armed) {
1250
+ return;
1251
+ }
1252
+ const t = [...event.changedTouches].find(x => x.identifier === armed.id);
1253
+ if (!t) {
1254
+ return;
1255
+ }
1256
+ const delta = t.clientY - armed.startY;
1257
+ // Promote to a sheet drag on a pull that opposes the armed edge and can
1258
+ // no longer scroll that way: at the top, a downward pull (delta > 0)
1259
+ // collapses; at the bottom, an upward pull (delta < 0) expands. The
1260
+ // opposite direction is a real scroll, so disarm and let it through.
1261
+ const pullDownAtTop = armed.top && delta > 0 && atTop(scroller);
1262
+ const pullUpAtBottom = armed.bottom && delta < 0 && atBottom(scroller);
1263
+ if (pullDownAtTop || pullUpAtBottom) {
1264
+ event.preventDefault();
1265
+ touchDragRef.current = null;
1266
+ beginDragRef.current(
1267
+ asPointer(t, scroller),
1268
+ measureHeightRef.current(),
1269
+ armed.startY,
1270
+ );
1271
+ pointerMoveRef.current(asPointer(t, scroller));
1272
+ return;
1273
+ }
1274
+ if ((armed.top && delta < 0) || (armed.bottom && delta > 0)) {
1275
+ // Scrolling away from the armed edge; hand back to native scroll. The
1276
+ // touch stays tracked: this is the swipe that may reach the far edge.
1277
+ armed.top = false;
1278
+ armed.bottom = false;
1279
+ }
1280
+ // Reaching the end of the content mid-gesture. Arming at `touchstart`
1281
+ // cannot see this, and re-arming for a preventDefault() promotion would
1282
+ // be useless anyway: once the browser has committed the gesture to
1283
+ // scrolling, every remaining touchmove is non-cancelable. Nothing needs
1284
+ // cancelling either — the scroller is clamped at its maximum, so further
1285
+ // upward travel scrolls nothing. Anchor at the point where the content
1286
+ // ran out and give the sheet everything past it, so the pull continues
1287
+ // into the sheet with no jump and no lost scrolling.
1288
+ if (activeOffsetRef.current > 0 && atBottom(scroller)) {
1289
+ if (armed.contentEndY == null) {
1290
+ armed.contentEndY = t.clientY;
1291
+ } else if (armed.contentEndY - t.clientY >= CONTENT_END_HANDOFF_SLOP) {
1292
+ armed.promotedAtContentEnd = true;
1293
+ beginDragRef.current(
1294
+ asPointer(t, scroller),
1295
+ measureHeightRef.current(),
1296
+ armed.contentEndY,
1297
+ );
1298
+ pointerMoveRef.current(asPointer(t, scroller));
1299
+ }
1300
+ } else {
1301
+ armed.contentEndY = null;
1302
+ }
1303
+ };
1304
+
1305
+ const onTouchEnd = (event: TouchEvent) => {
1306
+ touchDragRef.current = null;
1307
+ const pointerId = dragStateRef.current?.pointerId;
1308
+ if (pointerId == null) {
1309
+ return;
1310
+ }
1311
+ const t = [...event.changedTouches].find(
1312
+ touch => touch.identifier === pointerId,
1313
+ );
1314
+ const target = event.currentTarget as HTMLElement;
1315
+ if (t) {
1316
+ endDragRef.current(asPointer(t, target));
1317
+ } else if (event.touches.length === 0) {
1318
+ // Some interrupted multi-touch sequences omit the active touch from
1319
+ // changedTouches. If no fingers remain, the drag cannot finish later.
1320
+ cancelDragRef.current(target);
1321
+ }
1322
+ };
1323
+
1324
+ const prev = bodyNodeRef.current;
1325
+ if (prev && previousTouchHandlersRef.current) {
1326
+ const h = previousTouchHandlersRef.current;
1327
+ prev.removeEventListener('touchstart', h.start);
1328
+ prev.removeEventListener('touchmove', h.move);
1329
+ prev.removeEventListener('touchend', h.end);
1330
+ prev.removeEventListener('touchcancel', h.end);
1331
+ }
1332
+ bodyNodeRef.current = node;
1333
+ if (node) {
1334
+ node.addEventListener('touchstart', onTouchStart, {passive: true});
1335
+ node.addEventListener('touchmove', onTouchMove, {passive: false});
1336
+ node.addEventListener('touchend', onTouchEnd, {passive: true});
1337
+ node.addEventListener('touchcancel', onTouchEnd, {passive: true});
1338
+ previousTouchHandlersRef.current = {
1339
+ start: onTouchStart,
1340
+ move: onTouchMove,
1341
+ end: onTouchEnd,
1342
+ };
1343
+ } else {
1344
+ previousTouchHandlersRef.current = null;
1345
+ }
1346
+ }, []);
1347
+
1348
+ // Subscribed, not memoized: the preference can change while a sheet is open,
1349
+ // and this branch decides whether the settle runs as a transition at all.
1350
+ // The imperative gesture paths read prefersReducedMotion() directly.
1351
+ const reducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
1352
+
1353
+ const reconcileScrollPreservationInset = useCallback(
1354
+ (body: HTMLElement) => {
1355
+ if (scrollPreservationInsetRef.current <= 0) {
1356
+ return;
1357
+ }
1358
+ const renderedInset = renderedBlockEndPadding(body);
1359
+ const naturalMaxScrollTop = Math.max(
1360
+ 0,
1361
+ body.scrollHeight - body.clientHeight - renderedInset,
1362
+ );
1363
+ const requiredInset = Math.max(0, body.scrollTop - naturalMaxScrollTop);
1364
+ if (requiredInset < scrollPreservationInsetRef.current - 0.5) {
1365
+ updateScrollPreservationInset(requiredInset);
1366
+ }
1367
+ },
1368
+ [updateScrollPreservationInset],
1369
+ );
1370
+
1371
+ const handleBodyScroll = useCallback(
1372
+ (event: ReactUIEvent<HTMLElement>) => {
1373
+ if (
1374
+ dragStateRef.current != null ||
1375
+ settlingLayoutOffsetRef.current != null
1376
+ ) {
1377
+ return;
1378
+ }
1379
+ reconcileScrollPreservationInset(event.currentTarget);
1380
+ },
1381
+ [reconcileScrollPreservationInset],
1382
+ );
1383
+
1384
+ // While dragging, follow the finger; otherwise rest at the settled detent.
1385
+ const activeOffset = isDragging ? dragOffset : settledOffset;
1386
+
1387
+ const contentProps = useMemo<SheetContentProps>(
1388
+ () => ({
1389
+ style: {
1390
+ transform:
1391
+ activeOffset !== 0 ? `translateY(${activeOffset}px)` : undefined,
1392
+ transition:
1393
+ isDragging || isScrollAreaReconciling || reducedMotion
1394
+ ? 'none'
1395
+ : undefined,
1396
+ touchAction: 'none',
1397
+ overscrollBehavior: 'contain',
1398
+ },
1399
+ }),
1400
+ [activeOffset, isDragging, isScrollAreaReconciling, reducedMotion],
1401
+ );
1402
+
1403
+ const handleProps = useMemo<SheetHandleProps>(
1404
+ () => ({
1405
+ style: {touchAction: 'none', cursor: 'grab'},
1406
+ onContextMenu: handleContextMenu,
1407
+ onLostPointerCapture: handleLostPointerCapture,
1408
+ onPointerDown: handlePointerDown,
1409
+ onPointerMove: handlePointerMove,
1410
+ onPointerUp: endDrag,
1411
+ onPointerCancel: endDrag,
1412
+ }),
1413
+ [
1414
+ endDrag,
1415
+ handleContextMenu,
1416
+ handleLostPointerCapture,
1417
+ handlePointerDown,
1418
+ handlePointerMove,
1419
+ ],
1420
+ );
1421
+
1422
+ const bodyProps = useMemo<SheetBodyProps>(
1423
+ () => ({
1424
+ ref: bodyRef,
1425
+ onContextMenu: handleContextMenu,
1426
+ onLostPointerCapture: handleLostPointerCapture,
1427
+ onPointerDown: handleBodyPointerDown,
1428
+ onPointerMove: handleBodyPointerMove,
1429
+ onPointerUp: handleBodyEnd,
1430
+ onPointerCancel: handleBodyEnd,
1431
+ onScroll: handleBodyScroll,
1432
+ }),
1433
+ [
1434
+ bodyRef,
1435
+ handleBodyEnd,
1436
+ handleBodyPointerDown,
1437
+ handleBodyPointerMove,
1438
+ handleBodyScroll,
1439
+ handleContextMenu,
1440
+ handleLostPointerCapture,
1441
+ ],
1442
+ );
1443
+
1444
+ return {
1445
+ sheetRef,
1446
+ contentProps,
1447
+ handleProps,
1448
+ bodyProps,
1449
+ bodyElementRef: bodyNodeRef,
1450
+ dragOffset,
1451
+ settledOffset,
1452
+ isDragging,
1453
+ sheetHeight,
1454
+ scrollPreservationInset,
1455
+ settlingLayoutOffset,
1456
+ settledLayoutOffset,
1457
+ completeScrollAreaSettle,
1458
+ };
1459
+ }