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

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