@octanejs/vaul 0.0.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.
package/src/index.tsrx ADDED
@@ -0,0 +1,1225 @@
1
+ 'use client';
2
+
3
+ import { Dialog as DialogPrimitive } from '@octanejs/radix';
4
+ import { createPortal, useCallback, useEffect, useRef, useState } from 'octane';
5
+ import type React from 'react';
6
+ import { DrawerContext, useDrawerContext } from './context';
7
+ import './style.css';
8
+ import { usePreventScroll, isInput } from './use-prevent-scroll';
9
+ import { useComposedRefs } from './use-composed-refs';
10
+ import { useSnapPoints } from './use-snap-points';
11
+ import { set, getTranslate, dampenValue, isVertical, reset } from './helpers';
12
+ import {
13
+ TRANSITIONS,
14
+ VELOCITY_THRESHOLD,
15
+ CLOSE_THRESHOLD,
16
+ SCROLL_LOCK_TIMEOUT,
17
+ BORDER_RADIUS,
18
+ NESTED_DISPLACEMENT,
19
+ WINDOW_TOP_OFFSET,
20
+ DRAG_CLASS,
21
+ } from './constants';
22
+ import type { DrawerDirection } from './types';
23
+ import { useControllableState } from './use-controllable-state';
24
+ import { useScaleBackground } from './use-scale-background';
25
+ import { usePositionFixed } from './use-position-fixed';
26
+ import { isIOS, isMobileFirefox } from './browser';
27
+
28
+ export interface WithFadeFromProps {
29
+ /**
30
+ * Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up.
31
+ * Should go from least visible. Example `[0.2, 0.5, 0.8]`.
32
+ * You can also use px values, which doesn't take screen height into account.
33
+ */
34
+ snapPoints: (number | string)[];
35
+ /**
36
+ * Index of a `snapPoint` from which the overlay fade should be applied. Defaults to the last snap point.
37
+ */
38
+ fadeFromIndex: number;
39
+ }
40
+
41
+ export interface WithoutFadeFromProps {
42
+ /**
43
+ * Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up.
44
+ * Should go from least visible. Example `[0.2, 0.5, 0.8]`.
45
+ * You can also use px values, which doesn't take screen height into account.
46
+ */
47
+ snapPoints?: (number | string)[];
48
+ fadeFromIndex?: never;
49
+ }
50
+
51
+ export type DialogProps =
52
+ {
53
+ activeSnapPoint?: number | string | null;
54
+ setActiveSnapPoint?: (snapPoint: number | string | null) => void;
55
+ children?: React.ReactNode;
56
+ open?: boolean;
57
+ /**
58
+ * Number between 0 and 1 that determines when the drawer should be closed.
59
+ * Example: threshold of 0.5 would close the drawer if the user swiped for 50% of the height of the drawer or more.
60
+ * @default 0.25
61
+ */
62
+ closeThreshold?: number;
63
+ /**
64
+ * When `true` the `body` doesn't get any styles assigned from Vaul
65
+ */
66
+ noBodyStyles?: boolean;
67
+ onOpenChange?: (open: boolean) => void;
68
+ shouldScaleBackground?: boolean;
69
+ /**
70
+ * When `false` we don't change body's background color when the drawer is open.
71
+ * @default true
72
+ */
73
+ setBackgroundColorOnScale?: boolean;
74
+ /**
75
+ * Duration for which the drawer is not draggable after scrolling content inside of the drawer.
76
+ * @default 500ms
77
+ */
78
+ scrollLockTimeout?: number;
79
+ /**
80
+ * 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
81
+ */
82
+ fixed?: boolean;
83
+ /**
84
+ * When `true` only allows the drawer to be dragged by the `<Drawer.Handle />` component.
85
+ * @default false
86
+ */
87
+ handleOnly?: boolean;
88
+ /**
89
+ * When `false` dragging, clicking outside, pressing esc, etc. will not close the drawer.
90
+ * Use this in comination with the `open` prop, otherwise you won't be able to open/close the drawer.
91
+ * @default true
92
+ */
93
+ dismissible?: boolean;
94
+ onDrag?: (event: React.PointerEvent<HTMLDivElement>, percentageDragged: number) => void;
95
+ onRelease?: (event: React.PointerEvent<HTMLDivElement>, open: boolean) => void;
96
+ /**
97
+ * When `false` it allows to interact with elements outside of the drawer without closing it.
98
+ * @default true
99
+ */
100
+ modal?: boolean;
101
+ nested?: boolean;
102
+ onClose?: () => void;
103
+ /**
104
+ * Direction of the drawer. Can be `top` or `bottom`, `left`, `right`.
105
+ * @default 'bottom'
106
+ */
107
+ direction?: 'top' | 'bottom' | 'left' | 'right';
108
+ /**
109
+ * Opened by default, skips initial enter animation. Still reacts to `open` state changes
110
+ * @default false
111
+ */
112
+ defaultOpen?: boolean;
113
+ /**
114
+ * When set to `true` prevents scrolling on the document body on mount, and restores it on unmount.
115
+ * @default false
116
+ */
117
+ disablePreventScroll?: boolean;
118
+ /**
119
+ * When `true` Vaul will reposition inputs rather than scroll then into view if the keyboard is in the way.
120
+ * Setting it to `false` will fall back to the default browser behavior.
121
+ * @default true when {@link snapPoints} is defined
122
+ */
123
+ repositionInputs?: boolean;
124
+ /**
125
+ * Disabled velocity based swiping for snap points.
126
+ * This means that a snap point won't be skipped even if the velocity is high enough.
127
+ * Useful if each snap point in a drawer is equally important.
128
+ * @default false
129
+ */
130
+ snapToSequentialPoint?: boolean;
131
+ container?: HTMLElement | null;
132
+ /**
133
+ * 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.
134
+ * Useful to revert any state changes for example.
135
+ */
136
+ onAnimationEnd?: (open: boolean) => void;
137
+ preventScrollRestoration?: boolean;
138
+ autoFocus?: boolean;
139
+ } & (WithFadeFromProps | WithoutFadeFromProps);
140
+
141
+ export function Root({
142
+ open: openProp,
143
+ onOpenChange,
144
+ children,
145
+ onDrag: onDragProp,
146
+ onRelease: onReleaseProp,
147
+ snapPoints,
148
+ shouldScaleBackground = false,
149
+ setBackgroundColorOnScale = true,
150
+ closeThreshold = CLOSE_THRESHOLD,
151
+ scrollLockTimeout = SCROLL_LOCK_TIMEOUT,
152
+ dismissible = true,
153
+ handleOnly = false,
154
+ fadeFromIndex = snapPoints && snapPoints.length - 1,
155
+ activeSnapPoint: activeSnapPointProp,
156
+ setActiveSnapPoint: setActiveSnapPointProp,
157
+ fixed,
158
+ modal = true,
159
+ onClose,
160
+ nested,
161
+ noBodyStyles = false,
162
+ direction = 'bottom',
163
+ defaultOpen = false,
164
+ disablePreventScroll = true,
165
+ snapToSequentialPoint = false,
166
+ preventScrollRestoration = false,
167
+ repositionInputs = true,
168
+ onAnimationEnd,
169
+ container,
170
+ autoFocus = false,
171
+ }: DialogProps) @{
172
+ const [isOpen = false, setIsOpen] = useControllableState<boolean>({
173
+ defaultProp: defaultOpen,
174
+ prop: openProp,
175
+ onChange: (o: boolean) => {
176
+ onOpenChange?.(o);
177
+
178
+ if (!o && !nested) {
179
+ restorePositionSetting();
180
+ }
181
+
182
+ setTimeout(() => {
183
+ onAnimationEnd?.(o);
184
+ }, TRANSITIONS.DURATION * 1000);
185
+
186
+ if (o && !modal) {
187
+ if (typeof window !== 'undefined') {
188
+ window.requestAnimationFrame(() => {
189
+ document.body.style.pointerEvents = 'auto';
190
+ });
191
+ }
192
+ }
193
+
194
+ if (!o) {
195
+ // This will be removed when the exit animation ends (`500ms`)
196
+ document.body.style.pointerEvents = 'auto';
197
+ }
198
+ },
199
+ });
200
+ const [hasBeenOpened, setHasBeenOpened] = useState<boolean>(false);
201
+ const [isDragging, setIsDragging] = useState<boolean>(false);
202
+ const [justReleased, setJustReleased] = useState<boolean>(false);
203
+ const overlayRef = useRef<HTMLDivElement | null>(null);
204
+ const openTime = useRef<Date | null>(null);
205
+ const dragStartTime = useRef<Date | null>(null);
206
+ const dragEndTime = useRef<Date | null>(null);
207
+ const lastTimeDragPrevented = useRef<Date | null>(null);
208
+ const isAllowedToDrag = useRef<boolean>(false);
209
+ const nestedOpenChangeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
210
+ const pointerStart = useRef(0);
211
+ const keyboardIsOpen = useRef(false);
212
+ const shouldAnimate = useRef(!defaultOpen);
213
+ const previousDiffFromInitial = useRef(0);
214
+ const drawerRef = useRef<HTMLDivElement | null>(null);
215
+ const drawerHeightRef = useRef(drawerRef.current?.getBoundingClientRect().height || 0);
216
+ const drawerWidthRef = useRef(drawerRef.current?.getBoundingClientRect().width || 0);
217
+ const initialDrawerHeight = useRef(0);
218
+
219
+ const onSnapPointChange = useCallback((activeSnapPointIndex: number) => {
220
+ // Change openTime ref when we reach the last snap point to prevent dragging for 500ms incase it's scrollable.
221
+ if (snapPoints && activeSnapPointIndex === snapPointsOffset.length - 1) openTime.current =
222
+ new Date();
223
+ }, []);
224
+
225
+ const {
226
+ activeSnapPoint,
227
+ activeSnapPointIndex,
228
+ setActiveSnapPoint,
229
+ onRelease: onReleaseSnapPoints,
230
+ snapPointsOffset,
231
+ onDrag: onDragSnapPoints,
232
+ shouldFade,
233
+ getPercentageDragged: getSnapPointsPercentageDragged,
234
+ } = useSnapPoints({
235
+ snapPoints,
236
+ activeSnapPointProp,
237
+ setActiveSnapPointProp,
238
+ drawerRef,
239
+ fadeFromIndex,
240
+ overlayRef,
241
+ onSnapPointChange,
242
+ direction,
243
+ container,
244
+ snapToSequentialPoint,
245
+ });
246
+
247
+ usePreventScroll({
248
+ isDisabled: !isOpen || isDragging || !modal || justReleased || !hasBeenOpened ||
249
+ !repositionInputs ||
250
+ !disablePreventScroll,
251
+ });
252
+
253
+ const { restorePositionSetting } = usePositionFixed({
254
+ isOpen,
255
+ modal,
256
+ nested: nested ?? false,
257
+ hasBeenOpened,
258
+ preventScrollRestoration,
259
+ noBodyStyles,
260
+ });
261
+
262
+ function getScale() {
263
+ return (window.innerWidth - WINDOW_TOP_OFFSET) / window.innerWidth;
264
+ }
265
+
266
+ function onPress(event: React.PointerEvent<HTMLDivElement>) {
267
+ if (!dismissible && !snapPoints) return;
268
+ if (drawerRef.current && !drawerRef.current.contains(event.target as Node)) return;
269
+
270
+ drawerHeightRef.current = drawerRef.current?.getBoundingClientRect().height || 0;
271
+ drawerWidthRef.current = drawerRef.current?.getBoundingClientRect().width || 0;
272
+ setIsDragging(true);
273
+ dragStartTime.current = new Date();
274
+
275
+ // iOS doesn't trigger mouseUp after scrolling so we need to listen to touched in order to disallow dragging
276
+ if (isIOS()) {
277
+ window.addEventListener('touchend', () => (isAllowedToDrag.current = false), { once: true });
278
+ }
279
+ // Ensure we maintain correct pointer capture even when going outside of the drawer
280
+ (event.target as HTMLElement).setPointerCapture(event.pointerId);
281
+
282
+ pointerStart.current = isVertical(direction) ? event.pageY : event.pageX;
283
+ }
284
+
285
+ function shouldDrag(el: EventTarget, isDraggingInDirection: boolean) {
286
+ let element = el as HTMLElement;
287
+ const highlightedText = window.getSelection()?.toString();
288
+ const swipeAmount =
289
+ drawerRef.current ? getTranslate(drawerRef.current, direction) : null;
290
+ const date = new Date();
291
+
292
+ // Fixes https://github.com/emilkowalski/vaul/issues/483
293
+ if (element.tagName === 'SELECT') {
294
+ return false;
295
+ }
296
+
297
+ if (element.hasAttribute('data-vaul-no-drag') || element.closest('[data-vaul-no-drag]')) {
298
+ return false;
299
+ }
300
+
301
+ if (direction === 'right' || direction === 'left') {
302
+ return true;
303
+ }
304
+
305
+ // Allow scrolling when animating
306
+ if (openTime.current && date.getTime() - openTime.current.getTime() < 500) {
307
+ return false;
308
+ }
309
+
310
+ if (swipeAmount !== null) {
311
+ if (direction === 'bottom' ? swipeAmount > 0 : swipeAmount < 0) {
312
+ return true;
313
+ }
314
+ }
315
+
316
+ // Don't drag if there's highlighted text
317
+ if (highlightedText && highlightedText.length > 0) {
318
+ return false;
319
+ }
320
+
321
+ // Disallow dragging if drawer was scrolled within `scrollLockTimeout`
322
+ if (
323
+ lastTimeDragPrevented.current &&
324
+ date.getTime() - lastTimeDragPrevented.current.getTime() < scrollLockTimeout &&
325
+ swipeAmount === 0
326
+ ) {
327
+ lastTimeDragPrevented.current = date;
328
+ return false;
329
+ }
330
+
331
+ if (isDraggingInDirection) {
332
+ lastTimeDragPrevented.current = date;
333
+
334
+ // We are dragging down so we should allow scrolling
335
+ return false;
336
+ }
337
+
338
+ // Keep climbing up the DOM tree as long as there's a parent
339
+ while (element) {
340
+ // Check if the element is scrollable
341
+ if (element.scrollHeight > element.clientHeight) {
342
+ if (element.scrollTop !== 0) {
343
+ lastTimeDragPrevented.current = new Date();
344
+
345
+ // The element is scrollable and not scrolled to the top, so don't drag
346
+ return false;
347
+ }
348
+
349
+ if (element.getAttribute('role') === 'dialog') {
350
+ return true;
351
+ }
352
+ }
353
+
354
+ // Move up to the parent element
355
+ element = element.parentNode as HTMLElement;
356
+ }
357
+
358
+ // No scrollable parents not scrolled to the top found, so drag
359
+ return true;
360
+ }
361
+
362
+ function onDrag(event: React.PointerEvent<HTMLDivElement>) {
363
+ if (!drawerRef.current) {
364
+ return;
365
+ }
366
+
367
+ // We need to know how much of the drawer has been dragged in percentages so that we can transform background accordingly
368
+ if (isDragging) {
369
+ const directionMultiplier =
370
+ direction === 'bottom' || direction === 'right' ? 1 : -1;
371
+ const draggedDistance =
372
+ (pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX)) *
373
+ directionMultiplier;
374
+ const isDraggingInDirection = draggedDistance > 0;
375
+
376
+ // Pre condition for disallowing dragging in the close direction.
377
+ const noCloseSnapPointsPreCondition = snapPoints && !dismissible && !isDraggingInDirection;
378
+
379
+ // Disallow dragging down to close when first snap point is the active one and dismissible prop is set to false.
380
+ if (noCloseSnapPointsPreCondition && activeSnapPointIndex === 0) return;
381
+
382
+ // We need to capture last time when drag with scroll was triggered and have a timeout between
383
+ const absDraggedDistance = Math.abs(draggedDistance);
384
+ const wrapper = document.querySelector('[data-vaul-drawer-wrapper]');
385
+ const drawerDimension =
386
+ direction === 'bottom' || direction === 'top'
387
+ ? drawerHeightRef.current
388
+ : drawerWidthRef.current;
389
+
390
+ // Calculate the percentage dragged, where 1 is the closed position
391
+ let percentageDragged = absDraggedDistance / drawerDimension;
392
+ const snapPointPercentageDragged = getSnapPointsPercentageDragged(
393
+ absDraggedDistance,
394
+ isDraggingInDirection,
395
+ );
396
+
397
+ if (snapPointPercentageDragged !== null) {
398
+ percentageDragged = snapPointPercentageDragged;
399
+ }
400
+
401
+ // Disallow close dragging beyond the smallest snap point.
402
+ if (noCloseSnapPointsPreCondition && percentageDragged >= 1) {
403
+ return;
404
+ }
405
+
406
+ if (!isAllowedToDrag.current && !shouldDrag(event.target, isDraggingInDirection)) return;
407
+ drawerRef.current.classList.add(DRAG_CLASS);
408
+ // 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
409
+ isAllowedToDrag.current = true;
410
+ set(drawerRef.current, {
411
+ transition: 'none',
412
+ });
413
+
414
+ set(overlayRef.current, {
415
+ transition: 'none',
416
+ });
417
+
418
+ if (snapPoints) {
419
+ onDragSnapPoints({ draggedDistance });
420
+ }
421
+
422
+ // Run this only if snapPoints are not defined or if we are at the last snap point (highest one)
423
+ if (isDraggingInDirection && !snapPoints) {
424
+ const dampenedDraggedDistance = dampenValue(draggedDistance);
425
+
426
+ const translateValue = Math.min(dampenedDraggedDistance * -1, 0) * directionMultiplier;
427
+ set(drawerRef.current, {
428
+ transform: isVertical(direction)
429
+ ? `translate3d(0, ${translateValue}px, 0)`
430
+ : `translate3d(${translateValue}px, 0, 0)`,
431
+ });
432
+ return;
433
+ }
434
+
435
+ const opacityValue = 1 - percentageDragged;
436
+
437
+ if (shouldFade || fadeFromIndex && activeSnapPointIndex === fadeFromIndex - 1) {
438
+ onDragProp?.(event, percentageDragged);
439
+
440
+ set(
441
+ overlayRef.current,
442
+ {
443
+ opacity: `${opacityValue}`,
444
+ transition: 'none',
445
+ },
446
+ true,
447
+ );
448
+ }
449
+
450
+ if (wrapper && overlayRef.current && shouldScaleBackground) {
451
+ // Calculate percentageDragged as a fraction (0 to 1)
452
+ const scaleValue = Math.min(getScale() + percentageDragged * (1 - getScale()), 1);
453
+ const borderRadiusValue = 8 - percentageDragged * 8;
454
+
455
+ const translateValue = Math.max(0, 14 - percentageDragged * 14);
456
+
457
+ set(
458
+ wrapper,
459
+ {
460
+ borderRadius: `${borderRadiusValue}px`,
461
+ transform: isVertical(direction)
462
+ ? `scale(${scaleValue}) translate3d(0, ${translateValue}px, 0)`
463
+ : `scale(${scaleValue}) translate3d(${translateValue}px, 0, 0)`,
464
+ transition: 'none',
465
+ },
466
+ true,
467
+ );
468
+ }
469
+
470
+ if (!snapPoints) {
471
+ const translateValue = absDraggedDistance * directionMultiplier;
472
+
473
+ set(drawerRef.current, {
474
+ transform: isVertical(direction)
475
+ ? `translate3d(0, ${translateValue}px, 0)`
476
+ : `translate3d(${translateValue}px, 0, 0)`,
477
+ });
478
+ }
479
+ }
480
+ }
481
+
482
+ useEffect(() => {
483
+ window.requestAnimationFrame(() => {
484
+ shouldAnimate.current = true;
485
+ });
486
+ }, []);
487
+
488
+ useEffect(() => {
489
+ function onVisualViewportChange() {
490
+ if (!drawerRef.current || !repositionInputs) return;
491
+
492
+ const focusedElement = document.activeElement as HTMLElement;
493
+ if (isInput(focusedElement) || keyboardIsOpen.current) {
494
+ const visualViewportHeight = window.visualViewport?.height || 0;
495
+ const totalHeight = window.innerHeight;
496
+ // This is the height of the keyboard
497
+ let diffFromInitial = totalHeight - visualViewportHeight;
498
+ const drawerHeight = drawerRef.current.getBoundingClientRect().height || 0;
499
+ // Adjust drawer height only if it's tall enough
500
+ const isTallEnough = drawerHeight > totalHeight * 0.8;
501
+
502
+ if (!initialDrawerHeight.current) {
503
+ initialDrawerHeight.current = drawerHeight;
504
+ }
505
+ const offsetFromTop = drawerRef.current.getBoundingClientRect().top;
506
+
507
+ // 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.
508
+ if (Math.abs(previousDiffFromInitial.current - diffFromInitial) > 60) {
509
+ keyboardIsOpen.current = !keyboardIsOpen.current;
510
+ }
511
+
512
+ if (snapPoints && snapPoints.length > 0 && snapPointsOffset && activeSnapPointIndex) {
513
+ const activeSnapPointHeight = snapPointsOffset[activeSnapPointIndex] || 0;
514
+ diffFromInitial += activeSnapPointHeight;
515
+ }
516
+ previousDiffFromInitial.current = diffFromInitial;
517
+ // 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
518
+ if (drawerHeight > visualViewportHeight || keyboardIsOpen.current) {
519
+ const height = drawerRef.current.getBoundingClientRect().height;
520
+ let newDrawerHeight = height;
521
+
522
+ if (height > visualViewportHeight) {
523
+ newDrawerHeight = visualViewportHeight -
524
+ (isTallEnough ? offsetFromTop : WINDOW_TOP_OFFSET);
525
+ }
526
+ // 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
527
+ if (fixed) {
528
+ drawerRef.current.style.height = `${height - Math.max(diffFromInitial, 0)}px`;
529
+ } else {
530
+ drawerRef.current.style.height = `${Math.max(
531
+ newDrawerHeight,
532
+ visualViewportHeight - offsetFromTop,
533
+ )}px`;
534
+ }
535
+ } else if (!isMobileFirefox()) {
536
+ drawerRef.current.style.height = `${initialDrawerHeight.current}px`;
537
+ }
538
+
539
+ if (snapPoints && snapPoints.length > 0 && !keyboardIsOpen.current) {
540
+ drawerRef.current.style.bottom = `0px`;
541
+ } else {
542
+ // Negative bottom value would never make sense
543
+ drawerRef.current.style.bottom = `${Math.max(diffFromInitial, 0)}px`;
544
+ }
545
+ }
546
+ }
547
+
548
+ window.visualViewport?.addEventListener('resize', onVisualViewportChange);
549
+ return () => window.visualViewport?.removeEventListener('resize', onVisualViewportChange);
550
+ }, [activeSnapPointIndex, snapPoints, snapPointsOffset]);
551
+
552
+ function closeDrawer(fromWithin?: boolean) {
553
+ cancelDrag();
554
+ onClose?.();
555
+
556
+ if (!fromWithin) {
557
+ setIsOpen(false);
558
+ }
559
+
560
+ setTimeout(() => {
561
+ if (snapPoints) {
562
+ setActiveSnapPoint(snapPoints[0]);
563
+ }
564
+ }, TRANSITIONS.DURATION * 1000); // seconds to ms
565
+ }
566
+
567
+ function resetDrawer() {
568
+ if (!drawerRef.current) return;
569
+ const wrapper = document.querySelector('[data-vaul-drawer-wrapper]');
570
+ const currentSwipeAmount = getTranslate(drawerRef.current, direction);
571
+
572
+ set(drawerRef.current, {
573
+ transform: 'translate3d(0, 0, 0)',
574
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
575
+ });
576
+
577
+ set(overlayRef.current, {
578
+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
579
+ opacity: '1',
580
+ });
581
+
582
+ // Don't reset background if swiped upwards
583
+ if (shouldScaleBackground && currentSwipeAmount && currentSwipeAmount > 0 && isOpen) {
584
+ set(
585
+ wrapper,
586
+ {
587
+ borderRadius: `${BORDER_RADIUS}px`,
588
+ overflow: 'hidden',
589
+ ...(isVertical(direction)
590
+ ? {
591
+ transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
592
+ transformOrigin: 'top',
593
+ }
594
+ : {
595
+ transform: `scale(${getScale()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,
596
+ transformOrigin: 'left',
597
+ }),
598
+ transitionProperty: 'transform, border-radius',
599
+ transitionDuration: `${TRANSITIONS.DURATION}s`,
600
+ transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
601
+ },
602
+ true,
603
+ );
604
+ }
605
+ }
606
+
607
+ function cancelDrag() {
608
+ if (!isDragging || !drawerRef.current) return;
609
+
610
+ drawerRef.current.classList.remove(DRAG_CLASS);
611
+ isAllowedToDrag.current = false;
612
+ setIsDragging(false);
613
+ dragEndTime.current = new Date();
614
+ }
615
+
616
+ function onRelease(event: React.PointerEvent<HTMLDivElement> | null) {
617
+ if (!isDragging || !drawerRef.current) return;
618
+
619
+ drawerRef.current.classList.remove(DRAG_CLASS);
620
+ isAllowedToDrag.current = false;
621
+ setIsDragging(false);
622
+ dragEndTime.current = new Date();
623
+ const swipeAmount = getTranslate(drawerRef.current, direction);
624
+
625
+ if (
626
+ !event || !shouldDrag(event.target, false) || !swipeAmount || Number.isNaN(swipeAmount)
627
+ ) return;
628
+
629
+ if (dragStartTime.current === null) return;
630
+
631
+ const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
632
+ const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
633
+ const velocity = Math.abs(distMoved) / timeTaken;
634
+
635
+ if (velocity > 0.05) {
636
+ // `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.
637
+ setJustReleased(true);
638
+
639
+ setTimeout(() => {
640
+ setJustReleased(false);
641
+ }, 200);
642
+ }
643
+
644
+ if (snapPoints) {
645
+ const directionMultiplier =
646
+ direction === 'bottom' || direction === 'right' ? 1 : -1;
647
+ onReleaseSnapPoints({
648
+ draggedDistance: distMoved * directionMultiplier,
649
+ closeDrawer,
650
+ velocity,
651
+ dismissible,
652
+ });
653
+ onReleaseProp?.(event, true);
654
+ return;
655
+ }
656
+
657
+ // Moved upwards, don't do anything
658
+ if (direction === 'bottom' || direction === 'right' ? distMoved > 0 : distMoved < 0) {
659
+ resetDrawer();
660
+ onReleaseProp?.(event, true);
661
+ return;
662
+ }
663
+
664
+ if (velocity > VELOCITY_THRESHOLD) {
665
+ closeDrawer();
666
+ onReleaseProp?.(event, false);
667
+ return;
668
+ }
669
+
670
+ const visibleDrawerHeight = Math.min(
671
+ drawerRef.current.getBoundingClientRect().height ?? 0,
672
+ window.innerHeight,
673
+ );
674
+ const visibleDrawerWidth = Math.min(
675
+ drawerRef.current.getBoundingClientRect().width ?? 0,
676
+ window.innerWidth,
677
+ );
678
+
679
+ const isHorizontalSwipe = direction === 'left' || direction === 'right';
680
+ if (
681
+ Math.abs(swipeAmount) >=
682
+ (isHorizontalSwipe ? visibleDrawerWidth : visibleDrawerHeight) * closeThreshold
683
+ ) {
684
+ closeDrawer();
685
+ onReleaseProp?.(event, false);
686
+ return;
687
+ }
688
+
689
+ onReleaseProp?.(event, true);
690
+ resetDrawer();
691
+ }
692
+
693
+ useEffect(() => {
694
+ // Trigger enter animation without using CSS animation
695
+ if (isOpen) {
696
+ set(document.documentElement, {
697
+ scrollBehavior: 'auto',
698
+ });
699
+
700
+ openTime.current = new Date();
701
+ }
702
+
703
+ return () => {
704
+ reset(document.documentElement, 'scrollBehavior');
705
+ };
706
+ }, [isOpen]);
707
+
708
+ useEffect(
709
+ () => () => {
710
+ if (nestedOpenChangeTimer.current) {
711
+ window.clearTimeout(nestedOpenChangeTimer.current);
712
+ nestedOpenChangeTimer.current = null;
713
+ }
714
+ },
715
+ [],
716
+ );
717
+
718
+ function onNestedOpenChange(o: boolean) {
719
+ const scale = o ? (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth : 1;
720
+
721
+ const initialTranslate = o ? -NESTED_DISPLACEMENT : 0;
722
+
723
+ if (nestedOpenChangeTimer.current) {
724
+ window.clearTimeout(nestedOpenChangeTimer.current);
725
+ }
726
+
727
+ set(drawerRef.current, {
728
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
729
+ transform: isVertical(direction)
730
+ ? `scale(${scale}) translate3d(0, ${initialTranslate}px, 0)`
731
+ : `scale(${scale}) translate3d(${initialTranslate}px, 0, 0)`,
732
+ });
733
+
734
+ if (!o && drawerRef.current) {
735
+ nestedOpenChangeTimer.current = setTimeout(() => {
736
+ const translateValue = getTranslate(drawerRef.current as HTMLElement, direction);
737
+ set(drawerRef.current, {
738
+ transition: 'none',
739
+ transform: isVertical(direction)
740
+ ? `translate3d(0, ${translateValue}px, 0)`
741
+ : `translate3d(${translateValue}px, 0, 0)`,
742
+ });
743
+ }, 500);
744
+ }
745
+ }
746
+
747
+ function onNestedDrag(_event: React.PointerEvent<HTMLDivElement>, percentageDragged: number) {
748
+ if (percentageDragged < 0) return;
749
+
750
+ const initialScale = (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth;
751
+ const newScale = initialScale + percentageDragged * (1 - initialScale);
752
+ const newTranslate = -NESTED_DISPLACEMENT + percentageDragged * NESTED_DISPLACEMENT;
753
+
754
+ set(drawerRef.current, {
755
+ transform: isVertical(direction)
756
+ ? `scale(${newScale}) translate3d(0, ${newTranslate}px, 0)`
757
+ : `scale(${newScale}) translate3d(${newTranslate}px, 0, 0)`,
758
+ transition: 'none',
759
+ });
760
+ }
761
+
762
+ function onNestedRelease(_event: React.PointerEvent<HTMLDivElement>, o: boolean) {
763
+ const dim = isVertical(direction) ? window.innerHeight : window.innerWidth;
764
+ const scale = o ? (dim - NESTED_DISPLACEMENT) / dim : 1;
765
+ const translate = o ? -NESTED_DISPLACEMENT : 0;
766
+
767
+ if (o) {
768
+ set(drawerRef.current, {
769
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(
770
+ ',',
771
+ )})`,
772
+ transform: isVertical(direction)
773
+ ? `scale(${scale}) translate3d(0, ${translate}px, 0)`
774
+ : `scale(${scale}) translate3d(${translate}px, 0, 0)`,
775
+ });
776
+ }
777
+ }
778
+
779
+ useEffect(() => {
780
+ if (!modal) {
781
+ // Need to do this manually unfortunately
782
+ window.requestAnimationFrame(() => {
783
+ document.body.style.pointerEvents = 'auto';
784
+ });
785
+ }
786
+ }, [modal]);
787
+
788
+ <DialogPrimitive.Root
789
+ defaultOpen={defaultOpen}
790
+ onOpenChange={(open: boolean) => {
791
+ if (!dismissible && !open) return;
792
+ if (open) {
793
+ setHasBeenOpened(true);
794
+ } else {
795
+ closeDrawer(true);
796
+ }
797
+
798
+ setIsOpen(open);
799
+ }}
800
+ open={isOpen}
801
+ >
802
+ <DrawerContext.Provider
803
+ value={{
804
+ activeSnapPoint,
805
+ snapPoints,
806
+ setActiveSnapPoint,
807
+ drawerRef,
808
+ overlayRef,
809
+ onOpenChange,
810
+ onPress,
811
+ onRelease,
812
+ onDrag,
813
+ dismissible,
814
+ shouldAnimate,
815
+ handleOnly,
816
+ isOpen,
817
+ isDragging,
818
+ shouldFade,
819
+ closeDrawer,
820
+ onNestedDrag,
821
+ onNestedOpenChange,
822
+ onNestedRelease,
823
+ keyboardIsOpen,
824
+ modal,
825
+ snapPointsOffset,
826
+ activeSnapPointIndex,
827
+ direction,
828
+ shouldScaleBackground,
829
+ setBackgroundColorOnScale,
830
+ noBodyStyles,
831
+ container,
832
+ autoFocus,
833
+ }}
834
+ >{children}</DrawerContext.Provider>
835
+ </DialogPrimitive.Root>
836
+ }
837
+
838
+ export type OverlayProps =
839
+ React.ComponentPropsWithoutRef<'div'> & {
840
+ forceMount?: true;
841
+ ref?: React.Ref<HTMLDivElement>;
842
+ };
843
+
844
+ export function Overlay({ ref, ...rest }: OverlayProps) @{
845
+ const { overlayRef, snapPoints, onRelease, shouldFade, isOpen, modal, shouldAnimate } =
846
+ useDrawerContext();
847
+ const composedRef = useComposedRefs(ref, overlayRef);
848
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
849
+
850
+ // Overlay is the component that is locking scroll, removing it will unlock the scroll without having to dig into Radix's Dialog library
851
+ if (!modal) {
852
+ return null;
853
+ }
854
+
855
+ const onMouseUp = useCallback((event: React.PointerEvent<HTMLDivElement>) => onRelease(event), [
856
+ onRelease,
857
+ ]);
858
+
859
+ <DialogPrimitive.Overlay
860
+ onMouseUp={onMouseUp}
861
+ ref={composedRef}
862
+ data-vaul-overlay=""
863
+ data-vaul-snap-points={isOpen && hasSnapPoints ? 'true' : 'false'}
864
+ data-vaul-snap-points-overlay={isOpen && shouldFade ? 'true' : 'false'}
865
+ data-vaul-animate={shouldAnimate?.current ? 'true' : 'false'}
866
+ {...rest}
867
+ />
868
+ }
869
+
870
+ type PreventableEvent = Event & { defaultPrevented: boolean; preventDefault(): void };
871
+
872
+ export type ContentProps =
873
+ React.ComponentPropsWithoutRef<'div'> & {
874
+ forceMount?: true;
875
+ onOpenAutoFocus?: (event: PreventableEvent) => void;
876
+ onCloseAutoFocus?: (event: PreventableEvent) => void;
877
+ onEscapeKeyDown?: (event: KeyboardEvent) => void;
878
+ onPointerDownOutside?: (event: PreventableEvent) => void;
879
+ onFocusOutside?: (event: PreventableEvent) => void;
880
+ onInteractOutside?: (event: PreventableEvent) => void;
881
+ };
882
+
883
+ export function Content({
884
+ ref,
885
+ onPointerDownOutside,
886
+ style,
887
+ onOpenAutoFocus,
888
+ ...rest
889
+ }: ContentProps & { ref?: React.Ref<HTMLDivElement> }) @{
890
+ const {
891
+ drawerRef,
892
+ onPress,
893
+ onRelease,
894
+ onDrag,
895
+ keyboardIsOpen,
896
+ snapPointsOffset,
897
+ activeSnapPointIndex,
898
+ modal,
899
+ isOpen,
900
+ direction,
901
+ snapPoints,
902
+ container,
903
+ handleOnly,
904
+ shouldAnimate,
905
+ autoFocus,
906
+ } = useDrawerContext();
907
+ // Needed to use transition instead of animations
908
+ const [delayedSnapPoints, setDelayedSnapPoints] = useState(false);
909
+ const composedRef = useComposedRefs(ref, drawerRef);
910
+ const pointerStartRef = useRef<{ x: number; y: number } | null>(null);
911
+ const lastKnownPointerEventRef = useRef<React.PointerEvent<HTMLDivElement> | null>(null);
912
+ const wasBeyondThePointRef = useRef(false);
913
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
914
+ useScaleBackground();
915
+
916
+ const isDeltaInDirection = (
917
+ delta: { x: number; y: number },
918
+ direction: DrawerDirection,
919
+ threshold = 0,
920
+ ) => {
921
+ if (wasBeyondThePointRef.current) return true;
922
+
923
+ const deltaY = Math.abs(delta.y);
924
+ const deltaX = Math.abs(delta.x);
925
+ const isDeltaX = deltaX > deltaY;
926
+ const dFactor = ['bottom', 'right'].includes(direction) ? 1 : -1;
927
+
928
+ if (direction === 'left' || direction === 'right') {
929
+ const isReverseDirection = delta.x * dFactor < 0;
930
+ if (!isReverseDirection && deltaX >= 0 && deltaX <= threshold) {
931
+ return isDeltaX;
932
+ }
933
+ } else {
934
+ const isReverseDirection = delta.y * dFactor < 0;
935
+ if (!isReverseDirection && deltaY >= 0 && deltaY <= threshold) {
936
+ return !isDeltaX;
937
+ }
938
+ }
939
+
940
+ wasBeyondThePointRef.current = true;
941
+ return true;
942
+ };
943
+
944
+ useEffect(() => {
945
+ if (hasSnapPoints) {
946
+ window.requestAnimationFrame(() => {
947
+ setDelayedSnapPoints(true);
948
+ });
949
+ }
950
+ }, []);
951
+
952
+ function handleOnPointerUp(event: React.PointerEvent<HTMLDivElement> | null) {
953
+ pointerStartRef.current = null;
954
+ wasBeyondThePointRef.current = false;
955
+ onRelease(event);
956
+ }
957
+
958
+ <DialogPrimitive.Content
959
+ data-vaul-drawer-direction={direction}
960
+ data-vaul-drawer=""
961
+ data-vaul-delayed-snap-points={delayedSnapPoints ? 'true' : 'false'}
962
+ data-vaul-snap-points={isOpen && hasSnapPoints ? 'true' : 'false'}
963
+ data-vaul-custom-container={container ? 'true' : 'false'}
964
+ data-vaul-animate={shouldAnimate?.current ? 'true' : 'false'}
965
+ {...rest}
966
+ ref={composedRef}
967
+ style={snapPointsOffset && snapPointsOffset.length > 0
968
+ ? {
969
+ '--snap-point-height': `${snapPointsOffset[activeSnapPointIndex ?? 0]!}px`,
970
+ ...style,
971
+ } as React.CSSProperties
972
+ : style}
973
+ onPointerDown={(event: any) => {
974
+ if (handleOnly) return;
975
+ rest.onPointerDown?.(event);
976
+ pointerStartRef.current = { x: event.pageX, y: event.pageY };
977
+ onPress(event);
978
+ }}
979
+ onOpenAutoFocus={(e: any) => {
980
+ onOpenAutoFocus?.(e);
981
+
982
+ if (!autoFocus) {
983
+ e.preventDefault();
984
+ }
985
+ }}
986
+ onPointerDownOutside={(e: any) => {
987
+ onPointerDownOutside?.(e);
988
+
989
+ if (!modal || e.defaultPrevented) {
990
+ e.preventDefault();
991
+ return;
992
+ }
993
+
994
+ if (keyboardIsOpen.current) {
995
+ keyboardIsOpen.current = false;
996
+ }
997
+ }}
998
+ onFocusOutside={(e: any) => {
999
+ if (!modal) {
1000
+ e.preventDefault();
1001
+ return;
1002
+ }
1003
+ }}
1004
+ onPointerMove={(event: any) => {
1005
+ lastKnownPointerEventRef.current = event;
1006
+ if (handleOnly) return;
1007
+ rest.onPointerMove?.(event);
1008
+ if (!pointerStartRef.current) return;
1009
+ const yPosition = event.pageY - pointerStartRef.current.y;
1010
+ const xPosition = event.pageX - pointerStartRef.current.x;
1011
+
1012
+ const swipeStartThreshold =
1013
+ event.pointerType === 'touch' ? 10 : 2;
1014
+ const delta = { x: xPosition, y: yPosition };
1015
+
1016
+ const isAllowedToSwipe = isDeltaInDirection(delta, direction, swipeStartThreshold);
1017
+ if (isAllowedToSwipe) onDrag(event);
1018
+ else if (
1019
+ Math.abs(xPosition) > swipeStartThreshold || Math.abs(yPosition) > swipeStartThreshold
1020
+ ) {
1021
+ pointerStartRef.current = null;
1022
+ }
1023
+ }}
1024
+ onPointerUp={(event: any) => {
1025
+ rest.onPointerUp?.(event);
1026
+ pointerStartRef.current = null;
1027
+ wasBeyondThePointRef.current = false;
1028
+ onRelease(event);
1029
+ }}
1030
+ onPointerOut={(event: any) => {
1031
+ rest.onPointerOut?.(event);
1032
+ handleOnPointerUp(lastKnownPointerEventRef.current);
1033
+ }}
1034
+ onContextMenu={(event: any) => {
1035
+ rest.onContextMenu?.(event);
1036
+ if (lastKnownPointerEventRef.current) {
1037
+ handleOnPointerUp(lastKnownPointerEventRef.current);
1038
+ }
1039
+ }}
1040
+ />
1041
+ }
1042
+
1043
+ export type HandleProps =
1044
+ React.ComponentPropsWithoutRef<'div'> & {
1045
+ preventCycle?: boolean;
1046
+ };
1047
+
1048
+ const LONG_HANDLE_PRESS_TIMEOUT = 250;
1049
+ const DOUBLE_TAP_TIMEOUT = 120;
1050
+
1051
+ export function Handle({ ref, preventCycle = false, children, ...rest }: HandleProps & {
1052
+ ref?: React.Ref<HTMLDivElement>;
1053
+ }) @{
1054
+ const {
1055
+ closeDrawer,
1056
+ isDragging,
1057
+ snapPoints,
1058
+ activeSnapPoint,
1059
+ setActiveSnapPoint,
1060
+ dismissible,
1061
+ handleOnly,
1062
+ isOpen,
1063
+ onPress,
1064
+ onDrag,
1065
+ } = useDrawerContext();
1066
+
1067
+ const closeTimeoutIdRef = useRef<number | null>(null);
1068
+ const cycleTimeoutIdRef = useRef<number | null>(null);
1069
+ const shouldCancelInteractionRef = useRef(false);
1070
+
1071
+ useEffect(
1072
+ () => () => {
1073
+ if (closeTimeoutIdRef.current) window.clearTimeout(closeTimeoutIdRef.current);
1074
+ if (cycleTimeoutIdRef.current) window.clearTimeout(cycleTimeoutIdRef.current);
1075
+ },
1076
+ [],
1077
+ );
1078
+
1079
+ function handleStartCycle() {
1080
+ // Stop if this is the second click of a double click
1081
+ if (shouldCancelInteractionRef.current) {
1082
+ handleCancelInteraction();
1083
+ return;
1084
+ }
1085
+ if (cycleTimeoutIdRef.current) window.clearTimeout(cycleTimeoutIdRef.current);
1086
+ cycleTimeoutIdRef.current = window.setTimeout(() => {
1087
+ cycleTimeoutIdRef.current = null;
1088
+ handleCycleSnapPoints();
1089
+ }, DOUBLE_TAP_TIMEOUT);
1090
+ }
1091
+
1092
+ function handleCycleSnapPoints() {
1093
+ // Prevent accidental taps while resizing drawer
1094
+ if (isDragging || preventCycle || shouldCancelInteractionRef.current) {
1095
+ handleCancelInteraction();
1096
+ return;
1097
+ }
1098
+ // Make sure to clear the timeout id if the user releases the handle before the cancel timeout
1099
+ handleCancelInteraction();
1100
+
1101
+ if (!snapPoints || snapPoints.length === 0) {
1102
+ if (!dismissible) {
1103
+ closeDrawer();
1104
+ }
1105
+ return;
1106
+ }
1107
+
1108
+ const isLastSnapPoint = activeSnapPoint === snapPoints[snapPoints.length - 1];
1109
+
1110
+ if (isLastSnapPoint && dismissible) {
1111
+ closeDrawer();
1112
+ return;
1113
+ }
1114
+
1115
+ const currentSnapIndex = snapPoints.findIndex((point) => point === activeSnapPoint);
1116
+ if (currentSnapIndex === -1) return; // activeSnapPoint not found in snapPoints
1117
+ const nextSnapPoint = snapPoints[currentSnapIndex + 1];
1118
+ setActiveSnapPoint(nextSnapPoint);
1119
+ }
1120
+
1121
+ function handleStartInteraction() {
1122
+ if (closeTimeoutIdRef.current) window.clearTimeout(closeTimeoutIdRef.current);
1123
+ closeTimeoutIdRef.current = window.setTimeout(() => {
1124
+ // Cancel click interaction on a long press
1125
+ shouldCancelInteractionRef.current = true;
1126
+ }, LONG_HANDLE_PRESS_TIMEOUT);
1127
+ }
1128
+
1129
+ function handleCancelInteraction() {
1130
+ if (closeTimeoutIdRef.current) {
1131
+ window.clearTimeout(closeTimeoutIdRef.current);
1132
+ closeTimeoutIdRef.current = null;
1133
+ }
1134
+ shouldCancelInteractionRef.current = false;
1135
+ }
1136
+
1137
+ <div
1138
+ onClick={handleStartCycle}
1139
+ onPointerCancel={handleCancelInteraction}
1140
+ onPointerDown={(e) => {
1141
+ if (handleOnly) onPress(e as any);
1142
+ handleStartInteraction();
1143
+ }}
1144
+ onPointerMove={(e) => {
1145
+ if (handleOnly) onDrag(e as any);
1146
+ }}
1147
+ // onPointerUp is already handled by the content component
1148
+ ref={ref}
1149
+ data-vaul-drawer-visible={isOpen ? 'true' : 'false'}
1150
+ data-vaul-handle=""
1151
+ aria-hidden="true"
1152
+ {...rest as any}
1153
+ >
1154
+ {/* Expand handle's hit area beyond what's visible to ensure a 44x44 tap target for touch devices */}
1155
+ <span data-vaul-handle-hitarea="" aria-hidden="true">{children}</span>
1156
+ </div>
1157
+ }
1158
+
1159
+ export function NestedRoot({ onDrag, onOpenChange, open: nestedIsOpen, ...rest }: DialogProps) @{
1160
+ const { onNestedDrag, onNestedOpenChange, onNestedRelease } = useDrawerContext();
1161
+
1162
+ if (!onNestedDrag) {
1163
+ throw new Error('Drawer.NestedRoot must be placed in another drawer');
1164
+ }
1165
+
1166
+ <Root
1167
+ nested
1168
+ open={nestedIsOpen}
1169
+ onClose={() => {
1170
+ onNestedOpenChange(false);
1171
+ }}
1172
+ onDrag={(e, p) => {
1173
+ onNestedDrag(e, p);
1174
+ onDrag?.(e, p);
1175
+ }}
1176
+ onOpenChange={(o) => {
1177
+ if (o) {
1178
+ onNestedOpenChange(o);
1179
+ }
1180
+ onOpenChange?.(o);
1181
+ }}
1182
+ onRelease={onNestedRelease}
1183
+ {...rest}
1184
+ />
1185
+ }
1186
+
1187
+ export type PortalProps = {
1188
+ children?: React.ReactNode;
1189
+ container?: HTMLElement | null;
1190
+ forceMount?: true;
1191
+ };
1192
+
1193
+ export function Portal(props: PortalProps) {
1194
+ const context = useDrawerContext();
1195
+ const { children, container = context.container } = props;
1196
+ const target = container ?? (typeof document === 'undefined' ? null : document.body);
1197
+
1198
+ return target ? createPortal(children, target) : null;
1199
+ }
1200
+
1201
+ type ButtonPrimitiveProps =
1202
+ React.ComponentPropsWithoutRef<'button'> & {
1203
+ ref?: React.Ref<HTMLButtonElement>;
1204
+ };
1205
+ type TitlePrimitiveProps =
1206
+ React.ComponentPropsWithoutRef<'h2'> & {
1207
+ ref?: React.Ref<HTMLHeadingElement>;
1208
+ };
1209
+ type DescriptionPrimitiveProps =
1210
+ React.ComponentPropsWithoutRef<'p'> & {
1211
+ ref?: React.Ref<HTMLParagraphElement>;
1212
+ };
1213
+
1214
+ export const Drawer = {
1215
+ Root,
1216
+ NestedRoot,
1217
+ Content,
1218
+ Overlay,
1219
+ Trigger: DialogPrimitive.Trigger as (props: ButtonPrimitiveProps) => any,
1220
+ Portal,
1221
+ Handle,
1222
+ Close: DialogPrimitive.Close as (props: ButtonPrimitiveProps) => any,
1223
+ Title: DialogPrimitive.Title as (props: TitlePrimitiveProps) => any,
1224
+ Description: DialogPrimitive.Description as (props: DescriptionPrimitiveProps) => any,
1225
+ };