@kadoui/react 2.1.1 → 2.1.2

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 (83) hide show
  1. package/dist/react-components/DrawerSheet/DrawerSheet.d.ts +2 -0
  2. package/dist/react-components/DrawerSheet/DrawerSheet.d.ts.map +1 -0
  3. package/dist/react-components/DrawerSheet/DrawerSheet.js +1 -0
  4. package/dist/react-components/DrawerSheet/browser.d.ts +8 -0
  5. package/dist/react-components/DrawerSheet/browser.d.ts.map +1 -0
  6. package/dist/react-components/DrawerSheet/browser.js +27 -0
  7. package/dist/react-components/DrawerSheet/constants.d.ts +12 -0
  8. package/dist/react-components/DrawerSheet/constants.d.ts.map +1 -0
  9. package/dist/react-components/DrawerSheet/constants.js +11 -0
  10. package/dist/react-components/DrawerSheet/context.d.ts +38 -0
  11. package/dist/react-components/DrawerSheet/context.d.ts.map +1 -0
  12. package/dist/react-components/DrawerSheet/context.js +39 -0
  13. package/dist/react-components/DrawerSheet/helpers.d.ts +17 -0
  14. package/dist/react-components/DrawerSheet/helpers.d.ts.map +1 -0
  15. package/dist/react-components/DrawerSheet/helpers.js +97 -0
  16. package/dist/react-components/DrawerSheet/index.d.ts +147 -0
  17. package/dist/react-components/DrawerSheet/index.d.ts.map +1 -0
  18. package/dist/react-components/DrawerSheet/index.js +803 -0
  19. package/dist/react-components/DrawerSheet/types.d.ts +7 -0
  20. package/dist/react-components/DrawerSheet/types.d.ts.map +1 -0
  21. package/dist/react-components/DrawerSheet/types.js +1 -0
  22. package/dist/react-components/DrawerSheet/use-composed-refs.d.ts +14 -0
  23. package/dist/react-components/DrawerSheet/use-composed-refs.d.ts.map +1 -0
  24. package/dist/react-components/DrawerSheet/use-composed-refs.js +30 -0
  25. package/dist/react-components/DrawerSheet/use-controllable-state.d.ts +9 -0
  26. package/dist/react-components/DrawerSheet/use-controllable-state.d.ts.map +1 -0
  27. package/dist/react-components/DrawerSheet/use-controllable-state.js +41 -0
  28. package/dist/react-components/DrawerSheet/use-position-fixed.d.ts +19 -0
  29. package/dist/react-components/DrawerSheet/use-position-fixed.d.ts.map +1 -0
  30. package/dist/react-components/DrawerSheet/use-position-fixed.js +109 -0
  31. package/dist/react-components/DrawerSheet/use-prevent-scroll.d.ts +18 -0
  32. package/dist/react-components/DrawerSheet/use-prevent-scroll.d.ts.map +1 -0
  33. package/dist/react-components/DrawerSheet/use-prevent-scroll.js +237 -0
  34. package/dist/react-components/DrawerSheet/use-scale-background.d.ts +2 -0
  35. package/dist/react-components/DrawerSheet/use-scale-background.d.ts.map +1 -0
  36. package/dist/react-components/DrawerSheet/use-scale-background.js +50 -0
  37. package/dist/react-components/DrawerSheet/use-snap-points.d.ts +32 -0
  38. package/dist/react-components/DrawerSheet/use-snap-points.d.ts.map +1 -0
  39. package/dist/react-components/DrawerSheet/use-snap-points.js +200 -0
  40. package/dist/react-components/drawer-sheet/DrawerSheet.d.ts +23 -0
  41. package/dist/react-components/drawer-sheet/DrawerSheet.d.ts.map +1 -0
  42. package/dist/react-components/drawer-sheet/DrawerSheet.js +22 -0
  43. package/dist/react-components/drawer-sheet/DrawerSheetBackdrop.d.ts +3 -0
  44. package/dist/react-components/drawer-sheet/DrawerSheetBackdrop.d.ts.map +1 -0
  45. package/dist/react-components/drawer-sheet/DrawerSheetBackdrop.js +13 -0
  46. package/dist/react-components/drawer-sheet/DrawerSheetBody.d.ts +3 -0
  47. package/dist/react-components/drawer-sheet/DrawerSheetBody.d.ts.map +1 -0
  48. package/dist/react-components/drawer-sheet/DrawerSheetBody.js +165 -0
  49. package/dist/react-components/drawer-sheet/DrawerSheetContent.d.ts +3 -0
  50. package/dist/react-components/drawer-sheet/DrawerSheetContent.d.ts.map +1 -0
  51. package/dist/react-components/drawer-sheet/DrawerSheetContent.js +16 -0
  52. package/dist/react-components/drawer-sheet/DrawerSheetContext.d.ts +3 -0
  53. package/dist/react-components/drawer-sheet/DrawerSheetContext.d.ts.map +1 -0
  54. package/dist/react-components/drawer-sheet/DrawerSheetContext.js +2 -0
  55. package/dist/react-components/drawer-sheet/DrawerSheetHandlebar.d.ts +3 -0
  56. package/dist/react-components/drawer-sheet/DrawerSheetHandlebar.d.ts.map +1 -0
  57. package/dist/react-components/drawer-sheet/DrawerSheetHandlebar.js +5 -0
  58. package/dist/react-components/drawer-sheet/DrawerSheetHeader.d.ts +3 -0
  59. package/dist/react-components/drawer-sheet/DrawerSheetHeader.d.ts.map +1 -0
  60. package/dist/react-components/drawer-sheet/DrawerSheetHeader.js +5 -0
  61. package/dist/react-components/drawer-sheet/DrawerSheetPortal.d.ts +3 -0
  62. package/dist/react-components/drawer-sheet/DrawerSheetPortal.d.ts.map +1 -0
  63. package/dist/react-components/drawer-sheet/DrawerSheetPortal.js +13 -0
  64. package/dist/react-components/drawer-sheet/DrawerSheetProvider.d.ts +15 -0
  65. package/dist/react-components/drawer-sheet/DrawerSheetProvider.d.ts.map +1 -0
  66. package/dist/react-components/drawer-sheet/DrawerSheetProvider.js +75 -0
  67. package/dist/react-components/drawer-sheet/DrawerSheetRoot.d.ts +3 -0
  68. package/dist/react-components/drawer-sheet/DrawerSheetRoot.d.ts.map +1 -0
  69. package/dist/react-components/drawer-sheet/DrawerSheetRoot.js +130 -0
  70. package/dist/react-components/drawer-sheet/DrawerSheetToggle.d.ts +3 -0
  71. package/dist/react-components/drawer-sheet/DrawerSheetToggle.d.ts.map +1 -0
  72. package/dist/react-components/drawer-sheet/DrawerSheetToggle.js +11 -0
  73. package/dist/react-components/drawer-sheet/DrawerSheetViewport.d.ts +4 -0
  74. package/dist/react-components/drawer-sheet/DrawerSheetViewport.d.ts.map +1 -0
  75. package/dist/react-components/drawer-sheet/DrawerSheetViewport.js +5 -0
  76. package/dist/react-components/drawer-sheet/drawerSheetTypes.d.ts +30 -0
  77. package/dist/react-components/drawer-sheet/drawerSheetTypes.d.ts.map +1 -0
  78. package/dist/react-components/drawer-sheet/drawerSheetTypes.js +1 -0
  79. package/dist/react-exports.d.ts +1 -0
  80. package/dist/react-exports.d.ts.map +1 -1
  81. package/dist/react-exports.js +1 -0
  82. package/dist/tsconfig.tsbuildinfo +1 -1
  83. package/package.json +1 -1
@@ -0,0 +1,803 @@
1
+ 'use client';
2
+ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import React from 'react';
4
+ import { createPortal } from 'react-dom';
5
+ import { useMounted } from '@mantine/hooks';
6
+ import { DrawerContext, useDrawerContext } from './context';
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 { TRANSITIONS, VELOCITY_THRESHOLD, CLOSE_THRESHOLD, SCROLL_LOCK_TIMEOUT, BORDER_RADIUS, NESTED_DISPLACEMENT, WINDOW_TOP_OFFSET, DRAG_CLASS, } from './constants';
12
+ import { useControllableState } from './use-controllable-state';
13
+ import { useScaleBackground } from './use-scale-background';
14
+ import { usePositionFixed } from './use-position-fixed';
15
+ import { isIOS, isMobileFirefox } from './browser';
16
+ import { getBrowserScrollbarWith } from '../../utils-exports';
17
+ export function Root({ open: openProp, onOpenChange, children, onDrag: onDragProp, onRelease: onReleaseProp, snapPoints, shouldScaleBackground = false, setBackgroundColorOnScale = true, closeThreshold = CLOSE_THRESHOLD, scrollLockTimeout = SCROLL_LOCK_TIMEOUT, dismissible = true, handleOnly = false, fadeFromIndex = snapPoints && snapPoints.length - 1, activeSnapPoint: activeSnapPointProp, setActiveSnapPoint: setActiveSnapPointProp, fixed, modal = true, onClose, nested, noBodyStyles = false, direction = 'bottom', defaultOpen = false, disablePreventScroll = true, snapToSequentialPoint = false, preventScrollRestoration = false, repositionInputs = true, onAnimationEnd, container, autoFocus = false, }) {
18
+ const [isOpen = false, setIsOpen] = useControllableState({
19
+ defaultProp: defaultOpen,
20
+ prop: openProp,
21
+ onChange: (o) => {
22
+ onOpenChange?.(o);
23
+ if (!o && !nested) {
24
+ restorePositionSetting();
25
+ }
26
+ setTimeout(() => {
27
+ onAnimationEnd?.(o);
28
+ }, TRANSITIONS.DURATION * 1000);
29
+ if (o && !modal) {
30
+ if (typeof window !== 'undefined') {
31
+ window.requestAnimationFrame(() => {
32
+ document.body.style.pointerEvents = 'auto';
33
+ });
34
+ }
35
+ }
36
+ if (!o) {
37
+ // This will be removed when the exit animation ends (`500ms`)
38
+ document.body.style.pointerEvents = 'auto';
39
+ }
40
+ },
41
+ });
42
+ const [hasBeenOpened, setHasBeenOpened] = React.useState(false);
43
+ const [isDragging, setIsDragging] = React.useState(false);
44
+ const [justReleased, setJustReleased] = React.useState(false);
45
+ const overlayRef = React.useRef(null);
46
+ const openTime = React.useRef(null);
47
+ const dragStartTime = React.useRef(null);
48
+ const dragEndTime = React.useRef(null);
49
+ const lastTimeDragPrevented = React.useRef(null);
50
+ const isAllowedToDrag = React.useRef(false);
51
+ const nestedOpenChangeTimer = React.useRef(null);
52
+ const pointerStart = React.useRef(0);
53
+ const keyboardIsOpen = React.useRef(false);
54
+ const shouldAnimate = React.useRef(!defaultOpen);
55
+ const previousDiffFromInitial = React.useRef(0);
56
+ const drawerRef = React.useRef(null);
57
+ const drawerHeightRef = React.useRef(drawerRef.current?.getBoundingClientRect().height || 0);
58
+ const drawerWidthRef = React.useRef(drawerRef.current?.getBoundingClientRect().width || 0);
59
+ const initialDrawerHeight = React.useRef(0);
60
+ const onSnapPointChange = React.useCallback((activeSnapPointIndex) => {
61
+ if (snapPoints && activeSnapPointIndex === snapPoints.length - 1)
62
+ openTime.current = new Date();
63
+ }, [snapPoints]);
64
+ const { activeSnapPoint, activeSnapPointIndex, setActiveSnapPoint, onRelease: onReleaseSnapPoints, snapPointsOffset, onDrag: onDragSnapPoints, shouldFade, getPercentageDragged: getSnapPointsPercentageDragged, } = useSnapPoints({
65
+ snapPoints,
66
+ activeSnapPointProp,
67
+ setActiveSnapPointProp,
68
+ drawerRef,
69
+ fadeFromIndex,
70
+ overlayRef,
71
+ onSnapPointChange,
72
+ direction,
73
+ container,
74
+ snapToSequentialPoint,
75
+ });
76
+ usePreventScroll({
77
+ isDisabled: !isOpen || isDragging || !modal || justReleased || !hasBeenOpened || !repositionInputs || !disablePreventScroll,
78
+ });
79
+ const { restorePositionSetting } = usePositionFixed({
80
+ isOpen,
81
+ modal,
82
+ nested: nested ?? false,
83
+ hasBeenOpened,
84
+ preventScrollRestoration,
85
+ noBodyStyles,
86
+ });
87
+ function getScale() {
88
+ return (window.innerWidth - WINDOW_TOP_OFFSET) / window.innerWidth;
89
+ }
90
+ function onPress(event) {
91
+ if (!dismissible && !snapPoints)
92
+ return;
93
+ if (drawerRef.current && !drawerRef.current.contains(event.target))
94
+ return;
95
+ drawerHeightRef.current = drawerRef.current?.getBoundingClientRect().height || 0;
96
+ drawerWidthRef.current = drawerRef.current?.getBoundingClientRect().width || 0;
97
+ setIsDragging(true);
98
+ dragStartTime.current = new Date();
99
+ // iOS doesn't trigger mouseUp after scrolling so we need to listen to touched in order to disallow dragging
100
+ if (isIOS()) {
101
+ window.addEventListener('touchend', () => (isAllowedToDrag.current = false), { once: true });
102
+ }
103
+ // Ensure we maintain correct pointer capture even when going outside of the drawer
104
+ event.target.setPointerCapture(event.pointerId);
105
+ pointerStart.current = isVertical(direction) ? event.pageY : event.pageX;
106
+ }
107
+ function shouldDrag(el, isDraggingInDirection) {
108
+ let element = el;
109
+ const highlightedText = window.getSelection()?.toString();
110
+ const swipeAmount = drawerRef.current ? getTranslate(drawerRef.current, direction) : null;
111
+ const date = new Date();
112
+ // Fixes https://github.com/emilkowalski/vaul/issues/483
113
+ if (element.tagName === 'SELECT') {
114
+ return false;
115
+ }
116
+ if (element.hasAttribute('data-drawer-sheet-no-drag') || element.closest('[data-drawer-sheet-no-drag]')) {
117
+ return false;
118
+ }
119
+ if (direction === 'right' || direction === 'left') {
120
+ return true;
121
+ }
122
+ // Allow scrolling when animating
123
+ if (openTime.current && date.getTime() - openTime.current.getTime() < 500) {
124
+ return false;
125
+ }
126
+ if (swipeAmount !== null) {
127
+ if (direction === 'bottom' ? swipeAmount > 0 : swipeAmount < 0) {
128
+ return true;
129
+ }
130
+ }
131
+ // Don't drag if there's highlighted text
132
+ if (highlightedText && highlightedText.length > 0) {
133
+ return false;
134
+ }
135
+ // Disallow dragging if drawer was scrolled within `scrollLockTimeout`
136
+ if (lastTimeDragPrevented.current &&
137
+ date.getTime() - lastTimeDragPrevented.current.getTime() < scrollLockTimeout &&
138
+ swipeAmount === 0) {
139
+ lastTimeDragPrevented.current = date;
140
+ return false;
141
+ }
142
+ if (isDraggingInDirection) {
143
+ lastTimeDragPrevented.current = date;
144
+ // We are dragging down so we should allow scrolling
145
+ return false;
146
+ }
147
+ // Keep climbing up the DOM tree as long as there's a parent
148
+ while (element) {
149
+ // Check if the element is scrollable
150
+ if (element.scrollHeight > element.clientHeight) {
151
+ if (element.scrollTop !== 0) {
152
+ lastTimeDragPrevented.current = new Date();
153
+ // The element is scrollable and not scrolled to the top, so don't drag
154
+ return false;
155
+ }
156
+ if (element.getAttribute('role') === 'dialog') {
157
+ return true;
158
+ }
159
+ }
160
+ // Move up to the parent element
161
+ element = element.parentNode;
162
+ }
163
+ // No scrollable parents not scrolled to the top found, so drag
164
+ return true;
165
+ }
166
+ function onDrag(event) {
167
+ if (!drawerRef.current) {
168
+ return;
169
+ }
170
+ // We need to know how much of the drawer has been dragged in percentages so that we can transform background accordingly
171
+ if (isDragging) {
172
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
173
+ const draggedDistance = (pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX)) * directionMultiplier;
174
+ const isDraggingInDirection = draggedDistance > 0;
175
+ // Pre condition for disallowing dragging in the close direction.
176
+ const noCloseSnapPointsPreCondition = snapPoints && !dismissible && !isDraggingInDirection;
177
+ // Disallow dragging down to close when first snap point is the active one and dismissible prop is set to false.
178
+ if (noCloseSnapPointsPreCondition && activeSnapPointIndex === 0)
179
+ return;
180
+ // We need to capture last time when drag with scroll was triggered and have a timeout between
181
+ const absDraggedDistance = Math.abs(draggedDistance);
182
+ const wrapper = document.querySelector('[data-drawer-sheet-wrapper]');
183
+ const drawerDimension = direction === 'bottom' || direction === 'top' ? drawerHeightRef.current : drawerWidthRef.current;
184
+ // Calculate the percentage dragged, where 1 is the closed position
185
+ let percentageDragged = absDraggedDistance / drawerDimension;
186
+ const snapPointPercentageDragged = getSnapPointsPercentageDragged(absDraggedDistance, isDraggingInDirection);
187
+ if (snapPointPercentageDragged !== null) {
188
+ percentageDragged = snapPointPercentageDragged;
189
+ }
190
+ // Disallow close dragging beyond the smallest snap point.
191
+ if (noCloseSnapPointsPreCondition && percentageDragged >= 1) {
192
+ return;
193
+ }
194
+ if (!isAllowedToDrag.current && !shouldDrag(event.target, isDraggingInDirection))
195
+ return;
196
+ drawerRef.current.classList.add(DRAG_CLASS);
197
+ // 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
198
+ isAllowedToDrag.current = true;
199
+ set(drawerRef.current, {
200
+ transition: 'none',
201
+ });
202
+ set(overlayRef.current, {
203
+ transition: 'none',
204
+ });
205
+ if (snapPoints) {
206
+ onDragSnapPoints({ draggedDistance });
207
+ }
208
+ // Run this only if snapPoints are not defined or if we are at the last snap point (highest one)
209
+ if (isDraggingInDirection && !snapPoints) {
210
+ const dampenedDraggedDistance = dampenValue(draggedDistance);
211
+ const translateValue = Math.min(dampenedDraggedDistance * -1, 0) * directionMultiplier;
212
+ set(drawerRef.current, {
213
+ transform: isVertical(direction)
214
+ ? `translate3d(0, ${translateValue}px, 0)`
215
+ : `translate3d(${translateValue}px, 0, 0)`,
216
+ });
217
+ return;
218
+ }
219
+ const opacityValue = 1 - percentageDragged;
220
+ if (shouldFade || (fadeFromIndex && activeSnapPointIndex === fadeFromIndex - 1)) {
221
+ onDragProp?.(event, percentageDragged);
222
+ set(overlayRef.current, {
223
+ opacity: `${opacityValue}`,
224
+ transition: 'none',
225
+ }, true);
226
+ }
227
+ if (wrapper && overlayRef.current && shouldScaleBackground) {
228
+ // Calculate percentageDragged as a fraction (0 to 1)
229
+ const scaleValue = Math.min(getScale() + percentageDragged * (1 - getScale()), 1);
230
+ const borderRadiusValue = 8 - percentageDragged * 8;
231
+ const translateValue = Math.max(0, 14 - percentageDragged * 14);
232
+ set(wrapper, {
233
+ borderRadius: `${borderRadiusValue}px`,
234
+ transform: isVertical(direction)
235
+ ? `scale(${scaleValue}) translate3d(0, ${translateValue}px, 0)`
236
+ : `scale(${scaleValue}) translate3d(${translateValue}px, 0, 0)`,
237
+ transition: 'none',
238
+ }, true);
239
+ }
240
+ if (!snapPoints) {
241
+ const translateValue = absDraggedDistance * directionMultiplier;
242
+ set(drawerRef.current, {
243
+ transform: isVertical(direction)
244
+ ? `translate3d(0, ${translateValue}px, 0)`
245
+ : `translate3d(${translateValue}px, 0, 0)`,
246
+ });
247
+ }
248
+ }
249
+ }
250
+ React.useEffect(() => {
251
+ window.requestAnimationFrame(() => {
252
+ shouldAnimate.current = true;
253
+ });
254
+ }, []);
255
+ React.useEffect(() => {
256
+ function onVisualViewportChange() {
257
+ if (!drawerRef.current || !repositionInputs)
258
+ return;
259
+ const focusedElement = document.activeElement;
260
+ if (isInput(focusedElement) || keyboardIsOpen.current) {
261
+ const visualViewportHeight = window.visualViewport?.height || 0;
262
+ const totalHeight = window.innerHeight;
263
+ // This is the height of the keyboard
264
+ let diffFromInitial = totalHeight - visualViewportHeight;
265
+ const drawerHeight = drawerRef.current.getBoundingClientRect().height || 0;
266
+ // Adjust drawer height only if it's tall enough
267
+ const isTallEnough = drawerHeight > totalHeight * 0.8;
268
+ if (!initialDrawerHeight.current) {
269
+ initialDrawerHeight.current = drawerHeight;
270
+ }
271
+ const offsetFromTop = drawerRef.current.getBoundingClientRect().top;
272
+ // 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.
273
+ if (Math.abs(previousDiffFromInitial.current - diffFromInitial) > 60) {
274
+ keyboardIsOpen.current = !keyboardIsOpen.current;
275
+ }
276
+ if (snapPoints && snapPoints.length > 0 && snapPointsOffset && activeSnapPointIndex) {
277
+ const activeSnapPointHeight = snapPointsOffset[activeSnapPointIndex] || 0;
278
+ diffFromInitial += activeSnapPointHeight;
279
+ }
280
+ previousDiffFromInitial.current = diffFromInitial;
281
+ // 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
282
+ if (drawerHeight > visualViewportHeight || keyboardIsOpen.current) {
283
+ const height = drawerRef.current.getBoundingClientRect().height;
284
+ let newDrawerHeight = height;
285
+ if (height > visualViewportHeight) {
286
+ newDrawerHeight = visualViewportHeight - (isTallEnough ? offsetFromTop : WINDOW_TOP_OFFSET);
287
+ }
288
+ // 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
289
+ if (fixed) {
290
+ drawerRef.current.style.height = `${height - Math.max(diffFromInitial, 0)}px`;
291
+ }
292
+ else {
293
+ drawerRef.current.style.height = `${Math.max(newDrawerHeight, visualViewportHeight - offsetFromTop)}px`;
294
+ }
295
+ }
296
+ else if (!isMobileFirefox()) {
297
+ drawerRef.current.style.height = `${initialDrawerHeight.current}px`;
298
+ }
299
+ if (snapPoints && snapPoints.length > 0 && !keyboardIsOpen.current) {
300
+ drawerRef.current.style.bottom = `0px`;
301
+ }
302
+ else {
303
+ // Negative bottom value would never make sense
304
+ drawerRef.current.style.bottom = `${Math.max(diffFromInitial, 0)}px`;
305
+ }
306
+ }
307
+ }
308
+ window.visualViewport?.addEventListener('resize', onVisualViewportChange);
309
+ return () => window.visualViewport?.removeEventListener('resize', onVisualViewportChange);
310
+ }, [activeSnapPointIndex, snapPoints, snapPointsOffset]);
311
+ function closeDrawer(fromWithin) {
312
+ cancelDrag();
313
+ onClose?.();
314
+ if (!fromWithin) {
315
+ setIsOpen(false);
316
+ }
317
+ setTimeout(() => {
318
+ if (snapPoints) {
319
+ setActiveSnapPoint(snapPoints[0]);
320
+ }
321
+ }, TRANSITIONS.DURATION * 1000); // seconds to ms
322
+ }
323
+ function resetDrawer() {
324
+ if (!drawerRef.current)
325
+ return;
326
+ const wrapper = document.querySelector('[data-drawer-sheet-wrapper]');
327
+ const currentSwipeAmount = getTranslate(drawerRef.current, direction);
328
+ set(drawerRef.current, {
329
+ transform: 'translate3d(0, 0, 0)',
330
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
331
+ });
332
+ set(overlayRef.current, {
333
+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
334
+ opacity: '1',
335
+ });
336
+ // Don't reset background if swiped upwards
337
+ if (shouldScaleBackground && currentSwipeAmount && currentSwipeAmount > 0 && isOpen) {
338
+ set(wrapper, {
339
+ borderRadius: `${BORDER_RADIUS}px`,
340
+ overflow: 'hidden',
341
+ ...(isVertical(direction)
342
+ ? {
343
+ transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
344
+ transformOrigin: 'top',
345
+ }
346
+ : {
347
+ transform: `scale(${getScale()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,
348
+ transformOrigin: 'left',
349
+ }),
350
+ transitionProperty: 'transform, border-radius',
351
+ transitionDuration: `${TRANSITIONS.DURATION}s`,
352
+ transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
353
+ }, true);
354
+ }
355
+ }
356
+ function cancelDrag() {
357
+ if (!isDragging || !drawerRef.current)
358
+ return;
359
+ drawerRef.current.classList.remove(DRAG_CLASS);
360
+ isAllowedToDrag.current = false;
361
+ setIsDragging(false);
362
+ dragEndTime.current = new Date();
363
+ }
364
+ function onRelease(event) {
365
+ if (!isDragging || !drawerRef.current)
366
+ return;
367
+ drawerRef.current.classList.remove(DRAG_CLASS);
368
+ isAllowedToDrag.current = false;
369
+ setIsDragging(false);
370
+ dragEndTime.current = new Date();
371
+ const swipeAmount = getTranslate(drawerRef.current, direction);
372
+ if (!event || !shouldDrag(event.target, false) || !swipeAmount || Number.isNaN(swipeAmount))
373
+ return;
374
+ if (dragStartTime.current === null)
375
+ return;
376
+ const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
377
+ const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
378
+ const velocity = Math.abs(distMoved) / timeTaken;
379
+ if (velocity > 0.05) {
380
+ // `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.
381
+ setJustReleased(true);
382
+ setTimeout(() => {
383
+ setJustReleased(false);
384
+ }, 200);
385
+ }
386
+ if (snapPoints) {
387
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
388
+ onReleaseSnapPoints({
389
+ draggedDistance: distMoved * directionMultiplier,
390
+ closeDrawer,
391
+ velocity,
392
+ dismissible,
393
+ });
394
+ onReleaseProp?.(event, true);
395
+ return;
396
+ }
397
+ // Moved upwards, don't do anything
398
+ if (direction === 'bottom' || direction === 'right' ? distMoved > 0 : distMoved < 0) {
399
+ resetDrawer();
400
+ onReleaseProp?.(event, true);
401
+ return;
402
+ }
403
+ if (velocity > VELOCITY_THRESHOLD) {
404
+ closeDrawer();
405
+ onReleaseProp?.(event, false);
406
+ return;
407
+ }
408
+ const visibleDrawerHeight = Math.min(drawerRef.current.getBoundingClientRect().height ?? 0, window.innerHeight);
409
+ const visibleDrawerWidth = Math.min(drawerRef.current.getBoundingClientRect().width ?? 0, window.innerWidth);
410
+ const isHorizontalSwipe = direction === 'left' || direction === 'right';
411
+ if (Math.abs(swipeAmount) >= (isHorizontalSwipe ? visibleDrawerWidth : visibleDrawerHeight) * closeThreshold) {
412
+ closeDrawer();
413
+ onReleaseProp?.(event, false);
414
+ return;
415
+ }
416
+ onReleaseProp?.(event, true);
417
+ resetDrawer();
418
+ }
419
+ React.useEffect(() => {
420
+ // Trigger enter animation without using CSS animation
421
+ if (isOpen) {
422
+ set(document.documentElement, {
423
+ scrollBehavior: 'auto',
424
+ });
425
+ openTime.current = new Date();
426
+ }
427
+ return () => {
428
+ reset(document.documentElement, 'scrollBehavior');
429
+ };
430
+ }, [isOpen]);
431
+ function onNestedOpenChange(o) {
432
+ const scale = o ? (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth : 1;
433
+ const initialTranslate = o ? -NESTED_DISPLACEMENT : 0;
434
+ if (nestedOpenChangeTimer.current) {
435
+ window.clearTimeout(nestedOpenChangeTimer.current);
436
+ }
437
+ set(drawerRef.current, {
438
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
439
+ transform: isVertical(direction)
440
+ ? `scale(${scale}) translate3d(0, ${initialTranslate}px, 0)`
441
+ : `scale(${scale}) translate3d(${initialTranslate}px, 0, 0)`,
442
+ });
443
+ if (!o && drawerRef.current) {
444
+ nestedOpenChangeTimer.current = setTimeout(() => {
445
+ const translateValue = getTranslate(drawerRef.current, direction);
446
+ set(drawerRef.current, {
447
+ transition: 'none',
448
+ transform: isVertical(direction)
449
+ ? `translate3d(0, ${translateValue}px, 0)`
450
+ : `translate3d(${translateValue}px, 0, 0)`,
451
+ });
452
+ }, 500);
453
+ }
454
+ }
455
+ function onNestedDrag(_event, percentageDragged) {
456
+ if (percentageDragged < 0)
457
+ return;
458
+ const initialScale = (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth;
459
+ const newScale = initialScale + percentageDragged * (1 - initialScale);
460
+ const newTranslate = -NESTED_DISPLACEMENT + percentageDragged * NESTED_DISPLACEMENT;
461
+ set(drawerRef.current, {
462
+ transform: isVertical(direction)
463
+ ? `scale(${newScale}) translate3d(0, ${newTranslate}px, 0)`
464
+ : `scale(${newScale}) translate3d(${newTranslate}px, 0, 0)`,
465
+ transition: 'none',
466
+ });
467
+ }
468
+ function onNestedRelease(_event, o) {
469
+ const dim = isVertical(direction) ? window.innerHeight : window.innerWidth;
470
+ const scale = o ? (dim - NESTED_DISPLACEMENT) / dim : 1;
471
+ const translate = o ? -NESTED_DISPLACEMENT : 0;
472
+ if (o) {
473
+ set(drawerRef.current, {
474
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
475
+ transform: isVertical(direction)
476
+ ? `scale(${scale}) translate3d(0, ${translate}px, 0)`
477
+ : `scale(${scale}) translate3d(${translate}px, 0, 0)`,
478
+ });
479
+ }
480
+ }
481
+ React.useEffect(() => {
482
+ if (!modal) {
483
+ window.requestAnimationFrame(() => {
484
+ document.body.style.pointerEvents = 'auto';
485
+ });
486
+ }
487
+ }, [modal]);
488
+ React.useEffect(() => {
489
+ const handleEscape = (e) => {
490
+ if (e.key === 'Escape' && dismissible && isOpen) {
491
+ closeDrawer(true);
492
+ setIsOpen(false);
493
+ }
494
+ };
495
+ document.addEventListener('keydown', handleEscape);
496
+ return () => document.removeEventListener('keydown', handleEscape);
497
+ }, [dismissible, isOpen, closeDrawer]);
498
+ React.useEffect(() => {
499
+ const scrollbarWidth = getBrowserScrollbarWith();
500
+ const removeStyles = () => {
501
+ document.body.style.overflow = '';
502
+ document.body.style.paddingRight = '';
503
+ };
504
+ if (isOpen && modal) {
505
+ document.body.style.overflow = 'hidden';
506
+ document.body.style.paddingRight = `${scrollbarWidth}px`;
507
+ }
508
+ else {
509
+ removeStyles();
510
+ }
511
+ return removeStyles;
512
+ }, [isOpen, modal]);
513
+ const handleOpenChange = React.useCallback((open) => {
514
+ if (!dismissible && !open)
515
+ return;
516
+ if (open) {
517
+ setHasBeenOpened(true);
518
+ }
519
+ else {
520
+ closeDrawer(true);
521
+ }
522
+ setIsOpen(open);
523
+ }, [dismissible, closeDrawer]);
524
+ return (_jsx(DrawerContext.Provider, { value: {
525
+ activeSnapPoint,
526
+ snapPoints,
527
+ setActiveSnapPoint,
528
+ drawerRef,
529
+ overlayRef,
530
+ onOpenChange: handleOpenChange,
531
+ onPress,
532
+ onRelease,
533
+ onDrag,
534
+ dismissible,
535
+ shouldAnimate,
536
+ handleOnly,
537
+ isOpen,
538
+ isDragging,
539
+ shouldFade,
540
+ closeDrawer,
541
+ onNestedDrag,
542
+ onNestedOpenChange,
543
+ onNestedRelease,
544
+ keyboardIsOpen,
545
+ modal,
546
+ snapPointsOffset,
547
+ activeSnapPointIndex,
548
+ direction,
549
+ shouldScaleBackground,
550
+ setBackgroundColorOnScale,
551
+ noBodyStyles,
552
+ container,
553
+ autoFocus,
554
+ }, children: children }));
555
+ }
556
+ export const Overlay = React.forwardRef(function ({ onPointerUp, className, ...rest }, ref) {
557
+ const { overlayRef, snapPoints, onRelease, shouldFade, isOpen, modal, shouldAnimate, closeDrawer, dismissible, } = useDrawerContext();
558
+ const composedRef = useComposedRefs(ref, overlayRef);
559
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
560
+ if (!modal)
561
+ return null;
562
+ return (_jsx("div", { ref: composedRef, "data-drawer-sheet-overlay": "", "data-snap-points": isOpen && hasSnapPoints ? 'true' : 'false', "data-snap-points-overlay": isOpen && shouldFade ? 'true' : 'false', "data-drawer-sheet-animate": shouldAnimate?.current ? 'true' : 'false', "data-state": isOpen ? 'open' : 'closed', onPointerUp: (e) => {
563
+ onPointerUp?.(e);
564
+ onRelease(e);
565
+ }, onClick: () => {
566
+ if (dismissible && isOpen)
567
+ closeDrawer(false);
568
+ }, className: className, ...rest }));
569
+ });
570
+ Overlay.displayName = 'DrawerSheet.Overlay';
571
+ export const Content = React.forwardRef(function ({ style, ...rest }, ref) {
572
+ const { drawerRef, onPress, onRelease, onDrag, keyboardIsOpen, snapPointsOffset, activeSnapPointIndex, modal, isOpen, direction, snapPoints, container, handleOnly, shouldAnimate, autoFocus, } = useDrawerContext();
573
+ // Needed to use transition instead of animations
574
+ const [delayedSnapPoints, setDelayedSnapPoints] = React.useState(false);
575
+ const composedRef = useComposedRefs(ref, drawerRef);
576
+ const pointerStartRef = React.useRef(null);
577
+ const lastKnownPointerEventRef = React.useRef(null);
578
+ const wasBeyondThePointRef = React.useRef(false);
579
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
580
+ useScaleBackground();
581
+ const isDeltaInDirection = (delta, direction, threshold = 0) => {
582
+ if (wasBeyondThePointRef.current)
583
+ return true;
584
+ const deltaY = Math.abs(delta.y);
585
+ const deltaX = Math.abs(delta.x);
586
+ const isDeltaX = deltaX > deltaY;
587
+ const dFactor = ['bottom', 'right'].includes(direction) ? 1 : -1;
588
+ if (direction === 'left' || direction === 'right') {
589
+ const isReverseDirection = delta.x * dFactor < 0;
590
+ if (!isReverseDirection && deltaX >= 0 && deltaX <= threshold) {
591
+ return isDeltaX;
592
+ }
593
+ }
594
+ else {
595
+ const isReverseDirection = delta.y * dFactor < 0;
596
+ if (!isReverseDirection && deltaY >= 0 && deltaY <= threshold) {
597
+ return !isDeltaX;
598
+ }
599
+ }
600
+ wasBeyondThePointRef.current = true;
601
+ return true;
602
+ };
603
+ React.useEffect(() => {
604
+ if (hasSnapPoints) {
605
+ window.requestAnimationFrame(() => {
606
+ setDelayedSnapPoints(true);
607
+ });
608
+ }
609
+ }, []);
610
+ function handleOnPointerUp(event) {
611
+ pointerStartRef.current = null;
612
+ wasBeyondThePointRef.current = false;
613
+ onRelease(event);
614
+ }
615
+ const positionStyles = direction === 'bottom'
616
+ ? { bottom: 0, left: 0, right: 0 }
617
+ : direction === 'top'
618
+ ? { top: 0, left: 0, right: 0 }
619
+ : direction === 'left'
620
+ ? { top: 0, bottom: 0, left: 0 }
621
+ : { top: 0, bottom: 0, right: 0 };
622
+ return (_jsx("div", { ref: composedRef, role: "dialog", "aria-modal": modal, "data-direction": direction, "data-drawer-sheet": "", "data-delayed-snap-points": delayedSnapPoints ? 'true' : 'false', "data-snap-points": isOpen && hasSnapPoints ? 'true' : 'false', "data-custom-container": container ? 'true' : 'false', "data-drawer-sheet-animate": shouldAnimate?.current ? 'true' : 'false', "data-state": isOpen ? 'open' : 'closed', style: {
623
+ ...positionStyles,
624
+ ...(snapPointsOffset && snapPointsOffset.length > 0
625
+ ? { '--snap-point-height': `${snapPointsOffset[activeSnapPointIndex ?? 0]}px` }
626
+ : {}),
627
+ ...style,
628
+ }, onPointerDown: (event) => {
629
+ if (handleOnly)
630
+ return;
631
+ rest.onPointerDown?.(event);
632
+ pointerStartRef.current = { x: event.pageX, y: event.pageY };
633
+ onPress(event);
634
+ }, onPointerMove: (event) => {
635
+ lastKnownPointerEventRef.current = event;
636
+ if (handleOnly)
637
+ return;
638
+ rest.onPointerMove?.(event);
639
+ if (!pointerStartRef.current)
640
+ return;
641
+ const yPosition = event.pageY - pointerStartRef.current.y;
642
+ const xPosition = event.pageX - pointerStartRef.current.x;
643
+ const swipeStartThreshold = event.pointerType === 'touch' ? 10 : 2;
644
+ const delta = { x: xPosition, y: yPosition };
645
+ const isAllowedToSwipe = isDeltaInDirection(delta, direction, swipeStartThreshold);
646
+ if (isAllowedToSwipe)
647
+ onDrag(event);
648
+ else if (Math.abs(xPosition) > swipeStartThreshold || Math.abs(yPosition) > swipeStartThreshold) {
649
+ pointerStartRef.current = null;
650
+ }
651
+ }, onPointerUp: (event) => {
652
+ rest.onPointerUp?.(event);
653
+ pointerStartRef.current = null;
654
+ wasBeyondThePointRef.current = false;
655
+ onRelease(event);
656
+ }, onPointerOut: () => handleOnPointerUp(lastKnownPointerEventRef.current), onContextMenu: () => {
657
+ if (lastKnownPointerEventRef.current)
658
+ handleOnPointerUp(lastKnownPointerEventRef.current);
659
+ }, ...rest }));
660
+ });
661
+ Content.displayName = 'DrawerSheet.Content';
662
+ const LONG_HANDLE_PRESS_TIMEOUT = 250;
663
+ const DOUBLE_TAP_TIMEOUT = 120;
664
+ export const Handle = React.forwardRef(function ({ preventCycle = false, children, ...rest }, ref) {
665
+ const { closeDrawer, isDragging, snapPoints, activeSnapPoint, setActiveSnapPoint, dismissible, handleOnly, isOpen, onPress, onDrag, } = useDrawerContext();
666
+ const closeTimeoutIdRef = React.useRef(null);
667
+ const shouldCancelInteractionRef = React.useRef(false);
668
+ function handleStartCycle() {
669
+ // Stop if this is the second click of a double click
670
+ if (shouldCancelInteractionRef.current) {
671
+ handleCancelInteraction();
672
+ return;
673
+ }
674
+ window.setTimeout(() => {
675
+ handleCycleSnapPoints();
676
+ }, DOUBLE_TAP_TIMEOUT);
677
+ }
678
+ function handleCycleSnapPoints() {
679
+ // Prevent accidental taps while resizing drawer
680
+ if (isDragging || preventCycle || shouldCancelInteractionRef.current) {
681
+ handleCancelInteraction();
682
+ return;
683
+ }
684
+ // Make sure to clear the timeout id if the user releases the handle before the cancel timeout
685
+ handleCancelInteraction();
686
+ if (!snapPoints || snapPoints.length === 0) {
687
+ if (!dismissible) {
688
+ closeDrawer();
689
+ }
690
+ return;
691
+ }
692
+ const isLastSnapPoint = activeSnapPoint === snapPoints[snapPoints.length - 1];
693
+ if (isLastSnapPoint && dismissible) {
694
+ closeDrawer();
695
+ return;
696
+ }
697
+ const currentSnapIndex = snapPoints.findIndex((point) => point === activeSnapPoint);
698
+ if (currentSnapIndex === -1)
699
+ return; // activeSnapPoint not found in snapPoints
700
+ const nextSnapPoint = snapPoints[currentSnapIndex + 1];
701
+ setActiveSnapPoint(nextSnapPoint);
702
+ }
703
+ function handleStartInteraction() {
704
+ closeTimeoutIdRef.current = window.setTimeout(() => {
705
+ // Cancel click interaction on a long press
706
+ shouldCancelInteractionRef.current = true;
707
+ }, LONG_HANDLE_PRESS_TIMEOUT);
708
+ }
709
+ function handleCancelInteraction() {
710
+ if (closeTimeoutIdRef.current) {
711
+ window.clearTimeout(closeTimeoutIdRef.current);
712
+ }
713
+ shouldCancelInteractionRef.current = false;
714
+ }
715
+ return (_jsx("div", { onClick: handleStartCycle, onPointerCancel: handleCancelInteraction, onPointerDown: (e) => {
716
+ if (handleOnly)
717
+ onPress(e);
718
+ handleStartInteraction();
719
+ }, onPointerMove: (e) => {
720
+ if (handleOnly)
721
+ onDrag(e);
722
+ },
723
+ // onPointerUp is already handled by the content component
724
+ ref: ref, "data-drawer-sheet-handle": "", "aria-hidden": "true", ...rest, children: _jsx("span", { "data-drawer-sheet-handle-hitarea": "", "aria-hidden": "true", children: children }) }));
725
+ });
726
+ Handle.displayName = 'DrawerSheet.Handle';
727
+ export function NestedRoot({ onDrag, onOpenChange, open: nestedIsOpen, ...rest }) {
728
+ const { onNestedDrag, onNestedOpenChange, onNestedRelease } = useDrawerContext();
729
+ if (!onNestedDrag) {
730
+ throw new Error('DrawerSheet.NestedRoot must be placed in another drawer');
731
+ }
732
+ return (_jsx(Root, { nested: true, open: nestedIsOpen, onClose: () => {
733
+ onNestedOpenChange(false);
734
+ }, onDrag: (e, p) => {
735
+ onNestedDrag(e, p);
736
+ onDrag?.(e, p);
737
+ }, onOpenChange: (o) => {
738
+ if (o) {
739
+ onNestedOpenChange(o);
740
+ }
741
+ onOpenChange?.(o);
742
+ }, onRelease: onNestedRelease, ...rest }));
743
+ }
744
+ export function Portal({ children, container }) {
745
+ const context = useDrawerContext();
746
+ const target = container ?? context.container ?? document.body;
747
+ const isMounted = useMounted();
748
+ const [shouldRender, setShouldRender] = React.useState(context.isOpen);
749
+ React.useEffect(() => {
750
+ if (context.isOpen) {
751
+ setShouldRender(true);
752
+ }
753
+ else {
754
+ const timer = setTimeout(() => setShouldRender(false), 500);
755
+ return () => clearTimeout(timer);
756
+ }
757
+ }, [context.isOpen]);
758
+ if (!isMounted || !shouldRender)
759
+ return null;
760
+ return createPortal(_jsx(_Fragment, { children: children }), target);
761
+ }
762
+ function Trigger({ children, asChild, ...props }) {
763
+ const { onOpenChange } = useDrawerContext();
764
+ const handleClick = () => onOpenChange?.(true);
765
+ if (asChild && React.isValidElement(children)) {
766
+ const child = children;
767
+ return React.cloneElement(child, {
768
+ onClick: (e) => {
769
+ child.props.onClick?.(e);
770
+ handleClick();
771
+ },
772
+ });
773
+ }
774
+ return (_jsx("button", { type: "button", onClick: handleClick, ...props, children: children }));
775
+ }
776
+ function Close({ children, asChild, ...props }) {
777
+ const { closeDrawer } = useDrawerContext();
778
+ const handleClick = () => closeDrawer(false);
779
+ if (asChild && React.isValidElement(children)) {
780
+ const child = children;
781
+ return React.cloneElement(child, {
782
+ onClick: (e) => {
783
+ child.props.onClick?.(e);
784
+ handleClick();
785
+ },
786
+ });
787
+ }
788
+ return (_jsx("button", { type: "button", onClick: handleClick, ...props, children: children }));
789
+ }
790
+ const Title = React.forwardRef((props, ref) => _jsx("h2", { ref: ref, ...props }));
791
+ const Description = React.forwardRef((props, ref) => _jsx("p", { ref: ref, ...props }));
792
+ export const DrawerSheet = {
793
+ Root,
794
+ NestedRoot,
795
+ Content,
796
+ Overlay,
797
+ Trigger,
798
+ Portal,
799
+ Handle,
800
+ Close,
801
+ Title,
802
+ Description,
803
+ };