@lodev09/react-native-true-sheet 3.10.0 → 3.11.0-beta.0

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