@astryxdesign/core 0.4.2 → 0.4.3-canary.07f9998

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