@astryxdesign/core 0.4.2 → 0.4.3-canary.0a9618e

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 (199) 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/index.d.ts +1 -0
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +1 -0
  93. package/dist/theme/defineTheme.d.ts +30 -7
  94. package/dist/theme/defineTheme.d.ts.map +1 -1
  95. package/dist/theme/defineTheme.js +36 -47
  96. package/dist/theme/expandColorScale.d.ts +17 -2
  97. package/dist/theme/expandColorScale.d.ts.map +1 -1
  98. package/dist/theme/expandColorScale.js +63 -33
  99. package/dist/theme/mergeComponents.d.ts +20 -0
  100. package/dist/theme/mergeComponents.d.ts.map +1 -0
  101. package/dist/theme/mergeComponents.js +56 -0
  102. package/dist/theme/onMediaTokens.d.ts +6 -1
  103. package/dist/theme/onMediaTokens.d.ts.map +1 -1
  104. package/dist/theme/onMediaTokens.js +11 -3
  105. package/dist/utils/characters.d.ts +27 -0
  106. package/dist/utils/characters.d.ts.map +1 -0
  107. package/dist/utils/characters.js +83 -0
  108. package/dist/utils/ime.d.ts +5 -0
  109. package/dist/utils/ime.d.ts.map +1 -0
  110. package/dist/utils/ime.js +63 -0
  111. package/dist/utils/index.d.ts +2 -0
  112. package/dist/utils/index.d.ts.map +1 -1
  113. package/dist/utils/index.js +3 -1
  114. package/package.json +9 -8
  115. package/src/Avatar/Avatar.test.tsx +6 -1
  116. package/src/Avatar/Avatar.tsx +3 -21
  117. package/src/Banner/Banner.doc.mjs +12 -10
  118. package/src/Banner/Banner.test.tsx +108 -0
  119. package/src/Banner/Banner.tsx +124 -38
  120. package/src/Banner/index.ts +15 -13
  121. package/src/BottomSheet/BottomSheet.doc.mjs +266 -0
  122. package/src/BottomSheet/BottomSheet.test.tsx +1865 -0
  123. package/src/BottomSheet/BottomSheet.tsx +539 -0
  124. package/src/BottomSheet/BottomSheetPanel.test.tsx +240 -0
  125. package/src/BottomSheet/BottomSheetPanel.tsx +542 -0
  126. package/src/BottomSheet/BottomSheetSwitcher.doc.mjs +219 -0
  127. package/src/BottomSheet/BottomSheetSwitcher.test.tsx +850 -0
  128. package/src/BottomSheet/BottomSheetSwitcher.tsx +628 -0
  129. package/src/BottomSheet/BottomSheetSwitcherContext.ts +51 -0
  130. package/src/BottomSheet/index.ts +15 -0
  131. package/src/BottomSheet/snapOffsets.test.ts +187 -0
  132. package/src/BottomSheet/snapOffsets.ts +159 -0
  133. package/src/BottomSheet/useMobileKeyboard.ts +566 -0
  134. package/src/BottomSheet/useSheetGestures.test.ts +833 -0
  135. package/src/BottomSheet/useSheetGestures.ts +1333 -0
  136. package/src/Chat/ChatComposerInput.tsx +3 -4
  137. package/src/Chat/ChatTokenizedText.tsx +1 -1
  138. package/src/ComplexSelector/ComplexSelector.doc.mjs +55 -6
  139. package/src/ComplexSelector/ComplexSelector.test.tsx +197 -6
  140. package/src/ComplexSelector/ComplexSelector.tsx +156 -28
  141. package/src/ComplexSelector/index.ts +3 -1
  142. package/src/ContextMenu/ContextMenu.tsx +4 -2
  143. package/src/DateInput/DateInput.test.tsx +21 -0
  144. package/src/DateInput/DateInput.tsx +9 -1
  145. package/src/DateTimeInput/DateTimeInput.doc.mjs +4 -0
  146. package/src/DateTimeInput/DateTimeInput.test.tsx +137 -0
  147. package/src/DateTimeInput/DateTimeInput.tsx +39 -2
  148. package/src/Dialog/Dialog.tsx +2 -1
  149. package/src/Markdown/parser.test.ts +53 -0
  150. package/src/Markdown/parser.ts +53 -12
  151. package/src/MobileNav/MobileNav.tsx +128 -37
  152. package/src/MobileNav/MobileNavCloseEdgeCases.test.tsx +426 -0
  153. package/src/MobileNav/MobileNavCloseTiming.test.ts +58 -0
  154. package/src/MobileNav/MobileNavCloseVisibility.test.tsx +172 -0
  155. package/src/MultiSelector/MultiSelector.test.tsx +31 -0
  156. package/src/MultiSelector/MultiSelector.tsx +10 -1
  157. package/src/NumberInput/NumberInput.test.tsx +18 -0
  158. package/src/NumberInput/NumberInput.tsx +9 -1
  159. package/src/PowerSearch/PowerSearch.test.tsx +48 -3
  160. package/src/PowerSearch/PowerSearch.tsx +4 -1
  161. package/src/PowerSearch/PowerSearchEditPopover.tsx +1 -1
  162. package/src/PowerSearch/formatFilterValue.test.ts +22 -0
  163. package/src/PowerSearch/formatFilterValue.ts +2 -4
  164. package/src/Selector/Selector.test.tsx +33 -0
  165. package/src/Selector/Selector.tsx +10 -1
  166. package/src/Switch/Switch.test.tsx +16 -0
  167. package/src/Switch/Switch.tsx +7 -0
  168. package/src/Table/Table.test.tsx +6 -0
  169. package/src/Table/columnUtils.ts +3 -1
  170. package/src/TextArea/TextArea.doc.mjs +1 -1
  171. package/src/TextArea/TextArea.test.tsx +72 -0
  172. package/src/TextArea/TextArea.tsx +26 -8
  173. package/src/TimeInput/TimeInput.test.tsx +23 -0
  174. package/src/TimeInput/TimeInput.tsx +8 -0
  175. package/src/Tooltip/useTooltip.tsx +4 -1
  176. package/src/TreeList/TreeList.doc.mjs +2 -2
  177. package/src/TreeList/TreeList.tsx +1 -1
  178. package/src/Typeahead/BaseTypeahead.tsx +1 -1
  179. package/src/Typeahead/Typeahead.test.tsx +35 -0
  180. package/src/Typeahead/Typeahead.tsx +10 -1
  181. package/src/__tests__/stubMatchMedia.test.ts +79 -0
  182. package/src/__tests__/stubMatchMedia.ts +95 -0
  183. package/src/hooks/index.ts +9 -5
  184. package/src/hooks/useFocusTrap.ts +1 -14
  185. package/src/index.ts +1 -0
  186. package/src/theme/defineTheme.test.ts +127 -0
  187. package/src/theme/defineTheme.ts +70 -55
  188. package/src/theme/expandColorScale.test.ts +138 -0
  189. package/src/theme/expandColorScale.ts +89 -44
  190. package/src/theme/extensibleAxes.test.ts +365 -0
  191. package/src/theme/mergeComponents.ts +59 -0
  192. package/src/theme/onMediaTokens.ts +9 -2
  193. package/src/utils/characters.test.ts +141 -0
  194. package/src/utils/characters.ts +88 -0
  195. package/src/utils/ime.test.ts +32 -0
  196. package/src/utils/ime.ts +69 -0
  197. package/src/utils/index.ts +4 -0
  198. package/dist/astryx.umd.js +0 -147
  199. package/dist/astryx.umd.js.map +0 -7
@@ -0,0 +1,881 @@
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
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
43
+ import { useMediaQuery } from "../hooks/index.js";
44
+ import { computeDetentOffsets, isPeekOffset, resolveSettleOffset, scrimOpacityForOffset } from "./snapOffsets.js";
45
+
46
+ // A flick (fast throw) dismisses (down) or expands (up) regardless of where
47
+ // it ends. Requires both a speed and a distance floor so a small nudge
48
+ // doesn't trigger it.
49
+ const FLICK_VELOCITY = 1.2; // px/ms
50
+ const FLICK_MIN_DISTANCE = 48; // px traveled during the gesture
51
+ // On a slow drag below the shortest detent, dismiss once dragged past it by
52
+ // more than this fraction of that detent's height; otherwise snap back to it.
53
+ const DISMISS_OVERSHOOT_RATIO = 0.4;
54
+ // Within this many px of a detent, the live drag is magnetically eased toward
55
+ // it so it "clicks" into place instead of hovering just off the mark.
56
+ const MAGNET_RANGE = 40;
57
+ // Rubber-band factor for dragging up past fully-open, capped at OVERSCROLL_MAX
58
+ // (the sheet reserves that much bottom padding for the lift to reveal).
59
+ const OVERSCROLL_RESISTANCE = 0.35;
60
+ // SYNC: must match OVERSCROLL_PADDING in BottomSheetPanel.tsx (the reserved
61
+ // bottom padding the lift reveals). Kept as a local const rather than a shared
62
+ // import so it can be used inside stylex.create there.
63
+ const OVERSCROLL_MAX = 48;
64
+
65
+ // Short haptic tick on detent settle where supported. iOS Safari doesn't
66
+ // expose navigator.vibrate, so this is a no-op there; skipped under
67
+ // reduced-motion.
68
+ function hapticTick() {
69
+ if (typeof navigator === 'undefined' || typeof navigator.vibrate !== 'function') {
70
+ return;
71
+ }
72
+ if (prefersReducedMotion()) {
73
+ return;
74
+ }
75
+ navigator.vibrate(8);
76
+ }
77
+
78
+ // Pull a value toward the nearest of `targets` when within MAGNET_RANGE, easing
79
+ // the last stretch so the surface settles crisply onto a detent while dragging.
80
+ function magnetize(value, targets) {
81
+ let nearestTarget = targets[0];
82
+ let nearestDist = Math.abs(value - nearestTarget);
83
+ for (const t of targets) {
84
+ const d = Math.abs(value - t);
85
+ if (d < nearestDist) {
86
+ nearestDist = d;
87
+ nearestTarget = t;
88
+ }
89
+ }
90
+ if (nearestDist >= MAGNET_RANGE) {
91
+ return value;
92
+ }
93
+ // Ease-in over the range: pull grows as you approach (t^2), so the click
94
+ // feels magnetic near the detent but doesn't fight a deliberate drag-through.
95
+ const t = nearestDist / MAGNET_RANGE;
96
+ const pull = 1 - t * t;
97
+ return value + (nearestTarget - value) * pull;
98
+ }
99
+ function preservationInsetForOffset(baseOffset, targetOffset, naturalEndGap) {
100
+ return Math.max(0, baseOffset - targetOffset - naturalEndGap);
101
+ }
102
+ function renderedBlockEndPadding(element) {
103
+ const value = Number.parseFloat(getComputedStyle(element).paddingBlockEnd);
104
+ return Number.isFinite(value) ? value : 0;
105
+ }
106
+
107
+ // How much further the body could scroll on its own, ignoring the padding the
108
+ // hook adds to preserve scroll position across a height change.
109
+ function naturalEndGapFor(body) {
110
+ if (!body) {
111
+ return 0;
112
+ }
113
+ const renderedInset = renderedBlockEndPadding(body);
114
+ const naturalMaxScrollTop = Math.max(0, body.scrollHeight - body.clientHeight - renderedInset);
115
+ return naturalMaxScrollTop - body.scrollTop;
116
+ }
117
+ function visibleHeightForOffset(sheetHeight, offset, offscreenBlockEndInset) {
118
+ return Math.max(0, sheetHeight - offscreenBlockEndInset - offset);
119
+ }
120
+ function prefersReducedMotion() {
121
+ if (typeof window === 'undefined' || !window.matchMedia) {
122
+ return false;
123
+ }
124
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
125
+ }
126
+
127
+ /**
128
+ * Drag + snap machinery for the bottom sheet. Returns props to spread on the
129
+ * grab handle and the sliding surface, plus live drag state. A slow drag
130
+ * settles to the nearest detent; a fast downward flick dismisses; a fast
131
+ * upward flick expands to the tallest detent.
132
+ *
133
+ * @example
134
+ * ```
135
+ * const {contentProps, handleProps} = useSheetGestures({
136
+ * isOpen,
137
+ * onDismiss: () => onOpenChange(false),
138
+ * snapHeights: () => [240, 0.5 * (window.visualViewport?.height ?? 0)],
139
+ * });
140
+ * <div {...contentProps}>
141
+ * <div {...handleProps} />
142
+ * {children}
143
+ * </div>
144
+ * ```
145
+ */
146
+ export function useSheetGestures({
147
+ isOpen,
148
+ canDismiss = true,
149
+ offscreenBlockEndInset = 0,
150
+ onDismiss,
151
+ snapHeights,
152
+ onSnap,
153
+ onScrimOpacity
154
+ }) {
155
+ const [dragOffset, setDragOffset] = useState(0);
156
+ const [settledOffset, setSettledOffset] = useState(0);
157
+ const [isDragging, setIsDragging] = useState(false);
158
+ const [sheetHeight, setSheetHeight] = useState(0);
159
+ const [scrollPreservationInset, setScrollPreservationInset] = useState(0);
160
+ // How much of the settled travel is expressed as layout height. Equal to
161
+ // settledOffset for the resizing detents, and 0 at fully open and at the
162
+ // peek (see isPeekOffset), which keep the full height and use a transform.
163
+ const [settledLayoutOffset, setSettledLayoutOffset] = useState(0);
164
+ const settledLayoutOffsetRef = useRef(0);
165
+ // WHICH detent the sheet rests on, as an index into the resolved list. The
166
+ // offsets themselves are pixels derived from the viewport, so they stop
167
+ // meaning the same thing the moment the viewport changes; the index survives
168
+ // that and lets a resize re-resolve the same stop against the new geometry.
169
+ const settledDetentIndexRef = useRef(0);
170
+ const [settlingLayoutOffset, setSettlingLayoutOffset] = useState(null);
171
+ const [isScrollAreaReconciling, setIsScrollAreaReconciling] = useState(false);
172
+ const scrollPreservationInsetRef = useRef(0);
173
+ const settlingLayoutOffsetRef = useRef(null);
174
+ const pendingScrollPreservationInsetRef = useRef(null);
175
+ const offscreenBlockEndInsetRef = useRef(offscreenBlockEndInset);
176
+ offscreenBlockEndInsetRef.current = Math.max(0, offscreenBlockEndInset);
177
+ const recordSettledLayoutOffset = useCallback(offset => {
178
+ const normalizedOffset = Math.max(0, offset);
179
+ settledLayoutOffsetRef.current = normalizedOffset;
180
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- layout offset is recorded from measurement effects
181
+ setSettledLayoutOffset(normalizedOffset);
182
+ }, []);
183
+ const updateScrollPreservationInset = useCallback(nextInset => {
184
+ const normalizedInset = Math.max(0, nextInset);
185
+ const hasChanged = Math.abs(normalizedInset - scrollPreservationInsetRef.current) > 0.5;
186
+ if (!hasChanged) {
187
+ return;
188
+ }
189
+ scrollPreservationInsetRef.current = normalizedInset;
190
+ setScrollPreservationInset(normalizedInset);
191
+ }, []);
192
+ const completeScrollAreaSettle = useCallback(() => {
193
+ // Resetting the transform at the same time as the final height swap must
194
+ // not start a second transition. The layouts have identical visible
195
+ // geometry, so reconcile them with transitions disabled for one frame.
196
+ setIsScrollAreaReconciling(true);
197
+ settlingLayoutOffsetRef.current = null;
198
+ setSettlingLayoutOffset(null);
199
+ const pendingInset = pendingScrollPreservationInsetRef.current;
200
+ pendingScrollPreservationInsetRef.current = null;
201
+ if (pendingInset != null) {
202
+ updateScrollPreservationInset(pendingInset);
203
+ }
204
+ }, [updateScrollPreservationInset]);
205
+ const prepareScrollAreaSettle = useCallback((baseLayoutOffset, targetOffset, targetLayoutOffset, renderedOffset, layoutOffset, naturalEndGap, shouldAnimate) => {
206
+ const targetInset = preservationInsetForOffset(baseLayoutOffset, targetLayoutOffset, naturalEndGap);
207
+ if (shouldAnimate && Math.abs(renderedOffset - targetOffset) > 0.5 && !prefersReducedMotion()) {
208
+ pendingScrollPreservationInsetRef.current = targetInset;
209
+ settlingLayoutOffsetRef.current = layoutOffset;
210
+ setSettlingLayoutOffset(layoutOffset);
211
+ return;
212
+ }
213
+ pendingScrollPreservationInsetRef.current = null;
214
+ settlingLayoutOffsetRef.current = null;
215
+ setSettlingLayoutOffset(null);
216
+ // Released on the detent, so there is no travel left to animate — but
217
+ // the layout split may still differ from the one the drag rendered
218
+ // with (magnetize() lands a slow drag exactly on a detent). Swapping
219
+ // height for transform is only invisible while transitions are off:
220
+ // with them live, the composited transform would animate the whole
221
+ // swap while the layout height jumped, throwing the sheet the wrong
222
+ // way. Reconcile in one transition-free frame instead.
223
+ setIsScrollAreaReconciling(Math.abs(layoutOffset - targetLayoutOffset) > 0.5);
224
+ updateScrollPreservationInset(targetInset);
225
+ }, [updateScrollPreservationInset]);
226
+ const activeOffsetRef = useRef(0);
227
+ activeOffsetRef.current = isDragging ? dragOffset : settledOffset;
228
+ const isOpenRef = useRef(isOpen);
229
+ isOpenRef.current = isOpen;
230
+ const onDismissRef = useRef(onDismiss);
231
+ const canDismissRef = useRef(canDismiss);
232
+ const onSnapRef = useRef(onSnap);
233
+ const onScrimOpacityRef = useRef(onScrimOpacity);
234
+ const snapHeightsRef = useRef(snapHeights);
235
+ useEffect(() => {
236
+ onDismissRef.current = onDismiss;
237
+ canDismissRef.current = canDismiss;
238
+ onSnapRef.current = onSnap;
239
+ onScrimOpacityRef.current = onScrimOpacity;
240
+ snapHeightsRef.current = snapHeights;
241
+ });
242
+
243
+ // Live drag bookkeeping (refs so pointermove doesn't churn renders).
244
+ const dragStateRef = useRef(null);
245
+
246
+ // Fully-open height, tracked by a ResizeObserver (see sheetRef) so detents
247
+ // stay correct across rotation / viewport changes without re-measuring.
248
+ const sheetHeightRef = useRef(0);
249
+ const sheetElRef = useRef(null);
250
+ const bodyNodeRef = useRef(null);
251
+ const observerRef = useRef(null);
252
+ useLayoutEffect(() => {
253
+ if (!isScrollAreaReconciling) {
254
+ return;
255
+ }
256
+ // Force the transition-free transform reset to resolve before transitions
257
+ // are restored. Otherwise both DOM updates can be coalesced and the reset
258
+ // becomes an unintended fly-in animation from the bottom.
259
+ void sheetElRef.current?.offsetHeight;
260
+ const frame = requestAnimationFrame(() => {
261
+ setIsScrollAreaReconciling(false);
262
+ });
263
+ return () => cancelAnimationFrame(frame);
264
+ }, [isScrollAreaReconciling]);
265
+ const recordSheetHeight = useCallback(renderedHeight => {
266
+ if (renderedHeight <= 0) {
267
+ return;
268
+ }
269
+ // A resized or closing panel's observer reports intermediate heights
270
+ // throughout its animation. Keep the last fully-expanded measurement
271
+ // instead of feeding those transient values back into the rendered height.
272
+ if (!isOpenRef.current || activeOffsetRef.current > 0) {
273
+ return;
274
+ }
275
+ sheetHeightRef.current = renderedHeight;
276
+ setSheetHeight(previousHeight => previousHeight === renderedHeight ? previousHeight : renderedHeight);
277
+ }, []);
278
+ const sheetRef = useCallback(node => {
279
+ observerRef.current?.disconnect();
280
+ observerRef.current = null;
281
+ sheetElRef.current = node;
282
+ if (!node || typeof ResizeObserver === 'undefined') {
283
+ if (node) {
284
+ recordSheetHeight(node.getBoundingClientRect().height);
285
+ }
286
+ return;
287
+ }
288
+ recordSheetHeight(node.getBoundingClientRect().height);
289
+ const ro = new ResizeObserver(entries => {
290
+ const entry = entries[0];
291
+ if (entry) {
292
+ // Keep this measurement in the same border-box coordinate space as
293
+ // getBoundingClientRect(). contentRect excludes the sheet's reserved
294
+ // bottom padding and would make the first resized drag jump shorter.
295
+ const borderBoxHeight = entry.borderBoxSize?.[0]?.blockSize;
296
+ recordSheetHeight(borderBoxHeight ?? entry.target.getBoundingClientRect().height);
297
+ }
298
+ });
299
+ ro.observe(node);
300
+ observerRef.current = ro;
301
+ }, [recordSheetHeight]);
302
+ useEffect(() => () => observerRef.current?.disconnect(), []);
303
+
304
+ // Reset to the tallest detent each time the sheet re-opens.
305
+ useEffect(() => {
306
+ if (isOpen) {
307
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
308
+ setDragOffset(0);
309
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
310
+ setSettledOffset(0);
311
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
312
+ setIsDragging(false);
313
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
314
+ setIsScrollAreaReconciling(false);
315
+ recordSettledLayoutOffset(0);
316
+ settledDetentIndexRef.current = 0;
317
+ scrollPreservationInsetRef.current = 0;
318
+ settlingLayoutOffsetRef.current = null;
319
+ pendingScrollPreservationInsetRef.current = null;
320
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
321
+ setScrollPreservationInset(0);
322
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen
323
+ setSettlingLayoutOffset(null);
324
+ }
325
+ }, [isOpen, recordSettledLayoutOffset]);
326
+
327
+ // The fully-open height for detent math. Prefer the ResizeObserver-locked
328
+ // value; fall back to a live measure of the tracked sheet element if the
329
+ // observer hasn't reported yet.
330
+ const measureHeight = useCallback(() => {
331
+ if (sheetHeightRef.current > 0) {
332
+ return sheetHeightRef.current;
333
+ }
334
+ return sheetElRef.current?.getBoundingClientRect().height ?? 0;
335
+ }, []);
336
+
337
+ // Detent translate offsets (px) from the tallest detent, ascending. Exclude
338
+ // the border-box portion reserved below the viewport before comparing the
339
+ // candidate visible heights; otherwise every snap point lands that many px
340
+ // too low. Snap heights are resolved lazily so they track the viewport.
341
+ const detentOffsets = useCallback(height => {
342
+ const visibleSheetHeight = visibleHeightForOffset(height, 0, offscreenBlockEndInsetRef.current);
343
+ return computeDetentOffsets(visibleSheetHeight, snapHeightsRef.current?.() ?? []);
344
+ }, []);
345
+
346
+ // The height the sheet WOULD have fully open, right now. While it rests at a
347
+ // resizing detent the element carries a pixel height computed for whatever
348
+ // the viewport was then, so measuring it directly just reads that stale
349
+ // number back. Drop the inline height for the measurement and put it back in
350
+ // the same synchronous block — the browser cannot paint in between, so this
351
+ // is invisible — and the natural CSS budget is what gets measured.
352
+ const measureFullyOpenHeight = useCallback(() => {
353
+ const element = sheetElRef.current;
354
+ if (!element) {
355
+ return sheetHeightRef.current;
356
+ }
357
+ const inlineHeight = element.style.height;
358
+ if (inlineHeight === '') {
359
+ return element.getBoundingClientRect().height;
360
+ }
361
+ element.style.height = '';
362
+ const height = element.getBoundingClientRect().height;
363
+ element.style.height = inlineHeight;
364
+ return height;
365
+ }, []);
366
+
367
+ // Detents are viewport fractions, but a settled sheet holds them as pixels:
368
+ // an offset to translate by, and a layout height to render. Both are read
369
+ // once, at gesture time. Without this, a viewport change leaves the sheet
370
+ // frozen at the old pixel geometry — a "half height" sheet showing 75% of a
371
+ // shorter window, a peek detent whose slide-down is taller than the whole
372
+ // window (so the sheet leaves the screen while its dialog stays modal), and
373
+ // a stale fully-open height for the next drag to overshoot past.
374
+ //
375
+ // Re-resolve the SAME detent — by index, the one thing that survives the
376
+ // units changing — against the new geometry, and re-anchor without
377
+ // animating: the viewport moved, not the user's finger, so there is no
378
+ // gesture to continue and nothing to ease.
379
+ useEffect(() => {
380
+ if (!isOpen || typeof window === 'undefined') {
381
+ return;
382
+ }
383
+ const handleViewportChange = () => {
384
+ // A live drag re-measures on its own, and a settle in flight owns the
385
+ // layout until it lands.
386
+ if (dragStateRef.current != null || settlingLayoutOffsetRef.current != null) {
387
+ return;
388
+ }
389
+ const height = measureFullyOpenHeight();
390
+ if (height <= 0) {
391
+ return;
392
+ }
393
+ const offsets = detentOffsets(height);
394
+ const index = Math.min(settledDetentIndexRef.current, offsets.length - 1);
395
+ const target = offsets[index];
396
+ const targetLayoutOffset = isPeekOffset(target, offsets) ? 0 : target;
397
+ const baseLayoutOffset = settledLayoutOffsetRef.current;
398
+ if (height === sheetHeightRef.current && Math.abs(target - activeOffsetRef.current) <= 0.5 && Math.abs(targetLayoutOffset - baseLayoutOffset) <= 0.5) {
399
+ return;
400
+ }
401
+ sheetHeightRef.current = height;
402
+ setSheetHeight(height);
403
+ settledDetentIndexRef.current = index;
404
+ prepareScrollAreaSettle(baseLayoutOffset, target, targetLayoutOffset, target, baseLayoutOffset, naturalEndGapFor(bodyNodeRef.current), false);
405
+ recordSettledLayoutOffset(targetLayoutOffset);
406
+ setSettledOffset(target);
407
+ onSnapRef.current?.(visibleHeightForOffset(height, target, offscreenBlockEndInsetRef.current));
408
+ const maxOffset = offsets[offsets.length - 1];
409
+ const shortestDetentHeight = visibleHeightForOffset(height, maxOffset, offscreenBlockEndInsetRef.current);
410
+ onScrimOpacityRef.current?.(scrimOpacityForOffset(target, offsets, maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO));
411
+ };
412
+ window.addEventListener('resize', handleViewportChange);
413
+ window.addEventListener('orientationchange', handleViewportChange);
414
+ return () => {
415
+ window.removeEventListener('resize', handleViewportChange);
416
+ window.removeEventListener('orientationchange', handleViewportChange);
417
+ };
418
+ }, [detentOffsets, isOpen, measureFullyOpenHeight, prepareScrollAreaSettle, recordSettledLayoutOffset]);
419
+ const cancelDrag = useCallback(target => {
420
+ const state = dragStateRef.current;
421
+ if (state == null) {
422
+ return;
423
+ }
424
+
425
+ // Clear first: releasePointerCapture() may synchronously dispatch
426
+ // lostpointercapture, which must observe that this drag is already done.
427
+ dragStateRef.current = null;
428
+ if (target?.hasPointerCapture?.(state.pointerId)) {
429
+ target.releasePointerCapture(state.pointerId);
430
+ }
431
+ setDragOffset(state.baseOffset);
432
+ setIsDragging(false);
433
+ prepareScrollAreaSettle(state.baseLayoutOffset, state.baseOffset, state.baseLayoutOffset, state.renderedOffset, state.layoutOffset, state.naturalEndGap, true);
434
+
435
+ // An interrupted drag returns to its previous resting detent. Restore
436
+ // the matching scrim opacity as well so the modal shell cannot remain
437
+ // dimmed with its sheet translated out of view.
438
+ const offsets = detentOffsets(state.height);
439
+ const maxOffset = offsets[offsets.length - 1];
440
+ const shortestDetentHeight = visibleHeightForOffset(state.height, maxOffset, offscreenBlockEndInsetRef.current);
441
+ const dismissOffset = maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
442
+ onScrimOpacityRef.current?.(scrimOpacityForOffset(state.baseOffset, offsets, dismissOffset));
443
+ }, [detentOffsets, prepareScrollAreaSettle]);
444
+ useEffect(() => {
445
+ const handleWindowBlur = () => cancelDrag();
446
+ const handleVisibilityChange = () => {
447
+ if (document.visibilityState === 'hidden') {
448
+ cancelDrag();
449
+ }
450
+ };
451
+ window.addEventListener('blur', handleWindowBlur);
452
+ document.addEventListener('visibilitychange', handleVisibilityChange);
453
+ return () => {
454
+ window.removeEventListener('blur', handleWindowBlur);
455
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
456
+ };
457
+ }, [cancelDrag]);
458
+ const settleFromDrag = useCallback((offset, velocity, height, dir, travel, baseOffset, baseLayoutOffset, renderedOffset, layoutOffset, naturalEndGap) => {
459
+ const offsets = detentOffsets(height);
460
+ const maxOffset = offsets[offsets.length - 1];
461
+ const shortestDetentHeight = visibleHeightForOffset(height, maxOffset, offscreenBlockEndInsetRef.current);
462
+ const speed = Math.abs(velocity);
463
+ const isFlick = speed > FLICK_VELOCITY && travel > FLICK_MIN_DISTANCE;
464
+ const settleAt = target => {
465
+ // A peek keeps the full layout height and slides below the viewport;
466
+ // every taller detent resizes the scrolling area to what it shows.
467
+ const targetLayoutOffset = isPeekOffset(target, offsets) ? 0 : target;
468
+ prepareScrollAreaSettle(baseLayoutOffset, target, targetLayoutOffset, renderedOffset, layoutOffset, naturalEndGap, true);
469
+ recordSettledLayoutOffset(targetLayoutOffset);
470
+ settledDetentIndexRef.current = Math.max(0, offsets.indexOf(target));
471
+ setSettledOffset(target);
472
+ onSnapRef.current?.(visibleHeightForOffset(height, target, offscreenBlockEndInsetRef.current));
473
+ const dismissOffset = maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
474
+ onScrimOpacityRef.current?.(scrimOpacityForOffset(target, offsets, dismissOffset));
475
+ if (target !== baseOffset) {
476
+ hapticTick();
477
+ }
478
+ };
479
+ if (dir > 0 && isFlick) {
480
+ if (canDismissRef.current) {
481
+ prepareScrollAreaSettle(baseLayoutOffset, baseOffset, baseLayoutOffset, baseLayoutOffset, baseLayoutOffset, naturalEndGap, false);
482
+ onDismissRef.current();
483
+ } else {
484
+ settleAt(maxOffset);
485
+ }
486
+ return;
487
+ }
488
+ // Fast upward flick = expand to the tallest detent (the sheet's full
489
+ // provided height).
490
+ if (dir < 0 && isFlick) {
491
+ prepareScrollAreaSettle(baseLayoutOffset, 0, 0, renderedOffset, layoutOffset, naturalEndGap, true);
492
+ recordSettledLayoutOffset(0);
493
+ settledDetentIndexRef.current = 0;
494
+ setDragOffset(0);
495
+ setSettledOffset(0);
496
+ onSnapRef.current?.(visibleHeightForOffset(height, 0, offscreenBlockEndInsetRef.current));
497
+ onScrimOpacityRef.current?.(1);
498
+ hapticTick();
499
+ return;
500
+ }
501
+ if (offset > maxOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO) {
502
+ if (canDismissRef.current) {
503
+ prepareScrollAreaSettle(baseLayoutOffset, baseOffset, baseLayoutOffset, baseLayoutOffset, baseLayoutOffset, naturalEndGap, false);
504
+ onDismissRef.current();
505
+ } else {
506
+ settleAt(maxOffset);
507
+ }
508
+ return;
509
+ }
510
+ // Settle to the nearest detent in the drag direction (never back past
511
+ // the starting detent), de-duped and direction-clamped by the util.
512
+ const target = resolveSettleOffset(offset, offsets, dir, baseOffset);
513
+ settleAt(target);
514
+ }, [detentOffsets, prepareScrollAreaSettle, recordSettledLayoutOffset]);
515
+ const beginDrag = useCallback((event, sheetHeight, startCoord) => {
516
+ const target = event.currentTarget;
517
+ target.setPointerCapture?.(event.pointerId);
518
+ // `startCoord` lets a body-overscroll drag anchor at the original
519
+ // pointer-down position (not the promotion point), so the first frame's
520
+ // delta reflects the full pull distance.
521
+ const start = startCoord ?? event.clientY;
522
+ const naturalEndGap = naturalEndGapFor(bodyNodeRef.current);
523
+ const baseLayoutOffset = settledLayoutOffsetRef.current;
524
+ dragStateRef.current = {
525
+ pointerId: event.pointerId,
526
+ startCoord: start,
527
+ lastCoord: event.clientY,
528
+ lastTime: event.timeStamp,
529
+ velocity: 0,
530
+ height: sheetHeight,
531
+ baseOffset: settledOffset,
532
+ baseLayoutOffset,
533
+ renderedOffset: settledOffset,
534
+ layoutOffset: baseLayoutOffset,
535
+ naturalEndGap
536
+ };
537
+ updateScrollPreservationInset(preservationInsetForOffset(baseLayoutOffset, baseLayoutOffset, naturalEndGap));
538
+ // Seed dragOffset at the resting detent so flipping isDragging doesn't
539
+ // jump the sheet to fully-open for one frame.
540
+ setDragOffset(settledOffset);
541
+ setIsDragging(true);
542
+ }, [settledOffset, updateScrollPreservationInset]);
543
+ const handlePointerDown = useCallback(event => {
544
+ if (event.button !== 0 || !event.isPrimary) {
545
+ return;
546
+ }
547
+ // The handle has no native focus action. Prevent pointer-down from
548
+ // moving focus off a form control on a tap; once the pointer actually
549
+ // moves, BottomSheet dismisses the keyboard as sheet travel begins.
550
+ event.preventDefault();
551
+ beginDrag(event, measureHeight());
552
+ }, [beginDrag, measureHeight]);
553
+ const handleContextMenu = useCallback(event => {
554
+ if (dragStateRef.current == null) {
555
+ return;
556
+ }
557
+ event.preventDefault();
558
+ cancelDrag(event.currentTarget);
559
+ }, [cancelDrag]);
560
+ const handleLostPointerCapture = useCallback(event => {
561
+ if (dragStateRef.current?.pointerId === event.pointerId) {
562
+ cancelDrag();
563
+ }
564
+ }, [cancelDrag]);
565
+ const handlePointerMove = useCallback(event => {
566
+ const state = dragStateRef.current;
567
+ if (!state || state.pointerId !== event.pointerId) {
568
+ return;
569
+ }
570
+ const delta = event.clientY - state.startCoord;
571
+ const dt = event.timeStamp - state.lastTime;
572
+ if (dt > 0) {
573
+ state.velocity = (event.clientY - state.lastCoord) / dt;
574
+ state.lastCoord = event.clientY;
575
+ state.lastTime = event.timeStamp;
576
+ }
577
+ const offsets = detentOffsets(state.height);
578
+ const raw = state.baseOffset + delta;
579
+ const maxDetentOffset = offsets[offsets.length - 1];
580
+ let next;
581
+ if (raw < 0) {
582
+ // Up past fully-open: damped + capped rubber-band; springs back on release.
583
+ next = Math.max(-OVERSCROLL_MAX, raw * OVERSCROLL_RESISTANCE);
584
+ } else if (raw > maxDetentOffset) {
585
+ // In the dismiss zone: no magnet, so it doesn't fight a drag-to-close.
586
+ next = raw;
587
+ } else {
588
+ // Between detents: magnetically ease toward a nearby one.
589
+ next = magnetize(raw, offsets);
590
+ }
591
+ // Dragging above the base restores the full layout height below the
592
+ // viewport; otherwise keep whatever layout the base detent settled with
593
+ // (0 at a peek, so a peek drag stays transform-only).
594
+ const layoutOffset = next < state.baseOffset ? 0 : state.baseLayoutOffset;
595
+ state.renderedOffset = next;
596
+ state.layoutOffset = layoutOffset;
597
+ setDragOffset(next);
598
+ updateScrollPreservationInset(preservationInsetForOffset(state.baseLayoutOffset, layoutOffset, state.naturalEndGap));
599
+
600
+ // Mirror the scrim to the live drag: full at/above the mid detent,
601
+ // fading to hidden as it collapses onto the peek detent and through the
602
+ // dismiss overshoot.
603
+ const floorOffset = offsets[offsets.length - 1];
604
+ const shortestDetentHeight = visibleHeightForOffset(state.height, floorOffset, offscreenBlockEndInsetRef.current);
605
+ const dismissOffset = floorOffset + shortestDetentHeight * DISMISS_OVERSHOOT_RATIO;
606
+ onScrimOpacityRef.current?.(scrimOpacityForOffset(next, offsets, dismissOffset));
607
+ }, [detentOffsets, updateScrollPreservationInset]);
608
+ const endDrag = useCallback(event => {
609
+ const state = dragStateRef.current;
610
+ if (!state || state.pointerId !== event.pointerId) {
611
+ return;
612
+ }
613
+ const target = event.currentTarget;
614
+ const delta = event.clientY - state.startCoord;
615
+ const offset = Math.max(0, state.baseOffset + delta);
616
+ const dir = delta === 0 ? 0 : delta > 0 ? 1 : -1;
617
+ dragStateRef.current = null;
618
+ target.releasePointerCapture?.(event.pointerId);
619
+ setIsDragging(false);
620
+ settleFromDrag(offset, state.velocity, state.height || 1, dir, Math.abs(delta), state.baseOffset, state.baseLayoutOffset, state.renderedOffset, state.layoutOffset, state.naturalEndGap);
621
+ }, [settleFromDrag]);
622
+
623
+ // Pointer path for the body at-top pull-down (desktop / mouse). Touch uses
624
+ // the non-passive listener below, since pointer events are cancelled once a
625
+ // native pan starts.
626
+ const armedBodyRef = useRef(null);
627
+ const handleBodyPointerDown = useCallback(event => {
628
+ if (event.button !== 0 || !event.isPrimary) {
629
+ return;
630
+ }
631
+ const scroller = event.currentTarget;
632
+ if (scroller.scrollTop > 0) {
633
+ armedBodyRef.current = null;
634
+ return;
635
+ }
636
+ armedBodyRef.current = {
637
+ pointerId: event.pointerId,
638
+ startCoord: event.clientY,
639
+ scroller
640
+ };
641
+ }, []);
642
+ const handleBodyPointerMove = useCallback(event => {
643
+ if (dragStateRef.current) {
644
+ handlePointerMove(event);
645
+ return;
646
+ }
647
+ const armed = armedBodyRef.current;
648
+ if (!armed || armed.pointerId !== event.pointerId) {
649
+ return;
650
+ }
651
+ const delta = event.clientY - armed.startCoord;
652
+ if (delta > 0 && armed.scroller.scrollTop <= 0) {
653
+ // Downward pull at the top: promote to a sheet drag, anchored at the
654
+ // original pointer-down position so the pull distance carries over.
655
+ armedBodyRef.current = null;
656
+ beginDrag(event, measureHeight(), armed.startCoord);
657
+ handlePointerMove(event);
658
+ } else if (delta < 0) {
659
+ // Upward move = the user is scrolling; disarm so we don't hijack it.
660
+ armedBodyRef.current = null;
661
+ }
662
+ }, [beginDrag, handlePointerMove, measureHeight]);
663
+ const handleBodyEnd = useCallback(event => {
664
+ armedBodyRef.current = null;
665
+ if (dragStateRef.current) {
666
+ endDrag(event);
667
+ }
668
+ }, [endDrag]);
669
+
670
+ // Non-passive touchmove is the reliable scroll<->drag handoff on touch:
671
+ // preventDefault() at a scroll edge stops the native scroll and drives the
672
+ // sheet drag through the pointer math (Touch adapted to the fields it reads).
673
+ const touchDragRef = useRef(null);
674
+ const previousTouchHandlersRef = useRef(null);
675
+ const beginDragRef = useRef(beginDrag);
676
+ const cancelDragRef = useRef(cancelDrag);
677
+ const pointerMoveRef = useRef(handlePointerMove);
678
+ const endDragRef = useRef(endDrag);
679
+ const measureHeightRef = useRef(measureHeight);
680
+ useEffect(() => {
681
+ beginDragRef.current = beginDrag;
682
+ cancelDragRef.current = cancelDrag;
683
+ pointerMoveRef.current = handlePointerMove;
684
+ endDragRef.current = endDrag;
685
+ measureHeightRef.current = measureHeight;
686
+ });
687
+ const bodyRef = useCallback(node => {
688
+ const asPointer = (touch, target) => ({
689
+ pointerId: touch.identifier,
690
+ clientY: touch.clientY,
691
+ timeStamp: Date.now(),
692
+ currentTarget: target,
693
+ setPointerCapture: () => {},
694
+ releasePointerCapture: () => {}
695
+ });
696
+ const atTop = el => el.scrollTop <= 0;
697
+ const atBottom = el => el.scrollTop + el.clientHeight >= el.scrollHeight - 1;
698
+ const onTouchStart = event => {
699
+ const scroller = event.currentTarget;
700
+ const touch = event.changedTouches[0];
701
+ // Arm only at a scroll edge; from mid-content this is an ordinary scroll.
702
+ // At the top, a pull DOWN hands off (collapse); at the bottom, a pull UP
703
+ // hands off (expand). Record the edge so the move handler matches it.
704
+ if (!touch) {
705
+ touchDragRef.current = null;
706
+ return;
707
+ }
708
+ const top = atTop(scroller);
709
+ // The bottom edge hands off so the sheet can EXPAND, so it is only a
710
+ // handoff when a taller detent exists. Already at the tallest, an
711
+ // upward pull has nowhere to travel: promoting it would trade the
712
+ // user's scroll for a rubber-band the release throws straight back, and
713
+ // — because promotion preventDefault()s the rest of the gesture — would
714
+ // strand the scroller for as long as the finger stays down, so reversing
715
+ // downward to scroll back would collapse the sheet instead. Leave the
716
+ // gesture with the content.
717
+ const bottom = atBottom(scroller) && activeOffsetRef.current > 0;
718
+ if (!top && !bottom) {
719
+ touchDragRef.current = null;
720
+ return;
721
+ }
722
+ touchDragRef.current = {
723
+ id: touch.identifier,
724
+ startY: touch.clientY,
725
+ top,
726
+ bottom
727
+ };
728
+ };
729
+ const onTouchMove = event => {
730
+ const scroller = event.currentTarget;
731
+ if (dragStateRef.current) {
732
+ const t = [...event.changedTouches].find(x => x.identifier === dragStateRef.current?.pointerId);
733
+ if (t) {
734
+ event.preventDefault();
735
+ pointerMoveRef.current(asPointer(t, scroller));
736
+ }
737
+ return;
738
+ }
739
+ const armed = touchDragRef.current;
740
+ if (!armed) {
741
+ return;
742
+ }
743
+ const t = [...event.changedTouches].find(x => x.identifier === armed.id);
744
+ if (!t) {
745
+ return;
746
+ }
747
+ const delta = t.clientY - armed.startY;
748
+ // Promote to a sheet drag on a pull that opposes the armed edge and can
749
+ // no longer scroll that way: at the top, a downward pull (delta > 0)
750
+ // collapses; at the bottom, an upward pull (delta < 0) expands. The
751
+ // opposite direction is a real scroll, so disarm and let it through.
752
+ const pullDownAtTop = armed.top && delta > 0 && atTop(scroller);
753
+ const pullUpAtBottom = armed.bottom && delta < 0 && atBottom(scroller);
754
+ if (pullDownAtTop || pullUpAtBottom) {
755
+ event.preventDefault();
756
+ touchDragRef.current = null;
757
+ beginDragRef.current(asPointer(t, scroller), measureHeightRef.current(), armed.startY);
758
+ pointerMoveRef.current(asPointer(t, scroller));
759
+ } else if (armed.top && delta < 0 || armed.bottom && delta > 0) {
760
+ // Scrolling away from the armed edge; hand back to native scroll.
761
+ touchDragRef.current = null;
762
+ }
763
+ };
764
+ const onTouchEnd = event => {
765
+ touchDragRef.current = null;
766
+ const pointerId = dragStateRef.current?.pointerId;
767
+ if (pointerId == null) {
768
+ return;
769
+ }
770
+ const t = [...event.changedTouches].find(touch => touch.identifier === pointerId);
771
+ const target = event.currentTarget;
772
+ if (t) {
773
+ endDragRef.current(asPointer(t, target));
774
+ } else if (event.touches.length === 0) {
775
+ // Some interrupted multi-touch sequences omit the active touch from
776
+ // changedTouches. If no fingers remain, the drag cannot finish later.
777
+ cancelDragRef.current(target);
778
+ }
779
+ };
780
+ const prev = bodyNodeRef.current;
781
+ if (prev && previousTouchHandlersRef.current) {
782
+ const h = previousTouchHandlersRef.current;
783
+ prev.removeEventListener('touchstart', h.start);
784
+ prev.removeEventListener('touchmove', h.move);
785
+ prev.removeEventListener('touchend', h.end);
786
+ prev.removeEventListener('touchcancel', h.end);
787
+ }
788
+ bodyNodeRef.current = node;
789
+ if (node) {
790
+ node.addEventListener('touchstart', onTouchStart, {
791
+ passive: true
792
+ });
793
+ node.addEventListener('touchmove', onTouchMove, {
794
+ passive: false
795
+ });
796
+ node.addEventListener('touchend', onTouchEnd, {
797
+ passive: true
798
+ });
799
+ node.addEventListener('touchcancel', onTouchEnd, {
800
+ passive: true
801
+ });
802
+ previousTouchHandlersRef.current = {
803
+ start: onTouchStart,
804
+ move: onTouchMove,
805
+ end: onTouchEnd
806
+ };
807
+ } else {
808
+ previousTouchHandlersRef.current = null;
809
+ }
810
+ }, []);
811
+
812
+ // Subscribed, not memoized: the preference can change while a sheet is open,
813
+ // and this branch decides whether the settle runs as a transition at all.
814
+ // The imperative gesture paths read prefersReducedMotion() directly.
815
+ const reducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
816
+ const reconcileScrollPreservationInset = useCallback(body => {
817
+ if (scrollPreservationInsetRef.current <= 0) {
818
+ return;
819
+ }
820
+ const renderedInset = renderedBlockEndPadding(body);
821
+ const naturalMaxScrollTop = Math.max(0, body.scrollHeight - body.clientHeight - renderedInset);
822
+ const requiredInset = Math.max(0, body.scrollTop - naturalMaxScrollTop);
823
+ if (requiredInset < scrollPreservationInsetRef.current - 0.5) {
824
+ updateScrollPreservationInset(requiredInset);
825
+ }
826
+ }, [updateScrollPreservationInset]);
827
+ const handleBodyScroll = useCallback(event => {
828
+ if (dragStateRef.current != null || settlingLayoutOffsetRef.current != null) {
829
+ return;
830
+ }
831
+ reconcileScrollPreservationInset(event.currentTarget);
832
+ }, [reconcileScrollPreservationInset]);
833
+
834
+ // While dragging, follow the finger; otherwise rest at the settled detent.
835
+ const activeOffset = isDragging ? dragOffset : settledOffset;
836
+ const contentProps = useMemo(() => ({
837
+ style: {
838
+ transform: activeOffset !== 0 ? `translateY(${activeOffset}px)` : undefined,
839
+ transition: isDragging || isScrollAreaReconciling || reducedMotion ? 'none' : undefined,
840
+ touchAction: 'none',
841
+ overscrollBehavior: 'contain'
842
+ }
843
+ }), [activeOffset, isDragging, isScrollAreaReconciling, reducedMotion]);
844
+ const handleProps = useMemo(() => ({
845
+ style: {
846
+ touchAction: 'none',
847
+ cursor: 'grab'
848
+ },
849
+ onContextMenu: handleContextMenu,
850
+ onLostPointerCapture: handleLostPointerCapture,
851
+ onPointerDown: handlePointerDown,
852
+ onPointerMove: handlePointerMove,
853
+ onPointerUp: endDrag,
854
+ onPointerCancel: endDrag
855
+ }), [endDrag, handleContextMenu, handleLostPointerCapture, handlePointerDown, handlePointerMove]);
856
+ const bodyProps = useMemo(() => ({
857
+ ref: bodyRef,
858
+ onContextMenu: handleContextMenu,
859
+ onLostPointerCapture: handleLostPointerCapture,
860
+ onPointerDown: handleBodyPointerDown,
861
+ onPointerMove: handleBodyPointerMove,
862
+ onPointerUp: handleBodyEnd,
863
+ onPointerCancel: handleBodyEnd,
864
+ onScroll: handleBodyScroll
865
+ }), [bodyRef, handleBodyEnd, handleBodyPointerDown, handleBodyPointerMove, handleBodyScroll, handleContextMenu, handleLostPointerCapture]);
866
+ return {
867
+ sheetRef,
868
+ contentProps,
869
+ handleProps,
870
+ bodyProps,
871
+ bodyElementRef: bodyNodeRef,
872
+ dragOffset,
873
+ settledOffset,
874
+ isDragging,
875
+ sheetHeight,
876
+ scrollPreservationInset,
877
+ settlingLayoutOffset,
878
+ settledLayoutOffset,
879
+ completeScrollAreaSettle
880
+ };
881
+ }