@lodev09/react-native-true-sheet 3.10.1 → 3.11.0-beta.1

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 (108) hide show
  1. package/lib/module/TrueSheet.js +3 -0
  2. package/lib/module/TrueSheet.js.map +1 -1
  3. package/lib/module/TrueSheet.web.js +607 -376
  4. package/lib/module/TrueSheet.web.js.map +1 -1
  5. package/lib/module/TrueSheetProvider.js.map +1 -1
  6. package/lib/module/TrueSheetProvider.web.js +141 -100
  7. package/lib/module/TrueSheetProvider.web.js.map +1 -1
  8. package/lib/module/mocks/index.js.map +1 -1
  9. package/lib/module/reanimated/ReanimatedTrueSheet.web.js.map +1 -1
  10. package/lib/module/reanimated/useReanimatedPositionChangeHandler.web.js +2 -3
  11. package/lib/module/reanimated/useReanimatedPositionChangeHandler.web.js.map +1 -1
  12. package/lib/module/web/constants.js +16 -0
  13. package/lib/module/web/constants.js.map +1 -0
  14. package/lib/module/web/vaul/README.md +9 -0
  15. package/lib/module/web/vaul/browser.js +30 -0
  16. package/lib/module/web/vaul/browser.js.map +1 -0
  17. package/lib/module/web/vaul/constants.js +14 -0
  18. package/lib/module/web/vaul/constants.js.map +1 -0
  19. package/lib/module/web/vaul/context.js +57 -0
  20. package/lib/module/web/vaul/context.js.map +1 -0
  21. package/lib/module/web/vaul/helpers.js +93 -0
  22. package/lib/module/web/vaul/helpers.js.map +1 -0
  23. package/lib/module/web/vaul/index.js +1226 -0
  24. package/lib/module/web/vaul/index.js.map +1 -0
  25. package/lib/module/web/vaul/style.css +264 -0
  26. package/lib/module/web/vaul/types.js +2 -0
  27. package/lib/module/web/vaul/types.js.map +1 -0
  28. package/lib/module/web/vaul/use-composed-refs.js +34 -0
  29. package/lib/module/web/vaul/use-composed-refs.js.map +1 -0
  30. package/lib/module/web/vaul/use-controllable-state.js +54 -0
  31. package/lib/module/web/vaul/use-controllable-state.js.map +1 -0
  32. package/lib/module/web/vaul/use-position-fixed.js +123 -0
  33. package/lib/module/web/vaul/use-position-fixed.js.map +1 -0
  34. package/lib/module/web/vaul/use-prevent-scroll.js +258 -0
  35. package/lib/module/web/vaul/use-prevent-scroll.js.map +1 -0
  36. package/lib/module/web/vaul/use-scale-background.js +57 -0
  37. package/lib/module/web/vaul/use-scale-background.js.map +1 -0
  38. package/lib/module/web/vaul/use-snap-points.js +294 -0
  39. package/lib/module/web/vaul/use-snap-points.js.map +1 -0
  40. package/lib/typescript/src/TrueSheet.d.ts +2 -2
  41. package/lib/typescript/src/TrueSheet.d.ts.map +1 -1
  42. package/lib/typescript/src/TrueSheet.types.d.ts +79 -36
  43. package/lib/typescript/src/TrueSheet.types.d.ts.map +1 -1
  44. package/lib/typescript/src/TrueSheet.web.d.ts +3 -11
  45. package/lib/typescript/src/TrueSheet.web.d.ts.map +1 -1
  46. package/lib/typescript/src/TrueSheetProvider.d.ts +2 -2
  47. package/lib/typescript/src/TrueSheetProvider.d.ts.map +1 -1
  48. package/lib/typescript/src/TrueSheetProvider.web.d.ts +17 -14
  49. package/lib/typescript/src/TrueSheetProvider.web.d.ts.map +1 -1
  50. package/lib/typescript/src/mocks/index.d.ts +1 -2
  51. package/lib/typescript/src/mocks/index.d.ts.map +1 -1
  52. package/lib/typescript/src/navigation/types.d.ts +1 -1
  53. package/lib/typescript/src/navigation/types.d.ts.map +1 -1
  54. package/lib/typescript/src/reanimated/ReanimatedTrueSheet.web.d.ts +0 -1
  55. package/lib/typescript/src/reanimated/ReanimatedTrueSheet.web.d.ts.map +1 -1
  56. package/lib/typescript/src/reanimated/useReanimatedPositionChangeHandler.web.d.ts +2 -3
  57. package/lib/typescript/src/reanimated/useReanimatedPositionChangeHandler.web.d.ts.map +1 -1
  58. package/lib/typescript/src/web/constants.d.ts +14 -0
  59. package/lib/typescript/src/web/constants.d.ts.map +1 -0
  60. package/lib/typescript/src/web/vaul/browser.d.ts +8 -0
  61. package/lib/typescript/src/web/vaul/browser.d.ts.map +1 -0
  62. package/lib/typescript/src/web/vaul/constants.d.ts +12 -0
  63. package/lib/typescript/src/web/vaul/constants.d.ts.map +1 -0
  64. package/lib/typescript/src/web/vaul/context.d.ts +45 -0
  65. package/lib/typescript/src/web/vaul/context.d.ts.map +1 -0
  66. package/lib/typescript/src/web/vaul/helpers.d.ts +17 -0
  67. package/lib/typescript/src/web/vaul/helpers.d.ts.map +1 -0
  68. package/lib/typescript/src/web/vaul/index.d.ts +210 -0
  69. package/lib/typescript/src/web/vaul/index.d.ts.map +1 -0
  70. package/lib/typescript/src/web/vaul/types.d.ts +7 -0
  71. package/lib/typescript/src/web/vaul/types.d.ts.map +1 -0
  72. package/lib/typescript/src/web/vaul/use-composed-refs.d.ts +14 -0
  73. package/lib/typescript/src/web/vaul/use-composed-refs.d.ts.map +1 -0
  74. package/lib/typescript/src/web/vaul/use-controllable-state.d.ts +9 -0
  75. package/lib/typescript/src/web/vaul/use-controllable-state.d.ts.map +1 -0
  76. package/lib/typescript/src/web/vaul/use-position-fixed.d.ts +19 -0
  77. package/lib/typescript/src/web/vaul/use-position-fixed.d.ts.map +1 -0
  78. package/lib/typescript/src/web/vaul/use-prevent-scroll.d.ts +18 -0
  79. package/lib/typescript/src/web/vaul/use-prevent-scroll.d.ts.map +1 -0
  80. package/lib/typescript/src/web/vaul/use-scale-background.d.ts +2 -0
  81. package/lib/typescript/src/web/vaul/use-scale-background.d.ts.map +1 -0
  82. package/lib/typescript/src/web/vaul/use-snap-points.d.ts +37 -0
  83. package/lib/typescript/src/web/vaul/use-snap-points.d.ts.map +1 -0
  84. package/package.json +4 -4
  85. package/src/TrueSheet.tsx +9 -1
  86. package/src/TrueSheet.types.ts +88 -38
  87. package/src/TrueSheet.web.tsx +677 -450
  88. package/src/TrueSheetProvider.tsx +2 -4
  89. package/src/TrueSheetProvider.web.tsx +193 -125
  90. package/src/mocks/index.ts +1 -2
  91. package/src/navigation/types.ts +0 -1
  92. package/src/reanimated/ReanimatedTrueSheet.web.tsx +0 -1
  93. package/src/reanimated/useReanimatedPositionChangeHandler.web.ts +2 -3
  94. package/src/web/constants.ts +13 -0
  95. package/src/web/vaul/README.md +9 -0
  96. package/src/web/vaul/browser.ts +38 -0
  97. package/src/web/vaul/constants.ts +18 -0
  98. package/src/web/vaul/context.ts +87 -0
  99. package/src/web/vaul/helpers.ts +124 -0
  100. package/src/web/vaul/index.tsx +1616 -0
  101. package/src/web/vaul/style.css +264 -0
  102. package/src/web/vaul/types.ts +7 -0
  103. package/src/web/vaul/use-composed-refs.ts +35 -0
  104. package/src/web/vaul/use-controllable-state.ts +66 -0
  105. package/src/web/vaul/use-position-fixed.ts +147 -0
  106. package/src/web/vaul/use-prevent-scroll.ts +309 -0
  107. package/src/web/vaul/use-scale-background.ts +64 -0
  108. package/src/web/vaul/use-snap-points.ts +433 -0
@@ -0,0 +1,1616 @@
1
+ 'use client';
2
+
3
+ import React from 'react';
4
+
5
+ import * as DialogPrimitive from '@radix-ui/react-dialog';
6
+
7
+ import { DrawerContext, useDrawerContext } from './context';
8
+ import './style.css';
9
+
10
+ import { isIOS, isMobileFirefox } from './browser';
11
+ import {
12
+ BORDER_RADIUS,
13
+ CLOSE_THRESHOLD,
14
+ DRAG_CLASS,
15
+ NESTED_DISPLACEMENT,
16
+ SCROLL_LOCK_TIMEOUT,
17
+ TRANSITIONS,
18
+ VELOCITY_THRESHOLD,
19
+ WINDOW_TOP_OFFSET,
20
+ } from './constants';
21
+ import { dampenValue, getTranslate, isVertical, reset, set } from './helpers';
22
+ import type { DrawerDirection } from './types';
23
+ import { useComposedRefs } from './use-composed-refs';
24
+ import { useControllableState } from './use-controllable-state';
25
+ import { usePositionFixed } from './use-position-fixed';
26
+ import { isInput, usePreventScroll } from './use-prevent-scroll';
27
+ import { useScaleBackground } from './use-scale-background';
28
+ import { useSnapPoints } from './use-snap-points';
29
+
30
+ export interface WithFadeFromProps {
31
+ /**
32
+ * Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up.
33
+ * Should go from least visible. Example `[0.2, 0.5, 0.8]`.
34
+ * You can also use px values, which doesn't take screen height into account.
35
+ */
36
+ snapPoints: (number | string)[];
37
+ /**
38
+ * Index of a `snapPoint` from which the overlay fade should be applied. Defaults to the last snap point.
39
+ */
40
+ fadeFromIndex: number;
41
+ }
42
+
43
+ export interface WithoutFadeFromProps {
44
+ /**
45
+ * Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up.
46
+ * Should go from least visible. Example `[0.2, 0.5, 0.8]`.
47
+ * You can also use px values, which doesn't take screen height into account.
48
+ */
49
+ snapPoints?: (number | string)[];
50
+ fadeFromIndex?: never;
51
+ }
52
+
53
+ export type DialogProps = {
54
+ activeSnapPoint?: number | string | null;
55
+ setActiveSnapPoint?: (snapPoint: number | string | null) => void;
56
+ children?: React.ReactNode;
57
+ open?: boolean;
58
+ /**
59
+ * Number between 0 and 1 that determines when the drawer should be closed.
60
+ * Example: threshold of 0.5 would close the drawer if the user swiped for 50% of the height of the drawer or more.
61
+ * @default 0.25
62
+ */
63
+ closeThreshold?: number;
64
+ /**
65
+ * When `true` the `body` doesn't get any styles assigned from Vaul
66
+ */
67
+ noBodyStyles?: boolean;
68
+ onOpenChange?: (open: boolean) => void;
69
+ shouldScaleBackground?: boolean;
70
+ /**
71
+ * When `false` we don't change body's background color when the drawer is open.
72
+ * @default true
73
+ */
74
+ setBackgroundColorOnScale?: boolean;
75
+ /**
76
+ * Duration for which the drawer is not draggable after scrolling content inside of the drawer.
77
+ * @default 500ms
78
+ */
79
+ scrollLockTimeout?: number;
80
+ /**
81
+ * When `true`, don't move the drawer upwards if there's space, but rather only change it's height so it's fully scrollable when the keyboard is open
82
+ */
83
+ fixed?: boolean;
84
+ /**
85
+ * When `true` only allows the drawer to be dragged by the `<Drawer.Handle />` component.
86
+ * @default false
87
+ */
88
+ handleOnly?: boolean;
89
+ /**
90
+ * When `false` dragging, clicking outside, pressing esc, etc. will not close the drawer.
91
+ * Use this in comination with the `open` prop, otherwise you won't be able to open/close the drawer.
92
+ * @default true
93
+ */
94
+ dismissible?: boolean;
95
+ /**
96
+ * When `false` the drawer can't be dragged by the user. Programmatic snap-point
97
+ * changes still animate. Defaults to `true`.
98
+ */
99
+ draggable?: boolean;
100
+ onDrag?: (event: React.PointerEvent<HTMLDivElement>, percentageDragged: number) => void;
101
+ onRelease?: (event: React.PointerEvent<HTMLDivElement>, open: boolean) => void;
102
+ /**
103
+ * When `false` it allows to interact with elements outside of the drawer without closing it.
104
+ * @default true
105
+ */
106
+ modal?: boolean;
107
+ nested?: boolean;
108
+ onClose?: () => void;
109
+ /**
110
+ * Direction of the drawer. Can be `top` or `bottom`, `left`, `right`.
111
+ * @default 'bottom'
112
+ */
113
+ direction?: 'top' | 'bottom' | 'left' | 'right';
114
+ /**
115
+ * Opened by default, skips initial enter animation. Still reacts to `open` state changes
116
+ * @default false
117
+ */
118
+ defaultOpen?: boolean;
119
+ /**
120
+ * When set to `true` prevents scrolling on the document body on mount, and restores it on unmount.
121
+ * @default false
122
+ */
123
+ disablePreventScroll?: boolean;
124
+ /**
125
+ * When `true` Vaul will reposition inputs rather than scroll then into view if the keyboard is in the way.
126
+ * Setting it to `false` will fall back to the default browser behavior.
127
+ * @default true when {@link snapPoints} is defined
128
+ */
129
+ repositionInputs?: boolean;
130
+ /**
131
+ * Disabled velocity based swiping for snap points.
132
+ * This means that a snap point won't be skipped even if the velocity is high enough.
133
+ * Useful if each snap point in a drawer is equally important.
134
+ * @default false
135
+ */
136
+ snapToSequentialPoint?: boolean;
137
+ container?: HTMLElement | null;
138
+ /**
139
+ * Gets triggered after the open or close animation ends, it receives an `open` argument with the `open` state of the drawer by the time the function was triggered.
140
+ * Useful to revert any state changes for example.
141
+ */
142
+ onAnimationEnd?: (open: boolean) => void;
143
+ /**
144
+ * Fires on every animation frame while the drawer is open with the drawer's
145
+ * current top edge in the viewport (px). Emits during drag, snap, and the
146
+ * open/close transitions.
147
+ */
148
+ onPositionChange?: (position: number) => void;
149
+ preventScrollRestoration?: boolean;
150
+ autoFocus?: boolean;
151
+ /**
152
+ * Renders the drawer as a floating card offset from the bottom edge so it
153
+ * doesn't visually attach to the viewport. Snap points are computed against
154
+ * the reduced floating area, so {@link detachedOffset} is preserved during
155
+ * drag and snap.
156
+ * @default false
157
+ */
158
+ detached?: boolean;
159
+ /**
160
+ * Gap (in px) between the drawer's bottom edge and the viewport bottom when
161
+ * {@link detached} is `true`.
162
+ * @default 0
163
+ */
164
+ detachedOffset?: number;
165
+ /**
166
+ * Corner radius (in px) applied to the clip wrapper's bottom when
167
+ * {@link detached} is `true`, so the floating card's bottom edge stays
168
+ * rounded while it's clipped at the floating anchor.
169
+ * @default 0
170
+ */
171
+ detachedRadius?: number;
172
+ /**
173
+ * Extra styles merged into the detached clip wrapper. Use this to match the
174
+ * wrapper's horizontal bounds to the drawer's on desktop (e.g. `maxWidth` +
175
+ * auto margins) so its rounded-bottom clip aligns with the drawer.
176
+ */
177
+ detachedWrapperStyle?: React.CSSProperties;
178
+ /**
179
+ * Caps the visible sheet height (in px) so full and 'auto' snap points
180
+ * respect a user-specified ceiling.
181
+ */
182
+ maxContentHeight?: number;
183
+ /**
184
+ * When `false` the first snap on mount is applied without a transition so
185
+ * the sheet appears at its target detent instantly. Defaults to `true`.
186
+ */
187
+ initialAnimated?: boolean;
188
+ } & (WithFadeFromProps | WithoutFadeFromProps);
189
+
190
+ export function Root({
191
+ open: openProp,
192
+ onOpenChange,
193
+ children,
194
+ onDrag: onDragProp,
195
+ onRelease: onReleaseProp,
196
+ snapPoints,
197
+ shouldScaleBackground = false,
198
+ setBackgroundColorOnScale = true,
199
+ closeThreshold = CLOSE_THRESHOLD,
200
+ scrollLockTimeout = SCROLL_LOCK_TIMEOUT,
201
+ dismissible = true,
202
+ draggable = true,
203
+ handleOnly = false,
204
+ fadeFromIndex = snapPoints && snapPoints.length - 1,
205
+ activeSnapPoint: activeSnapPointProp,
206
+ setActiveSnapPoint: setActiveSnapPointProp,
207
+ fixed,
208
+ modal = true,
209
+ onClose,
210
+ nested,
211
+ noBodyStyles = false,
212
+ direction = 'bottom',
213
+ defaultOpen = false,
214
+ disablePreventScroll = true,
215
+ snapToSequentialPoint = false,
216
+ preventScrollRestoration = false,
217
+ repositionInputs = true,
218
+ onAnimationEnd,
219
+ onPositionChange,
220
+ container,
221
+ autoFocus = false,
222
+ detached = false,
223
+ detachedOffset = 0,
224
+ detachedRadius = 0,
225
+ detachedWrapperStyle,
226
+ maxContentHeight,
227
+ initialAnimated = true,
228
+ }: DialogProps) {
229
+ const [isOpen = false, setIsOpen] = useControllableState({
230
+ defaultProp: defaultOpen,
231
+ prop: openProp,
232
+ onChange: (o: boolean) => {
233
+ onOpenChange?.(o);
234
+
235
+ if (!o && !nested) {
236
+ restorePositionSetting();
237
+ }
238
+
239
+ setTimeout(() => {
240
+ onAnimationEnd?.(o);
241
+ }, TRANSITIONS.DURATION * 1000);
242
+
243
+ if (o && !modal) {
244
+ if (typeof window !== 'undefined') {
245
+ window.requestAnimationFrame(() => {
246
+ document.body.style.pointerEvents = 'auto';
247
+ });
248
+ }
249
+ }
250
+
251
+ if (!o) {
252
+ // This will be removed when the exit animation ends (`500ms`)
253
+ document.body.style.pointerEvents = 'auto';
254
+ }
255
+ },
256
+ });
257
+ const [hasBeenOpened, setHasBeenOpened] = React.useState<boolean>(false);
258
+ const [isDragging, setIsDragging] = React.useState<boolean>(false);
259
+ const [justReleased, setJustReleased] = React.useState<boolean>(false);
260
+ const overlayRef = React.useRef<HTMLDivElement>(null);
261
+ const openTime = React.useRef<Date | null>(null);
262
+ const dragStartTime = React.useRef<Date | null>(null);
263
+ const dragEndTime = React.useRef<Date | null>(null);
264
+ const lastTimeDragPrevented = React.useRef<Date | null>(null);
265
+ const isAllowedToDrag = React.useRef<boolean>(false);
266
+ const nestedOpenChangeTimer = React.useRef<NodeJS.Timeout | null>(null);
267
+ const pointerStart = React.useRef(0);
268
+ const keyboardIsOpen = React.useRef(false);
269
+ const shouldAnimate = React.useRef(!defaultOpen);
270
+ const previousDiffFromInitial = React.useRef(0);
271
+ const drawerRef = React.useRef<HTMLDivElement>(null);
272
+ const drawerHeightRef = React.useRef(drawerRef.current?.getBoundingClientRect().height || 0);
273
+ const drawerWidthRef = React.useRef(drawerRef.current?.getBoundingClientRect().width || 0);
274
+ const initialDrawerHeight = React.useRef(0);
275
+ const [contentHeight, setContentHeight] = React.useState(0);
276
+
277
+ const onSnapPointChange = React.useCallback((activeSnapPointIndex: number) => {
278
+ // Change openTime ref when we reach the last snap point to prevent dragging for 500ms incase it's scrollable.
279
+ if (snapPoints && activeSnapPointIndex === snapPointsOffset.length - 1)
280
+ openTime.current = new Date();
281
+ }, []);
282
+
283
+ const {
284
+ activeSnapPoint,
285
+ activeSnapPointIndex,
286
+ setActiveSnapPoint,
287
+ onRelease: onReleaseSnapPoints,
288
+ snapPointsOffset,
289
+ onDrag: onDragSnapPoints,
290
+ shouldFade,
291
+ getPercentageDragged: getSnapPointsPercentageDragged,
292
+ } = useSnapPoints({
293
+ snapPoints,
294
+ activeSnapPointProp,
295
+ setActiveSnapPointProp,
296
+ drawerRef,
297
+ fadeFromIndex,
298
+ overlayRef,
299
+ onSnapPointChange,
300
+ direction,
301
+ container,
302
+ snapToSequentialPoint,
303
+ isOpen,
304
+ contentHeight,
305
+ detachedOffset: detached ? detachedOffset : 0,
306
+ maxContentHeight,
307
+ initialAnimated,
308
+ });
309
+
310
+ usePreventScroll({
311
+ isDisabled:
312
+ !isOpen ||
313
+ isDragging ||
314
+ !modal ||
315
+ justReleased ||
316
+ !hasBeenOpened ||
317
+ !repositionInputs ||
318
+ !disablePreventScroll,
319
+ });
320
+
321
+ const { restorePositionSetting } = usePositionFixed({
322
+ isOpen,
323
+ modal,
324
+ nested: nested ?? false,
325
+ hasBeenOpened,
326
+ preventScrollRestoration,
327
+ noBodyStyles,
328
+ });
329
+
330
+ function getScale() {
331
+ return (window.innerWidth - WINDOW_TOP_OFFSET) / window.innerWidth;
332
+ }
333
+
334
+ function onPress(event: React.PointerEvent<HTMLDivElement>) {
335
+ if (!draggable) return;
336
+ if (!dismissible && !snapPoints) return;
337
+ if (drawerRef.current && !drawerRef.current.contains(event.target as Node)) return;
338
+
339
+ drawerHeightRef.current = drawerRef.current?.getBoundingClientRect().height || 0;
340
+ drawerWidthRef.current = drawerRef.current?.getBoundingClientRect().width || 0;
341
+ setIsDragging(true);
342
+ dragStartTime.current = new Date();
343
+
344
+ // iOS doesn't trigger mouseUp after scrolling so we need to listen to touched in order to disallow dragging
345
+ if (isIOS()) {
346
+ window.addEventListener('touchend', () => (isAllowedToDrag.current = false), { once: true });
347
+ }
348
+ // Ensure we maintain correct pointer capture even when going outside of the drawer
349
+ (event.target as HTMLElement).setPointerCapture(event.pointerId);
350
+
351
+ pointerStart.current = isVertical(direction) ? event.pageY : event.pageX;
352
+ }
353
+
354
+ function shouldDrag(el: EventTarget, isDraggingInDirection: boolean) {
355
+ let element = el as HTMLElement;
356
+ const highlightedText = window.getSelection()?.toString();
357
+ const swipeAmount = drawerRef.current ? getTranslate(drawerRef.current, direction) : null;
358
+ const date = new Date();
359
+
360
+ // Fixes https://github.com/emilkowalski/vaul/issues/483
361
+ if (element.tagName === 'SELECT') {
362
+ return false;
363
+ }
364
+
365
+ if (element.hasAttribute('data-vaul-no-drag') || element.closest('[data-vaul-no-drag]')) {
366
+ return false;
367
+ }
368
+
369
+ if (direction === 'right' || direction === 'left') {
370
+ return true;
371
+ }
372
+
373
+ // Allow scrolling when animating
374
+ if (openTime.current && date.getTime() - openTime.current.getTime() < 500) {
375
+ return false;
376
+ }
377
+
378
+ if (swipeAmount !== null) {
379
+ if (direction === 'bottom' ? swipeAmount > 0 : swipeAmount < 0) {
380
+ return true;
381
+ }
382
+ }
383
+
384
+ // Don't drag if there's highlighted text
385
+ if (highlightedText && highlightedText.length > 0) {
386
+ return false;
387
+ }
388
+
389
+ // Disallow dragging if drawer was scrolled within `scrollLockTimeout`
390
+ if (
391
+ lastTimeDragPrevented.current &&
392
+ date.getTime() - lastTimeDragPrevented.current.getTime() < scrollLockTimeout &&
393
+ swipeAmount === 0
394
+ ) {
395
+ lastTimeDragPrevented.current = date;
396
+ return false;
397
+ }
398
+
399
+ if (isDraggingInDirection) {
400
+ lastTimeDragPrevented.current = date;
401
+
402
+ // We are dragging down so we should allow scrolling
403
+ return false;
404
+ }
405
+
406
+ // Keep climbing up the DOM tree as long as there's a parent
407
+ while (element) {
408
+ // Check if the element is scrollable
409
+ if (element.scrollHeight > element.clientHeight) {
410
+ if (element.scrollTop !== 0) {
411
+ lastTimeDragPrevented.current = new Date();
412
+
413
+ // The element is scrollable and not scrolled to the top, so don't drag
414
+ return false;
415
+ }
416
+
417
+ if (element.getAttribute('role') === 'dialog') {
418
+ return true;
419
+ }
420
+ }
421
+
422
+ // Move up to the parent element
423
+ element = element.parentNode as HTMLElement;
424
+ }
425
+
426
+ // No scrollable parents not scrolled to the top found, so drag
427
+ return true;
428
+ }
429
+
430
+ function onDrag(event: React.PointerEvent<HTMLDivElement>) {
431
+ if (!drawerRef.current) {
432
+ return;
433
+ }
434
+
435
+ // We need to know how much of the drawer has been dragged in percentages so that we can transform background accordingly
436
+ if (isDragging) {
437
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
438
+ const draggedDistance =
439
+ (pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX)) *
440
+ directionMultiplier;
441
+ const isDraggingInDirection = draggedDistance > 0;
442
+
443
+ // Pre condition for disallowing dragging in the close direction.
444
+ const noCloseSnapPointsPreCondition = snapPoints && !dismissible && !isDraggingInDirection;
445
+
446
+ // Disallow dragging down to close when first snap point is the active one and dismissible prop is set to false.
447
+ if (noCloseSnapPointsPreCondition && activeSnapPointIndex === 0) return;
448
+
449
+ // We need to capture last time when drag with scroll was triggered and have a timeout between
450
+ const absDraggedDistance = Math.abs(draggedDistance);
451
+ const wrapper = document.querySelector('[data-vaul-drawer-wrapper]');
452
+ const drawerDimension =
453
+ direction === 'bottom' || direction === 'top'
454
+ ? drawerHeightRef.current
455
+ : drawerWidthRef.current;
456
+
457
+ // Calculate the percentage dragged, where 1 is the closed position
458
+ let percentageDragged = absDraggedDistance / drawerDimension;
459
+ const snapPointPercentageDragged = getSnapPointsPercentageDragged(
460
+ absDraggedDistance,
461
+ isDraggingInDirection
462
+ );
463
+
464
+ if (snapPointPercentageDragged !== null) {
465
+ percentageDragged = snapPointPercentageDragged;
466
+ }
467
+
468
+ // Disallow close dragging beyond the smallest snap point.
469
+ if (noCloseSnapPointsPreCondition && percentageDragged >= 1) {
470
+ return;
471
+ }
472
+
473
+ if (!isAllowedToDrag.current && !shouldDrag(event.target, isDraggingInDirection)) return;
474
+ drawerRef.current.classList.add(DRAG_CLASS);
475
+ // If shouldDrag gave true once after pressing down on the drawer, we set isAllowedToDrag to true and it will remain true until we let go, there's no reason to disable dragging mid way, ever, and that's the solution to it
476
+ isAllowedToDrag.current = true;
477
+ set(drawerRef.current, {
478
+ transition: 'none',
479
+ });
480
+
481
+ set(overlayRef.current, {
482
+ transition: 'none',
483
+ });
484
+
485
+ onDragProp?.(event, percentageDragged);
486
+
487
+ if (snapPoints) {
488
+ onDragSnapPoints({ draggedDistance });
489
+ }
490
+
491
+ // Run this only if snapPoints are not defined or if we are at the last snap point (highest one)
492
+ if (isDraggingInDirection && !snapPoints) {
493
+ const dampenedDraggedDistance = dampenValue(draggedDistance);
494
+
495
+ const translateValue = Math.min(dampenedDraggedDistance * -1, 0) * directionMultiplier;
496
+ set(drawerRef.current, {
497
+ transform: isVertical(direction)
498
+ ? `translate3d(0, ${translateValue}px, 0)`
499
+ : `translate3d(${translateValue}px, 0, 0)`,
500
+ });
501
+ return;
502
+ }
503
+
504
+ const opacityValue = 1 - percentageDragged;
505
+
506
+ if (shouldFade || (fadeFromIndex && activeSnapPointIndex === fadeFromIndex - 1)) {
507
+ set(
508
+ overlayRef.current,
509
+ {
510
+ opacity: `${opacityValue}`,
511
+ transition: 'none',
512
+ },
513
+ true
514
+ );
515
+ }
516
+
517
+ if (wrapper && overlayRef.current && shouldScaleBackground) {
518
+ // Calculate percentageDragged as a fraction (0 to 1)
519
+ const scaleValue = Math.min(getScale() + percentageDragged * (1 - getScale()), 1);
520
+ const borderRadiusValue = 8 - percentageDragged * 8;
521
+
522
+ const translateValue = Math.max(0, 14 - percentageDragged * 14);
523
+
524
+ set(
525
+ wrapper,
526
+ {
527
+ borderRadius: `${borderRadiusValue}px`,
528
+ transform: isVertical(direction)
529
+ ? `scale(${scaleValue}) translate3d(0, ${translateValue}px, 0)`
530
+ : `scale(${scaleValue}) translate3d(${translateValue}px, 0, 0)`,
531
+ transition: 'none',
532
+ },
533
+ true
534
+ );
535
+ }
536
+
537
+ if (!snapPoints) {
538
+ const translateValue = absDraggedDistance * directionMultiplier;
539
+
540
+ set(drawerRef.current, {
541
+ transform: isVertical(direction)
542
+ ? `translate3d(0, ${translateValue}px, 0)`
543
+ : `translate3d(${translateValue}px, 0, 0)`,
544
+ });
545
+ }
546
+ }
547
+ }
548
+
549
+ React.useEffect(() => {
550
+ window.requestAnimationFrame(() => {
551
+ shouldAnimate.current = true;
552
+ });
553
+ }, []);
554
+
555
+ // Reset to the first snap point on every open so a prior session's active snap
556
+ // (kept in state by `useControllableState` after dismissal) doesn't leak into
557
+ // the next present. Skipped when `activeSnapPoint` is controlled externally.
558
+ React.useEffect(() => {
559
+ if (isOpen && snapPoints && activeSnapPointProp === undefined) {
560
+ setActiveSnapPoint(snapPoints[0]);
561
+ }
562
+ }, [isOpen]);
563
+
564
+ const onPositionChangeRef = React.useRef(onPositionChange);
565
+ React.useEffect(() => {
566
+ onPositionChangeRef.current = onPositionChange;
567
+ });
568
+
569
+ // Radix's DismissableLayer (modal) sets body pointer-events to "none" so the
570
+ // overlay traps clicks. When the active snap is below fadeFromIndex the
571
+ // overlay is fully transparent, and we want clicks to reach the content
572
+ // behind the drawer — so we restore body interactivity. DismissableLayer
573
+ // captures its DOM node via a ref-callback `setNode`, so its body write
574
+ // runs one render later than ours on initial open — re-assert on rAF so
575
+ // the final write is ours.
576
+ React.useEffect(() => {
577
+ if (!modal || !snapPoints || fadeFromIndex === undefined) return;
578
+ // On close, restore body interactivity. `useControllableState.onChange`
579
+ // only fires for internal `setIsOpen` calls — when the parent flips the
580
+ // `open` prop imperatively, the reset at line ~201 never runs.
581
+ if (!isOpen) {
582
+ document.body.style.pointerEvents = 'auto';
583
+ return;
584
+ }
585
+ if (typeof activeSnapPointIndex !== 'number') return;
586
+ const isBelowFade = activeSnapPointIndex < fadeFromIndex;
587
+ const value = isBelowFade ? 'auto' : 'none';
588
+ document.body.style.pointerEvents = value;
589
+ const id = window.requestAnimationFrame(() => {
590
+ document.body.style.pointerEvents = value;
591
+ });
592
+
593
+ // React Navigation keeps unfocused screens mounted with `display: none` on
594
+ // web, so the drawer never unmounts and neither `isOpen` nor this effect's
595
+ // deps change — a lingering `none` body style would then leak to whichever
596
+ // screen becomes visible. Observe the drawer: when an ancestor hides it,
597
+ // restore `auto`; when it returns, re-apply the desired value.
598
+ let observer: IntersectionObserver | null = null;
599
+ let rafId = 0;
600
+ const startObserving = () => {
601
+ const node = drawerRef.current;
602
+ if (!node) {
603
+ rafId = window.requestAnimationFrame(startObserving);
604
+ return;
605
+ }
606
+ observer = new IntersectionObserver((entries) => {
607
+ const entry = entries[entries.length - 1];
608
+ if (!entry) return;
609
+ document.body.style.pointerEvents = entry.isIntersecting ? value : 'auto';
610
+ });
611
+ observer.observe(node);
612
+ };
613
+ rafId = window.requestAnimationFrame(startObserving);
614
+
615
+ // Always restore on cleanup so an unmount while the sheet is still open
616
+ // doesn't leave the page uninteractive. If the effect re-runs for a
617
+ // normal state change, it re-applies the correct value.
618
+ return () => {
619
+ window.cancelAnimationFrame(id);
620
+ window.cancelAnimationFrame(rafId);
621
+ observer?.disconnect();
622
+ document.body.style.pointerEvents = 'auto';
623
+ };
624
+ }, [isOpen, modal, snapPoints, fadeFromIndex, activeSnapPointIndex]);
625
+
626
+ // Radix DismissableLayer's body-restore on unmount is broken: its two
627
+ // useEffects (see @radix-ui/react-dismissable-layer dist/index.mjs:68-92)
628
+ // run cleanups in reverse declaration order, so the layers-set decrement
629
+ // (effect B) runs BEFORE the size-1 body-restore check (effect A). When
630
+ // the last layer unmounts, A sees size=0 and skips the restore — body
631
+ // stays 'none'. Take ownership of the restore here on Drawer.Root unmount.
632
+ // Skipped when nested or non-modal so an inner drawer's unmount doesn't
633
+ // unlock an outer drawer's modal trap. Also bail if any other Radix
634
+ // dismissable layer is still open (sibling Dialog/AlertDialog/Popover) —
635
+ // that one wants the lock kept.
636
+ React.useEffect(() => {
637
+ if (nested || !modal) return;
638
+ return () => {
639
+ if (typeof document === 'undefined') return;
640
+ if (document.body.style.pointerEvents !== 'none') return;
641
+ if (
642
+ document.querySelector(
643
+ '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]'
644
+ )
645
+ )
646
+ return;
647
+ document.body.style.pointerEvents = 'auto';
648
+ };
649
+ }, [nested, modal]);
650
+
651
+ React.useEffect(() => {
652
+ function onVisualViewportChange() {
653
+ if (!drawerRef.current || !repositionInputs) return;
654
+
655
+ const focusedElement = document.activeElement as HTMLElement;
656
+ if (isInput(focusedElement) || keyboardIsOpen.current) {
657
+ const visualViewportHeight = window.visualViewport?.height || 0;
658
+ const totalHeight = window.innerHeight;
659
+ // This is the height of the keyboard
660
+ let diffFromInitial = totalHeight - visualViewportHeight;
661
+ const drawerHeight = drawerRef.current.getBoundingClientRect().height || 0;
662
+ // Adjust drawer height only if it's tall enough
663
+ const isTallEnough = drawerHeight > totalHeight * 0.8;
664
+
665
+ if (!initialDrawerHeight.current) {
666
+ initialDrawerHeight.current = drawerHeight;
667
+ }
668
+ const offsetFromTop = drawerRef.current.getBoundingClientRect().top;
669
+
670
+ // visualViewport height may change due to somq e subtle changes to the keyboard. Checking if the height changed by 60 or more will make sure that they keyboard really changed its open state.
671
+ if (Math.abs(previousDiffFromInitial.current - diffFromInitial) > 60) {
672
+ keyboardIsOpen.current = !keyboardIsOpen.current;
673
+ }
674
+
675
+ if (snapPoints && snapPoints.length > 0 && snapPointsOffset && activeSnapPointIndex) {
676
+ const activeSnapPointHeight = snapPointsOffset[activeSnapPointIndex] || 0;
677
+ diffFromInitial += activeSnapPointHeight;
678
+ }
679
+ previousDiffFromInitial.current = diffFromInitial;
680
+ // We don't have to change the height if the input is in view, when we are here we are in the opened keyboard state so we can correctly check if the input is in view
681
+ if (drawerHeight > visualViewportHeight || keyboardIsOpen.current) {
682
+ const height = drawerRef.current.getBoundingClientRect().height;
683
+ let newDrawerHeight = height;
684
+
685
+ if (height > visualViewportHeight) {
686
+ newDrawerHeight =
687
+ visualViewportHeight - (isTallEnough ? offsetFromTop : WINDOW_TOP_OFFSET);
688
+ }
689
+ // When fixed, don't move the drawer upwards if there's space, but rather only change it's height so it's fully scrollable when the keyboard is open
690
+ if (fixed) {
691
+ drawerRef.current.style.height = `${height - Math.max(diffFromInitial, 0)}px`;
692
+ } else {
693
+ drawerRef.current.style.height = `${Math.max(newDrawerHeight, visualViewportHeight - offsetFromTop)}px`;
694
+ }
695
+ } else if (!isMobileFirefox()) {
696
+ drawerRef.current.style.height = `${initialDrawerHeight.current}px`;
697
+ }
698
+
699
+ if (snapPoints && snapPoints.length > 0 && !keyboardIsOpen.current) {
700
+ drawerRef.current.style.bottom = '0px';
701
+ } else {
702
+ // Negative bottom value would never make sense
703
+ drawerRef.current.style.bottom = `${Math.max(diffFromInitial, 0)}px`;
704
+ }
705
+ }
706
+ }
707
+
708
+ window.visualViewport?.addEventListener('resize', onVisualViewportChange);
709
+ return () => window.visualViewport?.removeEventListener('resize', onVisualViewportChange);
710
+ }, [activeSnapPointIndex, snapPoints, snapPointsOffset]);
711
+
712
+ function closeDrawer(fromWithin?: boolean) {
713
+ cancelDrag();
714
+ onClose?.();
715
+
716
+ if (!fromWithin) {
717
+ setIsOpen(false);
718
+ }
719
+ }
720
+
721
+ function resetDrawer() {
722
+ if (!drawerRef.current) return;
723
+ const wrapper = document.querySelector('[data-vaul-drawer-wrapper]');
724
+ const currentSwipeAmount = getTranslate(drawerRef.current, direction);
725
+
726
+ set(drawerRef.current, {
727
+ transform: 'translate3d(0, 0, 0)',
728
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
729
+ });
730
+
731
+ set(overlayRef.current, {
732
+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
733
+ opacity: '1',
734
+ });
735
+
736
+ // Don't reset background if swiped upwards
737
+ if (shouldScaleBackground && currentSwipeAmount && currentSwipeAmount > 0 && isOpen) {
738
+ set(
739
+ wrapper,
740
+ {
741
+ borderRadius: `${BORDER_RADIUS}px`,
742
+ overflow: 'hidden',
743
+ ...(isVertical(direction)
744
+ ? {
745
+ transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
746
+ transformOrigin: 'top',
747
+ }
748
+ : {
749
+ transform: `scale(${getScale()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,
750
+ transformOrigin: 'left',
751
+ }),
752
+ transitionProperty: 'transform, border-radius',
753
+ transitionDuration: `${TRANSITIONS.DURATION}s`,
754
+ transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
755
+ },
756
+ true
757
+ );
758
+ }
759
+ }
760
+
761
+ function cancelDrag() {
762
+ if (!isDragging || !drawerRef.current) return;
763
+
764
+ drawerRef.current.classList.remove(DRAG_CLASS);
765
+ isAllowedToDrag.current = false;
766
+ setIsDragging(false);
767
+ dragEndTime.current = new Date();
768
+ }
769
+
770
+ function onRelease(event: React.PointerEvent<HTMLDivElement> | null) {
771
+ if (!isDragging || !drawerRef.current) return;
772
+
773
+ drawerRef.current.classList.remove(DRAG_CLASS);
774
+ isAllowedToDrag.current = false;
775
+ setIsDragging(false);
776
+ dragEndTime.current = new Date();
777
+ const swipeAmount = getTranslate(drawerRef.current, direction);
778
+
779
+ if (!event || !shouldDrag(event.target, false) || !swipeAmount || Number.isNaN(swipeAmount))
780
+ return;
781
+
782
+ if (dragStartTime.current === null) return;
783
+
784
+ const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
785
+ const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
786
+ const velocity = Math.abs(distMoved) / timeTaken;
787
+
788
+ if (velocity > 0.05) {
789
+ // `justReleased` is needed to prevent the drawer from focusing on an input when the drag ends, as it's not the intent most of the time.
790
+ setJustReleased(true);
791
+
792
+ setTimeout(() => {
793
+ setJustReleased(false);
794
+ }, 200);
795
+ }
796
+
797
+ if (snapPoints) {
798
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
799
+ onReleaseSnapPoints({
800
+ draggedDistance: distMoved * directionMultiplier,
801
+ closeDrawer,
802
+ velocity,
803
+ dismissible,
804
+ });
805
+ onReleaseProp?.(event, true);
806
+ return;
807
+ }
808
+
809
+ // Moved upwards, don't do anything
810
+ if (direction === 'bottom' || direction === 'right' ? distMoved > 0 : distMoved < 0) {
811
+ resetDrawer();
812
+ onReleaseProp?.(event, true);
813
+ return;
814
+ }
815
+
816
+ if (velocity > VELOCITY_THRESHOLD) {
817
+ closeDrawer();
818
+ onReleaseProp?.(event, false);
819
+ return;
820
+ }
821
+
822
+ const visibleDrawerHeight = Math.min(
823
+ drawerRef.current.getBoundingClientRect().height ?? 0,
824
+ window.innerHeight
825
+ );
826
+ const visibleDrawerWidth = Math.min(
827
+ drawerRef.current.getBoundingClientRect().width ?? 0,
828
+ window.innerWidth
829
+ );
830
+
831
+ const isHorizontalSwipe = direction === 'left' || direction === 'right';
832
+ if (
833
+ Math.abs(swipeAmount) >=
834
+ (isHorizontalSwipe ? visibleDrawerWidth : visibleDrawerHeight) * closeThreshold
835
+ ) {
836
+ closeDrawer();
837
+ onReleaseProp?.(event, false);
838
+ return;
839
+ }
840
+
841
+ onReleaseProp?.(event, true);
842
+ resetDrawer();
843
+ }
844
+
845
+ React.useEffect(() => {
846
+ // Trigger enter animation without using CSS animation
847
+ if (isOpen) {
848
+ set(document.documentElement, {
849
+ scrollBehavior: 'auto',
850
+ });
851
+
852
+ openTime.current = new Date();
853
+ }
854
+
855
+ return () => {
856
+ reset(document.documentElement, 'scrollBehavior');
857
+ };
858
+ }, [isOpen]);
859
+
860
+ function onNestedOpenChange(o: boolean) {
861
+ const scale = o ? (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth : 1;
862
+
863
+ const initialTranslate = o ? -NESTED_DISPLACEMENT : 0;
864
+
865
+ if (nestedOpenChangeTimer.current) {
866
+ window.clearTimeout(nestedOpenChangeTimer.current);
867
+ }
868
+
869
+ set(drawerRef.current, {
870
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
871
+ transform: isVertical(direction)
872
+ ? `scale(${scale}) translate3d(0, ${initialTranslate}px, 0)`
873
+ : `scale(${scale}) translate3d(${initialTranslate}px, 0, 0)`,
874
+ });
875
+
876
+ if (!o && drawerRef.current) {
877
+ nestedOpenChangeTimer.current = setTimeout(() => {
878
+ const translateValue = getTranslate(drawerRef.current as HTMLElement, direction);
879
+ set(drawerRef.current, {
880
+ transition: 'none',
881
+ transform: isVertical(direction)
882
+ ? `translate3d(0, ${translateValue}px, 0)`
883
+ : `translate3d(${translateValue}px, 0, 0)`,
884
+ });
885
+ }, 500);
886
+ }
887
+ }
888
+
889
+ function onNestedDrag(_event: React.PointerEvent<HTMLDivElement>, percentageDragged: number) {
890
+ if (percentageDragged < 0) return;
891
+
892
+ const initialScale = (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth;
893
+ const newScale = initialScale + percentageDragged * (1 - initialScale);
894
+ const newTranslate = -NESTED_DISPLACEMENT + percentageDragged * NESTED_DISPLACEMENT;
895
+
896
+ set(drawerRef.current, {
897
+ transform: isVertical(direction)
898
+ ? `scale(${newScale}) translate3d(0, ${newTranslate}px, 0)`
899
+ : `scale(${newScale}) translate3d(${newTranslate}px, 0, 0)`,
900
+ transition: 'none',
901
+ });
902
+ }
903
+
904
+ function onNestedRelease(_event: React.PointerEvent<HTMLDivElement>, o: boolean) {
905
+ const dim = isVertical(direction) ? window.innerHeight : window.innerWidth;
906
+ const scale = o ? (dim - NESTED_DISPLACEMENT) / dim : 1;
907
+ const translate = o ? -NESTED_DISPLACEMENT : 0;
908
+
909
+ if (o) {
910
+ set(drawerRef.current, {
911
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
912
+ transform: isVertical(direction)
913
+ ? `scale(${scale}) translate3d(0, ${translate}px, 0)`
914
+ : `scale(${scale}) translate3d(${translate}px, 0, 0)`,
915
+ });
916
+ }
917
+ }
918
+
919
+ React.useEffect(() => {
920
+ if (!modal) {
921
+ // Need to do this manually unfortunately
922
+ window.requestAnimationFrame(() => {
923
+ document.body.style.pointerEvents = 'auto';
924
+ });
925
+ }
926
+ }, [modal]);
927
+
928
+ return (
929
+ <DialogPrimitive.Root
930
+ defaultOpen={defaultOpen}
931
+ onOpenChange={(open) => {
932
+ if (!dismissible && !open) return;
933
+ if (open) {
934
+ setHasBeenOpened(true);
935
+ } else {
936
+ closeDrawer(true);
937
+ }
938
+
939
+ setIsOpen(open);
940
+ }}
941
+ open={isOpen}
942
+ modal={modal}
943
+ >
944
+ <DrawerContext.Provider
945
+ value={{
946
+ activeSnapPoint,
947
+ snapPoints,
948
+ setActiveSnapPoint,
949
+ drawerRef,
950
+ overlayRef,
951
+ onOpenChange,
952
+ onPress,
953
+ onRelease,
954
+ onDrag,
955
+ dismissible,
956
+ shouldAnimate,
957
+ handleOnly,
958
+ isOpen,
959
+ isDragging,
960
+ shouldFade,
961
+ closeDrawer,
962
+ onNestedDrag,
963
+ onNestedOpenChange,
964
+ onNestedRelease,
965
+ keyboardIsOpen,
966
+ modal,
967
+ snapPointsOffset,
968
+ activeSnapPointIndex,
969
+ fadeFromIndex,
970
+ direction,
971
+ shouldScaleBackground,
972
+ setBackgroundColorOnScale,
973
+ noBodyStyles,
974
+ container,
975
+ autoFocus,
976
+ onPositionChangeRef,
977
+ setContentHeight,
978
+ detached,
979
+ detachedOffset: detached ? detachedOffset : 0,
980
+ detachedRadius: detached ? detachedRadius : 0,
981
+ detachedWrapperStyle,
982
+ }}
983
+ >
984
+ {children}
985
+ </DrawerContext.Provider>
986
+ </DialogPrimitive.Root>
987
+ );
988
+ }
989
+
990
+ export const Overlay = React.forwardRef<
991
+ HTMLDivElement,
992
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
993
+ >(({ style, ...rest }, ref) => {
994
+ const {
995
+ overlayRef,
996
+ snapPoints,
997
+ onRelease,
998
+ shouldFade,
999
+ isOpen,
1000
+ modal,
1001
+ shouldAnimate,
1002
+ activeSnapPointIndex,
1003
+ fadeFromIndex,
1004
+ } = useDrawerContext();
1005
+ const composedRef = useComposedRefs(ref, overlayRef);
1006
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
1007
+ const [delayedSnapPoints, setDelayedSnapPoints] = React.useState(false);
1008
+ const onMouseUp = React.useCallback(
1009
+ (event: React.PointerEvent<HTMLDivElement>) => onRelease(event),
1010
+ [onRelease]
1011
+ );
1012
+
1013
+ React.useEffect(() => {
1014
+ if (hasSnapPoints) {
1015
+ window.requestAnimationFrame(() => {
1016
+ setDelayedSnapPoints(true);
1017
+ });
1018
+ }
1019
+ }, []);
1020
+
1021
+ // Overlay is the component that is locking scroll, removing it will unlock the scroll without having to dig into Radix's Dialog library
1022
+ if (!modal) {
1023
+ return null;
1024
+ }
1025
+
1026
+ // When the active snap is below fadeFromIndex, the overlay is fully
1027
+ // transparent (CSS opacity: 0). Radix's DialogOverlayImpl sets inline
1028
+ // `pointer-events: auto` which would still catch clicks on the invisible
1029
+ // layer — drive this via React so it stays correct even before
1030
+ // `snapToPoint` runs (Presence defers the drawer/overlay mount, leaving
1031
+ // refs null on the first open effect pass).
1032
+ const isBelowFade =
1033
+ hasSnapPoints &&
1034
+ fadeFromIndex !== undefined &&
1035
+ typeof activeSnapPointIndex === 'number' &&
1036
+ activeSnapPointIndex < fadeFromIndex;
1037
+
1038
+ return (
1039
+ <DialogPrimitive.Overlay
1040
+ onMouseUp={onMouseUp}
1041
+ ref={composedRef}
1042
+ data-vaul-overlay=""
1043
+ data-vaul-snap-points={isOpen && hasSnapPoints ? 'true' : 'false'}
1044
+ data-vaul-delayed-snap-points={delayedSnapPoints ? 'true' : 'false'}
1045
+ data-vaul-snap-points-overlay={isOpen && shouldFade ? 'true' : 'false'}
1046
+ data-vaul-animate={shouldAnimate?.current ? 'true' : 'false'}
1047
+ {...rest}
1048
+ style={isBelowFade ? overlayBelowFadeStyle(style) : style}
1049
+ />
1050
+ );
1051
+ });
1052
+
1053
+ Overlay.displayName = 'Drawer.Overlay';
1054
+
1055
+ const overlayPointerEventsNone: React.CSSProperties = { pointerEvents: 'none' };
1056
+ const overlayBelowFadeStyle = (style: React.CSSProperties | undefined): React.CSSProperties =>
1057
+ style ? { ...style, ...overlayPointerEventsNone } : overlayPointerEventsNone;
1058
+
1059
+ export type ContentProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
1060
+ /**
1061
+ * Extra nodes rendered inside the detached clip wrapper as siblings of the
1062
+ * drawer. Use for floating elements (e.g. a footer) that should slide with
1063
+ * the wrapper on dismiss and drag-overshoot instead of staying pinned.
1064
+ */
1065
+ detachedSiblings?: React.ReactNode;
1066
+ };
1067
+
1068
+ export const Content = React.forwardRef<HTMLDivElement, ContentProps>(
1069
+ ({ onPointerDownOutside, style, onOpenAutoFocus, children, detachedSiblings, ...rest }, ref) => {
1070
+ const {
1071
+ drawerRef,
1072
+ onPress,
1073
+ onRelease,
1074
+ onDrag,
1075
+ keyboardIsOpen,
1076
+ snapPointsOffset,
1077
+ activeSnapPointIndex,
1078
+ fadeFromIndex,
1079
+ modal,
1080
+ isOpen,
1081
+ isDragging,
1082
+ direction,
1083
+ snapPoints,
1084
+ container,
1085
+ handleOnly,
1086
+ shouldAnimate,
1087
+ autoFocus,
1088
+ onPositionChangeRef,
1089
+ setContentHeight,
1090
+ detached,
1091
+ detachedOffset,
1092
+ detachedRadius,
1093
+ detachedWrapperStyle: detachedWrapperStyleProp,
1094
+ } = useDrawerContext();
1095
+ const hasAutoSnapPoint = React.useMemo(
1096
+ () => !!snapPoints?.some((p) => p === 'auto'),
1097
+ [snapPoints]
1098
+ );
1099
+
1100
+ // When 'auto' is used as a snap point, we need the natural content height.
1101
+ // The drawer itself may be styled to a fixed viewport height, so we measure
1102
+ // an inner wrapper instead. Ref callback starts the observer as soon as the
1103
+ // node mounts (Radix Presence defers the portal mount past useEffect).
1104
+ const autoRoRef = React.useRef<ResizeObserver | null>(null);
1105
+ const setAutoSizeNode = React.useCallback(
1106
+ (node: HTMLDivElement | null) => {
1107
+ autoRoRef.current?.disconnect();
1108
+ if (!node || !hasAutoSnapPoint) {
1109
+ autoRoRef.current = null;
1110
+ return;
1111
+ }
1112
+ const measure = () => setContentHeight(node.offsetHeight);
1113
+ measure();
1114
+ const ro = new ResizeObserver(measure);
1115
+ ro.observe(node);
1116
+ autoRoRef.current = ro;
1117
+ },
1118
+ [hasAutoSnapPoint, setContentHeight]
1119
+ );
1120
+
1121
+ const isBelowFade =
1122
+ snapPoints !== undefined &&
1123
+ snapPoints !== null &&
1124
+ fadeFromIndex !== undefined &&
1125
+ typeof activeSnapPointIndex === 'number' &&
1126
+ activeSnapPointIndex < fadeFromIndex;
1127
+ // Needed to use transition instead of animations
1128
+ const [delayedSnapPoints, setDelayedSnapPoints] = React.useState(false);
1129
+ const composedRef = useComposedRefs(ref, drawerRef);
1130
+ const pointerStartRef = React.useRef<{ x: number; y: number } | null>(null);
1131
+ const lastKnownPointerEventRef = React.useRef<React.PointerEvent<HTMLDivElement> | null>(null);
1132
+ const wasBeyondThePointRef = React.useRef(false);
1133
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
1134
+ useScaleBackground();
1135
+
1136
+ const isDeltaInDirection = (
1137
+ delta: { x: number; y: number },
1138
+ dir: DrawerDirection,
1139
+ threshold = 0
1140
+ ) => {
1141
+ if (wasBeyondThePointRef.current) return true;
1142
+
1143
+ const deltaY = Math.abs(delta.y);
1144
+ const deltaX = Math.abs(delta.x);
1145
+ const isDeltaX = deltaX > deltaY;
1146
+ const dFactor = ['bottom', 'right'].includes(dir) ? 1 : -1;
1147
+
1148
+ if (dir === 'left' || dir === 'right') {
1149
+ const isReverseDirection = delta.x * dFactor < 0;
1150
+ if (!isReverseDirection && deltaX >= 0 && deltaX <= threshold) {
1151
+ return isDeltaX;
1152
+ }
1153
+ } else {
1154
+ const isReverseDirection = delta.y * dFactor < 0;
1155
+ if (!isReverseDirection && deltaY >= 0 && deltaY <= threshold) {
1156
+ return !isDeltaX;
1157
+ }
1158
+ }
1159
+
1160
+ wasBeyondThePointRef.current = true;
1161
+ return true;
1162
+ };
1163
+
1164
+ React.useEffect(() => {
1165
+ if (hasSnapPoints) {
1166
+ window.requestAnimationFrame(() => {
1167
+ setDelayedSnapPoints(true);
1168
+ });
1169
+ }
1170
+ }, []);
1171
+
1172
+ // Event-driven position tracking. We only tick RAF while the drawer is
1173
+ // actually moving (drag / CSS transition / CSS animation). When it's idle at
1174
+ // a snap, no frames run at all.
1175
+ const positionTrackingRef = React.useRef<{
1176
+ rafId: number | null;
1177
+ movingCount: number;
1178
+ lastPosition: number;
1179
+ start: () => void;
1180
+ stop: () => void;
1181
+ } | null>(null);
1182
+
1183
+ React.useEffect(() => {
1184
+ const drawer = drawerRef.current;
1185
+ if (!drawer) return;
1186
+
1187
+ const state = {
1188
+ rafId: null as number | null,
1189
+ movingCount: 0,
1190
+ lastPosition: Number.NaN,
1191
+ start: () => {},
1192
+ stop: () => {},
1193
+ };
1194
+
1195
+ const emit = () => {
1196
+ const cb = onPositionChangeRef.current;
1197
+ if (!cb) return;
1198
+ const position = drawer.getBoundingClientRect().top;
1199
+ if (position !== state.lastPosition) {
1200
+ state.lastPosition = position;
1201
+ cb(position);
1202
+ }
1203
+ };
1204
+
1205
+ const tick = () => {
1206
+ emit();
1207
+ state.rafId = state.movingCount > 0 ? window.requestAnimationFrame(tick) : null;
1208
+ };
1209
+
1210
+ state.start = () => {
1211
+ state.movingCount += 1;
1212
+ if (state.rafId === null) {
1213
+ state.rafId = window.requestAnimationFrame(tick);
1214
+ }
1215
+ };
1216
+
1217
+ state.stop = () => {
1218
+ state.movingCount = Math.max(0, state.movingCount - 1);
1219
+ // RAF loop will exit on its next tick; emit the settled position now.
1220
+ if (state.movingCount === 0) emit();
1221
+ };
1222
+
1223
+ const wrapper = drawer.closest<HTMLElement>('[data-vaul-detached-wrapper]');
1224
+
1225
+ // Listen on the wrapper too: drag-overshoot snap-back animates the wrapper
1226
+ // alone when the drawer's target is unchanged (e.g. snapping back to the
1227
+ // same detent). Without this, position goes stale mid-animation because
1228
+ // the drawer's `transitionrun` never fires.
1229
+ const onTransitionRun = (e: TransitionEvent) => {
1230
+ if ((e.target === drawer || e.target === wrapper) && e.propertyName === 'transform')
1231
+ state.start();
1232
+ };
1233
+ const onTransitionDone = (e: TransitionEvent) => {
1234
+ if ((e.target === drawer || e.target === wrapper) && e.propertyName === 'transform')
1235
+ state.stop();
1236
+ };
1237
+ const onAnimationStart = (e: AnimationEvent) => {
1238
+ if (e.target === drawer || e.target === wrapper) state.start();
1239
+ };
1240
+ const onAnimationDone = (e: AnimationEvent) => {
1241
+ if (e.target === drawer || e.target === wrapper) state.stop();
1242
+ };
1243
+
1244
+ drawer.addEventListener('transitionrun', onTransitionRun);
1245
+ drawer.addEventListener('transitionend', onTransitionDone);
1246
+ drawer.addEventListener('transitioncancel', onTransitionDone);
1247
+ drawer.addEventListener('animationstart', onAnimationStart);
1248
+ drawer.addEventListener('animationend', onAnimationDone);
1249
+ drawer.addEventListener('animationcancel', onAnimationDone);
1250
+ wrapper?.addEventListener('transitionrun', onTransitionRun);
1251
+ wrapper?.addEventListener('transitionend', onTransitionDone);
1252
+ wrapper?.addEventListener('transitioncancel', onTransitionDone);
1253
+
1254
+ positionTrackingRef.current = state;
1255
+ emit();
1256
+
1257
+ return () => {
1258
+ drawer.removeEventListener('transitionrun', onTransitionRun);
1259
+ drawer.removeEventListener('transitionend', onTransitionDone);
1260
+ drawer.removeEventListener('transitioncancel', onTransitionDone);
1261
+ drawer.removeEventListener('animationstart', onAnimationStart);
1262
+ drawer.removeEventListener('animationend', onAnimationDone);
1263
+ drawer.removeEventListener('animationcancel', onAnimationDone);
1264
+ wrapper?.removeEventListener('transitionrun', onTransitionRun);
1265
+ wrapper?.removeEventListener('transitionend', onTransitionDone);
1266
+ wrapper?.removeEventListener('transitioncancel', onTransitionDone);
1267
+ if (state.rafId !== null) window.cancelAnimationFrame(state.rafId);
1268
+ positionTrackingRef.current = null;
1269
+ };
1270
+ }, []);
1271
+
1272
+ React.useEffect(() => {
1273
+ const state = positionTrackingRef.current;
1274
+ if (!state) return;
1275
+ if (isDragging) state.start();
1276
+ else state.stop();
1277
+ }, [isDragging]);
1278
+
1279
+ function handleOnPointerUp(event: React.PointerEvent<HTMLDivElement> | null) {
1280
+ pointerStartRef.current = null;
1281
+ wasBeyondThePointRef.current = false;
1282
+ onRelease(event);
1283
+ }
1284
+
1285
+ // The drawer always sits inside a fixed clip wrapper. `contain: paint`
1286
+ // establishes the wrapper as the containing block so the drawer's own
1287
+ // `position: fixed` is constrained here, and `overflow: hidden` keeps any
1288
+ // overshoot out of the viewport. When `detached` the wrapper also floats
1289
+ // with a bottom gap and rounded bottom corners; otherwise it sits flush.
1290
+ // Transform/transition are managed imperatively (via drag overshoot and the
1291
+ // dismiss effect) so React doesn't skip DOM writes for values it thinks it
1292
+ // already owns.
1293
+ const wrapperStyle = React.useMemo<React.CSSProperties>(
1294
+ () => ({
1295
+ position: 'fixed',
1296
+ top: 0,
1297
+ left: 0,
1298
+ right: 0,
1299
+ bottom: detached ? detachedOffset : 0,
1300
+ overflow: 'hidden',
1301
+ contain: 'paint',
1302
+ pointerEvents: 'none',
1303
+ borderBottomLeftRadius: detached ? detachedRadius : 0,
1304
+ borderBottomRightRadius: detached ? detachedRadius : 0,
1305
+ ...detachedWrapperStyleProp,
1306
+ }),
1307
+ [detached, detachedOffset, detachedRadius, detachedWrapperStyleProp]
1308
+ );
1309
+
1310
+ // Translate the wrapper off-screen on dismiss so the whole card slides out
1311
+ // as one. The reset-then-target pattern on open forces the browser to
1312
+ // record a starting value so the transition actually animates.
1313
+ const wasOpenRef = React.useRef(isOpen);
1314
+ React.useEffect(() => {
1315
+ if (!drawerRef.current) {
1316
+ wasOpenRef.current = isOpen;
1317
+ return;
1318
+ }
1319
+ const wrapper = drawerRef.current.closest<HTMLElement>('[data-vaul-detached-wrapper]');
1320
+ if (wrapper) {
1321
+ const transition = `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`;
1322
+ const viewportH = typeof window !== 'undefined' ? window.innerHeight : 0;
1323
+ if (!isOpen && wasOpenRef.current) {
1324
+ wrapper.style.transition = transition;
1325
+ wrapper.style.transform = `translate3d(0, ${viewportH}px, 0)`;
1326
+ } else if (isOpen && !wasOpenRef.current) {
1327
+ wrapper.style.transition = 'none';
1328
+ wrapper.style.transform = `translate3d(0, ${viewportH}px, 0)`;
1329
+ // eslint-disable-next-line no-void
1330
+ void wrapper.offsetHeight;
1331
+ wrapper.style.transition = transition;
1332
+ wrapper.style.transform = 'translate3d(0, 0, 0)';
1333
+ } else if (isOpen && !wrapper.style.transform) {
1334
+ // Fresh mount with open=true — ensure the wrapper starts at rest.
1335
+ wrapper.style.transition = transition;
1336
+ wrapper.style.transform = 'translate3d(0, 0, 0)';
1337
+ }
1338
+ }
1339
+ wasOpenRef.current = isOpen;
1340
+ }, [isOpen, detached, drawerRef]);
1341
+
1342
+ const contentNode = (
1343
+ <DialogPrimitive.Content
1344
+ data-vaul-drawer-direction={direction}
1345
+ data-vaul-drawer=""
1346
+ data-vaul-detached={detached ? 'true' : 'false'}
1347
+ data-vaul-delayed-snap-points={delayedSnapPoints ? 'true' : 'false'}
1348
+ data-vaul-snap-points={isOpen && hasSnapPoints ? 'true' : 'false'}
1349
+ data-vaul-custom-container={container ? 'true' : 'false'}
1350
+ data-vaul-animate={shouldAnimate?.current ? 'true' : 'false'}
1351
+ {...rest}
1352
+ ref={composedRef}
1353
+ style={
1354
+ snapPointsOffset && snapPointsOffset.length > 0
1355
+ ? ({
1356
+ '--snap-point-height': `${snapPointsOffset[activeSnapPointIndex ?? 0]!}px`,
1357
+ ...style,
1358
+ 'pointerEvents': 'auto',
1359
+ } as React.CSSProperties)
1360
+ : ({ ...style, pointerEvents: 'auto' } as React.CSSProperties)
1361
+ }
1362
+ onPointerDown={(event) => {
1363
+ if (handleOnly) return;
1364
+ rest.onPointerDown?.(event);
1365
+ pointerStartRef.current = { x: event.pageX, y: event.pageY };
1366
+ onPress(event);
1367
+ }}
1368
+ onOpenAutoFocus={(e) => {
1369
+ onOpenAutoFocus?.(e);
1370
+
1371
+ if (!autoFocus) {
1372
+ e.preventDefault();
1373
+ }
1374
+ }}
1375
+ onPointerDownOutside={(e) => {
1376
+ onPointerDownOutside?.(e);
1377
+
1378
+ if (!modal || e.defaultPrevented || isBelowFade) {
1379
+ e.preventDefault();
1380
+ return;
1381
+ }
1382
+
1383
+ if (keyboardIsOpen.current) {
1384
+ keyboardIsOpen.current = false;
1385
+ }
1386
+ }}
1387
+ onFocusOutside={(e) => {
1388
+ if (!modal || isBelowFade) {
1389
+ e.preventDefault();
1390
+ return;
1391
+ }
1392
+ }}
1393
+ onPointerMove={(event) => {
1394
+ lastKnownPointerEventRef.current = event;
1395
+ if (handleOnly) return;
1396
+ rest.onPointerMove?.(event);
1397
+ if (!pointerStartRef.current) return;
1398
+ const yPosition = event.pageY - pointerStartRef.current.y;
1399
+ const xPosition = event.pageX - pointerStartRef.current.x;
1400
+
1401
+ const swipeStartThreshold = event.pointerType === 'touch' ? 10 : 2;
1402
+ const delta = { x: xPosition, y: yPosition };
1403
+
1404
+ const isAllowedToSwipe = isDeltaInDirection(delta, direction, swipeStartThreshold);
1405
+ if (isAllowedToSwipe) onDrag(event);
1406
+ else if (
1407
+ Math.abs(xPosition) > swipeStartThreshold ||
1408
+ Math.abs(yPosition) > swipeStartThreshold
1409
+ ) {
1410
+ pointerStartRef.current = null;
1411
+ }
1412
+ }}
1413
+ onPointerUp={(event) => {
1414
+ rest.onPointerUp?.(event);
1415
+ pointerStartRef.current = null;
1416
+ wasBeyondThePointRef.current = false;
1417
+ onRelease(event);
1418
+ }}
1419
+ onPointerOut={(event) => {
1420
+ rest.onPointerOut?.(event);
1421
+ handleOnPointerUp(lastKnownPointerEventRef.current);
1422
+ }}
1423
+ onContextMenu={(event) => {
1424
+ rest.onContextMenu?.(event);
1425
+ if (lastKnownPointerEventRef.current) {
1426
+ handleOnPointerUp(lastKnownPointerEventRef.current);
1427
+ }
1428
+ }}
1429
+ >
1430
+ {hasAutoSnapPoint ? (
1431
+ <div ref={setAutoSizeNode} data-vaul-auto-size-wrapper="" style={autoSizeWrapperStyle}>
1432
+ {children}
1433
+ </div>
1434
+ ) : (
1435
+ children
1436
+ )}
1437
+ </DialogPrimitive.Content>
1438
+ );
1439
+
1440
+ return (
1441
+ <div data-vaul-detached-wrapper="" style={wrapperStyle}>
1442
+ {contentNode}
1443
+ {detachedSiblings}
1444
+ </div>
1445
+ );
1446
+ }
1447
+ );
1448
+
1449
+ Content.displayName = 'Drawer.Content';
1450
+
1451
+ // `flow-root` establishes a new block formatting context so the first child's
1452
+ // margin-top (e.g. a grabber) stays inside the wrapper instead of collapsing
1453
+ // out — otherwise `offsetHeight` under-reports and the drawer positions the
1454
+ // wrapper below where the content actually ends.
1455
+ const autoSizeWrapperStyle: React.CSSProperties = { display: 'flow-root' };
1456
+
1457
+ export type HandleProps = React.ComponentPropsWithoutRef<'div'> & {
1458
+ preventCycle?: boolean;
1459
+ };
1460
+
1461
+ const LONG_HANDLE_PRESS_TIMEOUT = 250;
1462
+ const DOUBLE_TAP_TIMEOUT = 120;
1463
+
1464
+ export const Handle = React.forwardRef<HTMLDivElement, HandleProps>(
1465
+ ({ preventCycle = false, children, ...rest }, ref) => {
1466
+ const {
1467
+ closeDrawer,
1468
+ isDragging,
1469
+ snapPoints,
1470
+ activeSnapPoint,
1471
+ setActiveSnapPoint,
1472
+ dismissible,
1473
+ handleOnly,
1474
+ isOpen,
1475
+ onPress,
1476
+ onDrag,
1477
+ } = useDrawerContext();
1478
+
1479
+ const closeTimeoutIdRef = React.useRef<number | null>(null);
1480
+ const shouldCancelInteractionRef = React.useRef(false);
1481
+
1482
+ function handleStartCycle() {
1483
+ // Stop if this is the second click of a double click
1484
+ if (shouldCancelInteractionRef.current) {
1485
+ handleCancelInteraction();
1486
+ return;
1487
+ }
1488
+ window.setTimeout(() => {
1489
+ handleCycleSnapPoints();
1490
+ }, DOUBLE_TAP_TIMEOUT);
1491
+ }
1492
+
1493
+ function handleCycleSnapPoints() {
1494
+ // Prevent accidental taps while resizing drawer
1495
+ if (isDragging || preventCycle || shouldCancelInteractionRef.current) {
1496
+ handleCancelInteraction();
1497
+ return;
1498
+ }
1499
+ // Make sure to clear the timeout id if the user releases the handle before the cancel timeout
1500
+ handleCancelInteraction();
1501
+
1502
+ if (!snapPoints || snapPoints.length === 0) {
1503
+ if (!dismissible) {
1504
+ closeDrawer();
1505
+ }
1506
+ return;
1507
+ }
1508
+
1509
+ const isLastSnapPoint = activeSnapPoint === snapPoints[snapPoints.length - 1];
1510
+
1511
+ if (isLastSnapPoint && dismissible) {
1512
+ closeDrawer();
1513
+ return;
1514
+ }
1515
+
1516
+ const currentSnapIndex = snapPoints.findIndex((point) => point === activeSnapPoint);
1517
+ if (currentSnapIndex === -1) return; // activeSnapPoint not found in snapPoints
1518
+ const nextSnapPoint = snapPoints[currentSnapIndex + 1];
1519
+ if (nextSnapPoint === undefined) return;
1520
+ setActiveSnapPoint(nextSnapPoint);
1521
+ }
1522
+
1523
+ function handleStartInteraction() {
1524
+ closeTimeoutIdRef.current = window.setTimeout(() => {
1525
+ // Cancel click interaction on a long press
1526
+ shouldCancelInteractionRef.current = true;
1527
+ }, LONG_HANDLE_PRESS_TIMEOUT);
1528
+ }
1529
+
1530
+ function handleCancelInteraction() {
1531
+ if (closeTimeoutIdRef.current) {
1532
+ window.clearTimeout(closeTimeoutIdRef.current);
1533
+ }
1534
+ shouldCancelInteractionRef.current = false;
1535
+ }
1536
+
1537
+ return (
1538
+ <div
1539
+ onClick={handleStartCycle}
1540
+ onPointerCancel={handleCancelInteraction}
1541
+ onPointerDown={(e) => {
1542
+ if (handleOnly) onPress(e);
1543
+ handleStartInteraction();
1544
+ }}
1545
+ onPointerMove={(e) => {
1546
+ if (handleOnly) onDrag(e);
1547
+ }}
1548
+ // onPointerUp is already handled by the content component
1549
+ ref={ref}
1550
+ data-vaul-drawer-visible={isOpen ? 'true' : 'false'}
1551
+ data-vaul-handle=""
1552
+ aria-hidden="true"
1553
+ {...rest}
1554
+ >
1555
+ {/* Expand handle's hit area beyond what's visible to ensure a 44x44 tap target for touch devices */}
1556
+ <span data-vaul-handle-hitarea="" aria-hidden="true">
1557
+ {children}
1558
+ </span>
1559
+ </div>
1560
+ );
1561
+ }
1562
+ );
1563
+
1564
+ Handle.displayName = 'Drawer.Handle';
1565
+
1566
+ export function NestedRoot({ onDrag, onOpenChange, open: nestedIsOpen, ...rest }: DialogProps) {
1567
+ const { onNestedDrag, onNestedOpenChange, onNestedRelease } = useDrawerContext();
1568
+
1569
+ if (!onNestedDrag) {
1570
+ throw new Error('Drawer.NestedRoot must be placed in another drawer');
1571
+ }
1572
+
1573
+ return (
1574
+ <Root
1575
+ nested
1576
+ open={nestedIsOpen}
1577
+ onClose={() => {
1578
+ onNestedOpenChange(false);
1579
+ }}
1580
+ onDrag={(e, p) => {
1581
+ onNestedDrag(e, p);
1582
+ onDrag?.(e, p);
1583
+ }}
1584
+ onOpenChange={(o) => {
1585
+ if (o) {
1586
+ onNestedOpenChange(o);
1587
+ }
1588
+ onOpenChange?.(o);
1589
+ }}
1590
+ onRelease={onNestedRelease}
1591
+ {...rest}
1592
+ />
1593
+ );
1594
+ }
1595
+
1596
+ type PortalProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive.Portal>;
1597
+
1598
+ export function Portal(props: PortalProps) {
1599
+ const context = useDrawerContext();
1600
+ const { container = context.container, ...portalProps } = props;
1601
+
1602
+ return <DialogPrimitive.Portal container={container} {...portalProps} />;
1603
+ }
1604
+
1605
+ export const Drawer = {
1606
+ Root,
1607
+ NestedRoot,
1608
+ Content,
1609
+ Overlay,
1610
+ Trigger: DialogPrimitive.Trigger,
1611
+ Portal,
1612
+ Handle,
1613
+ Close: DialogPrimitive.Close,
1614
+ Title: DialogPrimitive.Title,
1615
+ Description: DialogPrimitive.Description,
1616
+ };