@astryxdesign/core 0.4.2 → 0.4.3-canary.00bed29

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