base-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/dist/index.js ADDED
@@ -0,0 +1,1668 @@
1
+ 'use client';
2
+ function __insertCSS(code) {
3
+ if (!code || typeof document == 'undefined') return
4
+ let head = document.head || document.getElementsByTagName('head')[0]
5
+ let style = document.createElement('style')
6
+ style.type = 'text/css'
7
+ head.appendChild(style)
8
+ ;style.styleSheet ? (style.styleSheet.cssText = code) : style.appendChild(document.createTextNode(code))
9
+ }
10
+
11
+ Object.defineProperty(exports, '__esModule', { value: true });
12
+
13
+ var react = require('@base-ui/react');
14
+ var React = require('react');
15
+
16
+ function _interopNamespace(e) {
17
+ if (e && e.__esModule) return e;
18
+ var n = Object.create(null);
19
+ if (e) {
20
+ Object.keys(e).forEach(function (k) {
21
+ if (k !== 'default') {
22
+ var d = Object.getOwnPropertyDescriptor(e, k);
23
+ Object.defineProperty(n, k, d.get ? d : {
24
+ enumerable: true,
25
+ get: function () { return e[k]; }
26
+ });
27
+ }
28
+ });
29
+ }
30
+ n.default = e;
31
+ return n;
32
+ }
33
+
34
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
35
+
36
+ const DrawerContext = React__namespace.default.createContext({
37
+ drawerRef: {
38
+ current: null
39
+ },
40
+ overlayRef: {
41
+ current: null
42
+ },
43
+ onPress: ()=>{},
44
+ onRelease: ()=>{},
45
+ onDrag: ()=>{},
46
+ onNestedDrag: ()=>{},
47
+ onNestedOpenChange: ()=>{},
48
+ onNestedRelease: ()=>{},
49
+ openProp: undefined,
50
+ dismissible: false,
51
+ isOpen: false,
52
+ isDragging: false,
53
+ keyboardIsOpen: {
54
+ current: false
55
+ },
56
+ snapPointsOffset: null,
57
+ snapPoints: null,
58
+ handleOnly: false,
59
+ modal: false,
60
+ shouldFade: false,
61
+ activeSnapPoint: null,
62
+ onOpenChange: ()=>{},
63
+ setActiveSnapPoint: ()=>{},
64
+ closeDrawer: ()=>{},
65
+ direction: 'bottom',
66
+ shouldAnimate: {
67
+ current: true
68
+ },
69
+ shouldScaleBackground: false,
70
+ setBackgroundColorOnScale: true,
71
+ noBodyStyles: false,
72
+ container: null,
73
+ autoFocus: false
74
+ });
75
+ const useDrawerContext = ()=>{
76
+ const context = React__namespace.default.useContext(DrawerContext);
77
+ if (!context) {
78
+ throw new Error('useDrawerContext must be used within a Drawer.Root');
79
+ }
80
+ return context;
81
+ };
82
+
83
+ __insertCSS("[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-open]{animation-name:fadeIn}[data-vaul-overlay][data-closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not([data-closed]){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}");
84
+
85
+ function isMobileFirefox() {
86
+ const userAgent = navigator.userAgent;
87
+ return typeof window !== 'undefined' && (/Firefox/.test(userAgent) && /Mobile/.test(userAgent) || // Android Firefox
88
+ /FxiOS/.test(userAgent) // iOS Firefox
89
+ );
90
+ }
91
+ function isMac() {
92
+ return testPlatform(/^Mac/);
93
+ }
94
+ function isIPhone() {
95
+ return testPlatform(/^iPhone/);
96
+ }
97
+ function isSafari() {
98
+ return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
99
+ }
100
+ function isIPad() {
101
+ return testPlatform(/^iPad/) || // iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.
102
+ isMac() && navigator.maxTouchPoints > 1;
103
+ }
104
+ function isIOS() {
105
+ return isIPhone() || isIPad();
106
+ }
107
+ function testPlatform(re) {
108
+ return typeof window !== 'undefined' && window.navigator != null ? re.test(window.navigator.platform) : undefined;
109
+ }
110
+
111
+ // This code comes from https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/overlays/src/usePreventScroll.ts
112
+ const KEYBOARD_BUFFER = 24;
113
+ const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
114
+ function chain$1(...callbacks) {
115
+ return (...args)=>{
116
+ for (let callback of callbacks){
117
+ if (typeof callback === 'function') {
118
+ callback(...args);
119
+ }
120
+ }
121
+ };
122
+ }
123
+ // @ts-ignore
124
+ const visualViewport = typeof document !== 'undefined' && window.visualViewport;
125
+ function isScrollable(node) {
126
+ let style = window.getComputedStyle(node);
127
+ return /(auto|scroll)/.test(style.overflow + style.overflowX + style.overflowY);
128
+ }
129
+ function getScrollParent(node) {
130
+ if (isScrollable(node)) {
131
+ node = node.parentElement;
132
+ }
133
+ while(node && !isScrollable(node)){
134
+ node = node.parentElement;
135
+ }
136
+ return node || document.scrollingElement || document.documentElement;
137
+ }
138
+ // HTML input types that do not cause the software keyboard to appear.
139
+ const nonTextInputTypes = new Set([
140
+ 'checkbox',
141
+ 'radio',
142
+ 'range',
143
+ 'color',
144
+ 'file',
145
+ 'image',
146
+ 'button',
147
+ 'submit',
148
+ 'reset'
149
+ ]);
150
+ // The number of active usePreventScroll calls. Used to determine whether to revert back to the original page style/scroll position
151
+ let preventScrollCount = 0;
152
+ let restore;
153
+ /**
154
+ * Prevents scrolling on the document body on mount, and
155
+ * restores it on unmount. Also ensures that content does not
156
+ * shift due to the scrollbars disappearing.
157
+ */ function usePreventScroll(options = {}) {
158
+ let { isDisabled } = options;
159
+ useIsomorphicLayoutEffect(()=>{
160
+ if (isDisabled) {
161
+ return;
162
+ }
163
+ preventScrollCount++;
164
+ if (preventScrollCount === 1) {
165
+ if (isIOS()) {
166
+ restore = preventScrollMobileSafari();
167
+ }
168
+ }
169
+ return ()=>{
170
+ preventScrollCount--;
171
+ if (preventScrollCount === 0) {
172
+ restore == null ? void 0 : restore();
173
+ }
174
+ };
175
+ }, [
176
+ isDisabled
177
+ ]);
178
+ }
179
+ // Mobile Safari is a whole different beast. Even with overflow: hidden,
180
+ // it still scrolls the page in many situations:
181
+ //
182
+ // 1. When the bottom toolbar and address bar are collapsed, page scrolling is always allowed.
183
+ // 2. When the keyboard is visible, the viewport does not resize. Instead, the keyboard covers part of
184
+ // it, so it becomes scrollable.
185
+ // 3. When tapping on an input, the page always scrolls so that the input is centered in the visual viewport.
186
+ // This may cause even fixed position elements to scroll off the screen.
187
+ // 4. When using the next/previous buttons in the keyboard to navigate between inputs, the whole page always
188
+ // scrolls, even if the input is inside a nested scrollable element that could be scrolled instead.
189
+ //
190
+ // In order to work around these cases, and prevent scrolling without jankiness, we do a few things:
191
+ //
192
+ // 1. Prevent default on `touchmove` events that are not in a scrollable element. This prevents touch scrolling
193
+ // on the window.
194
+ // 2. Prevent default on `touchmove` events inside a scrollable element when the scroll position is at the
195
+ // top or bottom. This avoids the whole page scrolling instead, but does prevent overscrolling.
196
+ // 3. Prevent default on `touchend` events on input elements and handle focusing the element ourselves.
197
+ // 4. When focusing an input, apply a transform to trick Safari into thinking the input is at the top
198
+ // of the page, which prevents it from scrolling the page. After the input is focused, scroll the element
199
+ // into view ourselves, without scrolling the whole page.
200
+ // 5. Offset the body by the scroll position using a negative margin and scroll to the top. This should appear the
201
+ // same visually, but makes the actual scroll position always zero. This is required to make all of the
202
+ // above work or Safari will still try to scroll the page when focusing an input.
203
+ // 6. As a last resort, handle window scroll events, and scroll back to the top. This can happen when attempting
204
+ // to navigate to an input with the next/previous buttons that's outside a modal.
205
+ function preventScrollMobileSafari() {
206
+ let scrollable;
207
+ let lastY = 0;
208
+ let onTouchStart = (e)=>{
209
+ // Store the nearest scrollable parent element from the element that the user touched.
210
+ scrollable = getScrollParent(e.target);
211
+ if (scrollable === document.documentElement && scrollable === document.body) {
212
+ return;
213
+ }
214
+ lastY = e.changedTouches[0].pageY;
215
+ };
216
+ let onTouchMove = (e)=>{
217
+ // Prevent scrolling the window.
218
+ if (!scrollable || scrollable === document.documentElement || scrollable === document.body) {
219
+ e.preventDefault();
220
+ return;
221
+ }
222
+ // Prevent scrolling up when at the top and scrolling down when at the bottom
223
+ // of a nested scrollable area, otherwise mobile Safari will start scrolling
224
+ // the window instead. Unfortunately, this disables bounce scrolling when at
225
+ // the top but it's the best we can do.
226
+ let y = e.changedTouches[0].pageY;
227
+ let scrollTop = scrollable.scrollTop;
228
+ let bottom = scrollable.scrollHeight - scrollable.clientHeight;
229
+ if (bottom === 0) {
230
+ return;
231
+ }
232
+ if (scrollTop <= 0 && y > lastY || scrollTop >= bottom && y < lastY) {
233
+ e.preventDefault();
234
+ }
235
+ lastY = y;
236
+ };
237
+ let onTouchEnd = (e)=>{
238
+ let target = e.target;
239
+ // Apply this change if we're not already focused on the target element
240
+ if (isInput(target) && target !== document.activeElement) {
241
+ e.preventDefault();
242
+ // Apply a transform to trick Safari into thinking the input is at the top of the page
243
+ // so it doesn't try to scroll it into view. When tapping on an input, this needs to
244
+ // be done before the "focus" event, so we have to focus the element ourselves.
245
+ target.style.transform = 'translateY(-2000px)';
246
+ target.focus();
247
+ requestAnimationFrame(()=>{
248
+ target.style.transform = '';
249
+ });
250
+ }
251
+ };
252
+ let onFocus = (e)=>{
253
+ let target = e.target;
254
+ if (isInput(target)) {
255
+ // Transform also needs to be applied in the focus event in cases where focus moves
256
+ // other than tapping on an input directly, e.g. the next/previous buttons in the
257
+ // software keyboard. In these cases, it seems applying the transform in the focus event
258
+ // is good enough, whereas when tapping an input, it must be done before the focus event. 🤷‍♂️
259
+ target.style.transform = 'translateY(-2000px)';
260
+ requestAnimationFrame(()=>{
261
+ target.style.transform = '';
262
+ // This will have prevented the browser from scrolling the focused element into view,
263
+ // so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
264
+ if (visualViewport) {
265
+ if (visualViewport.height < window.innerHeight) {
266
+ // If the keyboard is already visible, do this after one additional frame
267
+ // to wait for the transform to be removed.
268
+ requestAnimationFrame(()=>{
269
+ scrollIntoView(target);
270
+ });
271
+ } else {
272
+ // Otherwise, wait for the visual viewport to resize before scrolling so we can
273
+ // measure the correct position to scroll to.
274
+ visualViewport.addEventListener('resize', ()=>scrollIntoView(target), {
275
+ once: true
276
+ });
277
+ }
278
+ }
279
+ });
280
+ }
281
+ };
282
+ let onWindowScroll = ()=>{
283
+ // Last resort. If the window scrolled, scroll it back to the top.
284
+ // It should always be at the top because the body will have a negative margin (see below).
285
+ window.scrollTo(0, 0);
286
+ };
287
+ // Record the original scroll position so we can restore it.
288
+ // Then apply a negative margin to the body to offset it by the scroll position. This will
289
+ // enable us to scroll the window to the top, which is required for the rest of this to work.
290
+ let scrollX = window.pageXOffset;
291
+ let scrollY = window.pageYOffset;
292
+ let restoreStyles = chain$1(setStyle(document.documentElement, 'paddingRight', `${window.innerWidth - document.documentElement.clientWidth}px`));
293
+ // Scroll to the top. The negative margin on the body will make this appear the same.
294
+ window.scrollTo(0, 0);
295
+ let removeEvents = chain$1(addEvent(document, 'touchstart', onTouchStart, {
296
+ passive: false,
297
+ capture: true
298
+ }), addEvent(document, 'touchmove', onTouchMove, {
299
+ passive: false,
300
+ capture: true
301
+ }), addEvent(document, 'touchend', onTouchEnd, {
302
+ passive: false,
303
+ capture: true
304
+ }), addEvent(document, 'focus', onFocus, true), addEvent(window, 'scroll', onWindowScroll));
305
+ return ()=>{
306
+ // Restore styles and scroll the page back to where it was.
307
+ restoreStyles();
308
+ removeEvents();
309
+ window.scrollTo(scrollX, scrollY);
310
+ };
311
+ }
312
+ // Sets a CSS property on an element, and returns a function to revert it to the previous value.
313
+ function setStyle(element, style, value) {
314
+ // https://github.com/microsoft/TypeScript/issues/17827#issuecomment-391663310
315
+ // @ts-ignore
316
+ let cur = element.style[style];
317
+ // @ts-ignore
318
+ element.style[style] = value;
319
+ return ()=>{
320
+ // @ts-ignore
321
+ element.style[style] = cur;
322
+ };
323
+ }
324
+ // Adds an event listener to an element, and returns a function to remove it.
325
+ function addEvent(target, event, handler, options) {
326
+ // @ts-ignore
327
+ target.addEventListener(event, handler, options);
328
+ return ()=>{
329
+ // @ts-ignore
330
+ target.removeEventListener(event, handler, options);
331
+ };
332
+ }
333
+ function scrollIntoView(target) {
334
+ let root = document.scrollingElement || document.documentElement;
335
+ while(target && target !== root){
336
+ // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
337
+ let scrollable = getScrollParent(target);
338
+ if (scrollable !== document.documentElement && scrollable !== document.body && scrollable !== target) {
339
+ let scrollableTop = scrollable.getBoundingClientRect().top;
340
+ let targetTop = target.getBoundingClientRect().top;
341
+ let targetBottom = target.getBoundingClientRect().bottom;
342
+ // Buffer is needed for some edge cases
343
+ const keyboardHeight = scrollable.getBoundingClientRect().bottom + KEYBOARD_BUFFER;
344
+ if (targetBottom > keyboardHeight) {
345
+ scrollable.scrollTop += targetTop - scrollableTop;
346
+ }
347
+ }
348
+ // @ts-ignore
349
+ target = scrollable.parentElement;
350
+ }
351
+ }
352
+ function isInput(target) {
353
+ return target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable;
354
+ }
355
+
356
+ // This code comes from https://github.com/radix-ui/primitives/tree/main/packages/react/compose-refs
357
+ /**
358
+ * Set a given ref to a given value
359
+ * This utility takes care of different types of refs: callback refs and RefObject(s)
360
+ */ function setRef(ref, value) {
361
+ if (typeof ref === 'function') {
362
+ ref(value);
363
+ } else if (ref !== null && ref !== undefined) {
364
+ ref.current = value;
365
+ }
366
+ }
367
+ /**
368
+ * A utility to compose multiple refs together
369
+ * Accepts callback refs and RefObject(s)
370
+ */ function composeRefs(...refs) {
371
+ return (node)=>refs.forEach((ref)=>setRef(ref, node));
372
+ }
373
+ /**
374
+ * A custom hook that composes multiple refs
375
+ * Accepts callback refs and RefObject(s)
376
+ */ function useComposedRefs(...refs) {
377
+ // eslint-disable-next-line react-hooks/exhaustive-deps
378
+ return React__namespace.useCallback(composeRefs(...refs), refs);
379
+ }
380
+
381
+ const cache = new WeakMap();
382
+ function set(el, styles, ignoreCache = false) {
383
+ if (!el || !(el instanceof HTMLElement)) return;
384
+ let originalStyles = {};
385
+ Object.entries(styles).forEach(([key, value])=>{
386
+ if (key.startsWith('--')) {
387
+ el.style.setProperty(key, value);
388
+ return;
389
+ }
390
+ originalStyles[key] = el.style[key];
391
+ el.style[key] = value;
392
+ });
393
+ if (ignoreCache) return;
394
+ cache.set(el, originalStyles);
395
+ }
396
+ function reset(el, prop) {
397
+ if (!el || !(el instanceof HTMLElement)) return;
398
+ let originalStyles = cache.get(el);
399
+ if (!originalStyles) {
400
+ return;
401
+ }
402
+ {
403
+ el.style[prop] = originalStyles[prop];
404
+ }
405
+ }
406
+ const isVertical = (direction)=>{
407
+ switch(direction){
408
+ case 'top':
409
+ case 'bottom':
410
+ return true;
411
+ case 'left':
412
+ case 'right':
413
+ return false;
414
+ default:
415
+ return direction;
416
+ }
417
+ };
418
+ function getTranslate(element, direction) {
419
+ if (!element) {
420
+ return null;
421
+ }
422
+ const style = window.getComputedStyle(element);
423
+ const transform = // @ts-ignore
424
+ style.transform || style.webkitTransform || style.mozTransform;
425
+ let mat = transform.match(/^matrix3d\((.+)\)$/);
426
+ if (mat) {
427
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix3d
428
+ return parseFloat(mat[1].split(', ')[isVertical(direction) ? 13 : 12]);
429
+ }
430
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix
431
+ mat = transform.match(/^matrix\((.+)\)$/);
432
+ return mat ? parseFloat(mat[1].split(', ')[isVertical(direction) ? 5 : 4]) : null;
433
+ }
434
+ function dampenValue(v) {
435
+ return 8 * (Math.log(v + 1) - 2);
436
+ }
437
+ function assignStyle(element, style) {
438
+ if (!element) return ()=>{};
439
+ const prevStyle = element.style.cssText;
440
+ Object.assign(element.style, style);
441
+ return ()=>{
442
+ element.style.cssText = prevStyle;
443
+ };
444
+ }
445
+ /**
446
+ * Receives functions as arguments and returns a new function that calls all.
447
+ */ function chain(...fns) {
448
+ return (...args)=>{
449
+ for (const fn of fns){
450
+ if (typeof fn === 'function') {
451
+ // @ts-ignore
452
+ fn(...args);
453
+ }
454
+ }
455
+ };
456
+ }
457
+
458
+ const TRANSITIONS = {
459
+ DURATION: 0.5,
460
+ EASE: [
461
+ 0.32,
462
+ 0.72,
463
+ 0,
464
+ 1
465
+ ]
466
+ };
467
+ const VELOCITY_THRESHOLD = 0.4;
468
+ const CLOSE_THRESHOLD = 0.25;
469
+ const SCROLL_LOCK_TIMEOUT = 100;
470
+ const BORDER_RADIUS = 8;
471
+ const NESTED_DISPLACEMENT = 16;
472
+ const WINDOW_TOP_OFFSET = 26;
473
+ const DRAG_CLASS = 'vaul-dragging';
474
+
475
+ // This code comes from https://github.com/radix-ui/primitives/blob/main/packages/react/use-controllable-state/src/useControllableState.tsx
476
+ function useCallbackRef(callback) {
477
+ const callbackRef = React__namespace.default.useRef(callback);
478
+ React__namespace.default.useEffect(()=>{
479
+ callbackRef.current = callback;
480
+ });
481
+ // https://github.com/facebook/react/issues/19240
482
+ return React__namespace.default.useMemo(()=>(...args)=>callbackRef.current == null ? void 0 : callbackRef.current.call(callbackRef, ...args), []);
483
+ }
484
+ function useUncontrolledState({ defaultProp, onChange }) {
485
+ const uncontrolledState = React__namespace.default.useState(defaultProp);
486
+ const [value] = uncontrolledState;
487
+ const prevValueRef = React__namespace.default.useRef(value);
488
+ const handleChange = useCallbackRef(onChange);
489
+ React__namespace.default.useEffect(()=>{
490
+ if (prevValueRef.current !== value) {
491
+ handleChange(value);
492
+ prevValueRef.current = value;
493
+ }
494
+ }, [
495
+ value,
496
+ prevValueRef,
497
+ handleChange
498
+ ]);
499
+ return uncontrolledState;
500
+ }
501
+ function useControllableState({ prop, defaultProp, onChange = ()=>{} }) {
502
+ const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({
503
+ defaultProp,
504
+ onChange
505
+ });
506
+ const isControlled = prop !== undefined;
507
+ const value = isControlled ? prop : uncontrolledProp;
508
+ const handleChange = useCallbackRef(onChange);
509
+ const setValue = React__namespace.default.useCallback((nextValue)=>{
510
+ if (isControlled) {
511
+ const setter = nextValue;
512
+ const value = typeof nextValue === 'function' ? setter(prop) : nextValue;
513
+ if (value !== prop) handleChange(value);
514
+ } else {
515
+ setUncontrolledProp(nextValue);
516
+ }
517
+ }, [
518
+ isControlled,
519
+ prop,
520
+ setUncontrolledProp,
521
+ handleChange
522
+ ]);
523
+ return [
524
+ value,
525
+ setValue
526
+ ];
527
+ }
528
+
529
+ function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints, drawerRef, overlayRef, fadeFromIndex, onSnapPointChange, direction = 'bottom', container, snapToSequentialPoint }) {
530
+ const [activeSnapPoint, setActiveSnapPoint] = useControllableState({
531
+ prop: activeSnapPointProp,
532
+ defaultProp: snapPoints == null ? void 0 : snapPoints[0],
533
+ onChange: setActiveSnapPointProp
534
+ });
535
+ const [windowDimensions, setWindowDimensions] = React__namespace.default.useState(typeof window !== 'undefined' ? {
536
+ innerWidth: window.innerWidth,
537
+ innerHeight: window.innerHeight
538
+ } : undefined);
539
+ React__namespace.default.useEffect(()=>{
540
+ function onResize() {
541
+ setWindowDimensions({
542
+ innerWidth: window.innerWidth,
543
+ innerHeight: window.innerHeight
544
+ });
545
+ }
546
+ window.addEventListener('resize', onResize);
547
+ return ()=>window.removeEventListener('resize', onResize);
548
+ }, []);
549
+ const isLastSnapPoint = React__namespace.default.useMemo(()=>activeSnapPoint === (snapPoints == null ? void 0 : snapPoints[snapPoints.length - 1]) || null, [
550
+ snapPoints,
551
+ activeSnapPoint
552
+ ]);
553
+ const activeSnapPointIndex = React__namespace.default.useMemo(()=>{
554
+ var _snapPoints_findIndex;
555
+ return (_snapPoints_findIndex = snapPoints == null ? void 0 : snapPoints.findIndex((snapPoint)=>snapPoint === activeSnapPoint)) != null ? _snapPoints_findIndex : null;
556
+ }, [
557
+ snapPoints,
558
+ activeSnapPoint
559
+ ]);
560
+ const shouldFade = snapPoints && snapPoints.length > 0 && (fadeFromIndex || fadeFromIndex === 0) && !Number.isNaN(fadeFromIndex) && snapPoints[fadeFromIndex] === activeSnapPoint || !snapPoints;
561
+ const snapPointsOffset = React__namespace.default.useMemo(()=>{
562
+ const containerSize = container ? {
563
+ width: container.getBoundingClientRect().width,
564
+ height: container.getBoundingClientRect().height
565
+ } : typeof window !== 'undefined' ? {
566
+ width: window.innerWidth,
567
+ height: window.innerHeight
568
+ } : {
569
+ width: 0,
570
+ height: 0
571
+ };
572
+ var _snapPoints_map;
573
+ return (_snapPoints_map = snapPoints == null ? void 0 : snapPoints.map((snapPoint)=>{
574
+ const isPx = typeof snapPoint === 'string';
575
+ let snapPointAsNumber = 0;
576
+ if (isPx) {
577
+ snapPointAsNumber = parseInt(snapPoint, 10);
578
+ }
579
+ if (isVertical(direction)) {
580
+ const height = isPx ? snapPointAsNumber : windowDimensions ? snapPoint * containerSize.height : 0;
581
+ if (windowDimensions) {
582
+ return direction === 'bottom' ? containerSize.height - height : -containerSize.height + height;
583
+ }
584
+ return height;
585
+ }
586
+ const width = isPx ? snapPointAsNumber : windowDimensions ? snapPoint * containerSize.width : 0;
587
+ if (windowDimensions) {
588
+ return direction === 'right' ? containerSize.width - width : -containerSize.width + width;
589
+ }
590
+ return width;
591
+ })) != null ? _snapPoints_map : [];
592
+ }, [
593
+ snapPoints,
594
+ windowDimensions,
595
+ container
596
+ ]);
597
+ const activeSnapPointOffset = React__namespace.default.useMemo(()=>activeSnapPointIndex !== null ? snapPointsOffset == null ? void 0 : snapPointsOffset[activeSnapPointIndex] : null, [
598
+ snapPointsOffset,
599
+ activeSnapPointIndex
600
+ ]);
601
+ const snapToPoint = React__namespace.default.useCallback((dimension)=>{
602
+ var _snapPointsOffset_findIndex;
603
+ const newSnapPointIndex = (_snapPointsOffset_findIndex = snapPointsOffset == null ? void 0 : snapPointsOffset.findIndex((snapPointDim)=>snapPointDim === dimension)) != null ? _snapPointsOffset_findIndex : null;
604
+ onSnapPointChange(newSnapPointIndex);
605
+ set(drawerRef.current, {
606
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
607
+ transform: isVertical(direction) ? `translate3d(0, ${dimension}px, 0)` : `translate3d(${dimension}px, 0, 0)`
608
+ });
609
+ if (snapPointsOffset && newSnapPointIndex !== snapPointsOffset.length - 1 && fadeFromIndex !== undefined && newSnapPointIndex !== fadeFromIndex && newSnapPointIndex < fadeFromIndex) {
610
+ set(overlayRef.current, {
611
+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
612
+ opacity: '0'
613
+ });
614
+ } else {
615
+ set(overlayRef.current, {
616
+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
617
+ opacity: '1'
618
+ });
619
+ }
620
+ setActiveSnapPoint(snapPoints == null ? void 0 : snapPoints[Math.max(newSnapPointIndex, 0)]);
621
+ }, [
622
+ drawerRef.current,
623
+ snapPoints,
624
+ snapPointsOffset,
625
+ fadeFromIndex,
626
+ overlayRef,
627
+ setActiveSnapPoint
628
+ ]);
629
+ React__namespace.default.useEffect(()=>{
630
+ if (activeSnapPoint || activeSnapPointProp) {
631
+ var _snapPoints_findIndex;
632
+ const newIndex = (_snapPoints_findIndex = snapPoints == null ? void 0 : snapPoints.findIndex((snapPoint)=>snapPoint === activeSnapPointProp || snapPoint === activeSnapPoint)) != null ? _snapPoints_findIndex : -1;
633
+ if (snapPointsOffset && newIndex !== -1 && typeof snapPointsOffset[newIndex] === 'number') {
634
+ snapToPoint(snapPointsOffset[newIndex]);
635
+ }
636
+ }
637
+ }, [
638
+ activeSnapPoint,
639
+ activeSnapPointProp,
640
+ snapPoints,
641
+ snapPointsOffset,
642
+ snapToPoint
643
+ ]);
644
+ function onRelease({ draggedDistance, closeDrawer, velocity, dismissible }) {
645
+ if (fadeFromIndex === undefined) return;
646
+ const currentPosition = direction === 'bottom' || direction === 'right' ? (activeSnapPointOffset != null ? activeSnapPointOffset : 0) - draggedDistance : (activeSnapPointOffset != null ? activeSnapPointOffset : 0) + draggedDistance;
647
+ const isOverlaySnapPoint = activeSnapPointIndex === fadeFromIndex - 1;
648
+ const isFirst = activeSnapPointIndex === 0;
649
+ const hasDraggedUp = draggedDistance > 0;
650
+ if (isOverlaySnapPoint) {
651
+ set(overlayRef.current, {
652
+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`
653
+ });
654
+ }
655
+ if (!snapToSequentialPoint && velocity > 2 && !hasDraggedUp) {
656
+ if (dismissible) closeDrawer();
657
+ else snapToPoint(snapPointsOffset[0]); // snap to initial point
658
+ return;
659
+ }
660
+ if (!snapToSequentialPoint && velocity > 2 && hasDraggedUp && snapPointsOffset && snapPoints) {
661
+ snapToPoint(snapPointsOffset[snapPoints.length - 1]);
662
+ return;
663
+ }
664
+ // Find the closest snap point to the current position
665
+ const closestSnapPoint = snapPointsOffset == null ? void 0 : snapPointsOffset.reduce((prev, curr)=>{
666
+ if (typeof prev !== 'number' || typeof curr !== 'number') return prev;
667
+ return Math.abs(curr - currentPosition) < Math.abs(prev - currentPosition) ? curr : prev;
668
+ });
669
+ const dim = isVertical(direction) ? window.innerHeight : window.innerWidth;
670
+ if (velocity > VELOCITY_THRESHOLD && Math.abs(draggedDistance) < dim * 0.4) {
671
+ const dragDirection = hasDraggedUp ? 1 : -1; // 1 = up, -1 = down
672
+ // Don't do anything if we swipe upwards while being on the last snap point
673
+ if (dragDirection > 0 && isLastSnapPoint && snapPoints) {
674
+ snapToPoint(snapPointsOffset[snapPoints.length - 1]);
675
+ return;
676
+ }
677
+ if (isFirst && dragDirection < 0 && dismissible) {
678
+ closeDrawer();
679
+ }
680
+ if (activeSnapPointIndex === null) return;
681
+ snapToPoint(snapPointsOffset[activeSnapPointIndex + dragDirection]);
682
+ return;
683
+ }
684
+ snapToPoint(closestSnapPoint);
685
+ }
686
+ function onDrag({ draggedDistance }) {
687
+ if (activeSnapPointOffset === null) return;
688
+ const newValue = direction === 'bottom' || direction === 'right' ? activeSnapPointOffset - draggedDistance : activeSnapPointOffset + draggedDistance;
689
+ // Don't do anything if we exceed the last(biggest) snap point
690
+ if ((direction === 'bottom' || direction === 'right') && newValue < snapPointsOffset[snapPointsOffset.length - 1]) {
691
+ return;
692
+ }
693
+ if ((direction === 'top' || direction === 'left') && newValue > snapPointsOffset[snapPointsOffset.length - 1]) {
694
+ return;
695
+ }
696
+ set(drawerRef.current, {
697
+ transform: isVertical(direction) ? `translate3d(0, ${newValue}px, 0)` : `translate3d(${newValue}px, 0, 0)`
698
+ });
699
+ }
700
+ function getPercentageDragged(absDraggedDistance, isDraggingDown) {
701
+ if (!snapPoints || typeof activeSnapPointIndex !== 'number' || !snapPointsOffset || fadeFromIndex === undefined) return null;
702
+ // If this is true we are dragging to a snap point that is supposed to have an overlay
703
+ const isOverlaySnapPoint = activeSnapPointIndex === fadeFromIndex - 1;
704
+ const isOverlaySnapPointOrHigher = activeSnapPointIndex >= fadeFromIndex;
705
+ if (isOverlaySnapPointOrHigher && isDraggingDown) {
706
+ return 0;
707
+ }
708
+ // Don't animate, but still use this one if we are dragging away from the overlaySnapPoint
709
+ if (isOverlaySnapPoint && !isDraggingDown) return 1;
710
+ if (!shouldFade && !isOverlaySnapPoint) return null;
711
+ // Either fadeFrom index or the one before
712
+ const targetSnapPointIndex = isOverlaySnapPoint ? activeSnapPointIndex + 1 : activeSnapPointIndex - 1;
713
+ // Get the distance from overlaySnapPoint to the one before or vice-versa to calculate the opacity percentage accordingly
714
+ const snapPointDistance = isOverlaySnapPoint ? snapPointsOffset[targetSnapPointIndex] - snapPointsOffset[targetSnapPointIndex - 1] : snapPointsOffset[targetSnapPointIndex + 1] - snapPointsOffset[targetSnapPointIndex];
715
+ const percentageDragged = absDraggedDistance / Math.abs(snapPointDistance);
716
+ if (isOverlaySnapPoint) {
717
+ return 1 - percentageDragged;
718
+ } else {
719
+ return percentageDragged;
720
+ }
721
+ }
722
+ return {
723
+ isLastSnapPoint,
724
+ activeSnapPoint,
725
+ shouldFade,
726
+ getPercentageDragged,
727
+ setActiveSnapPoint,
728
+ activeSnapPointIndex,
729
+ onRelease,
730
+ onDrag,
731
+ snapPointsOffset
732
+ };
733
+ }
734
+
735
+ const noop = ()=>()=>{};
736
+ function useScaleBackground() {
737
+ const { direction, isOpen, shouldScaleBackground, setBackgroundColorOnScale, noBodyStyles } = useDrawerContext();
738
+ const timeoutIdRef = React__namespace.default.useRef(null);
739
+ const initialBackgroundColor = React.useMemo(()=>document.body.style.backgroundColor, []);
740
+ function getScale() {
741
+ return (window.innerWidth - WINDOW_TOP_OFFSET) / window.innerWidth;
742
+ }
743
+ React__namespace.default.useEffect(()=>{
744
+ if (isOpen && shouldScaleBackground) {
745
+ if (timeoutIdRef.current) clearTimeout(timeoutIdRef.current);
746
+ const wrapper = document.querySelector('[data-vaul-drawer-wrapper]') || document.querySelector('[vaul-drawer-wrapper]');
747
+ if (!wrapper) return;
748
+ chain(setBackgroundColorOnScale && !noBodyStyles ? assignStyle(document.body, {
749
+ background: 'black'
750
+ }) : noop, assignStyle(wrapper, {
751
+ transformOrigin: isVertical(direction) ? 'top' : 'left',
752
+ transitionProperty: 'transform, border-radius',
753
+ transitionDuration: `${TRANSITIONS.DURATION}s`,
754
+ transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`
755
+ }));
756
+ const wrapperStylesCleanup = assignStyle(wrapper, {
757
+ borderRadius: `${BORDER_RADIUS}px`,
758
+ overflow: 'hidden',
759
+ ...isVertical(direction) ? {
760
+ transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`
761
+ } : {
762
+ transform: `scale(${getScale()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`
763
+ }
764
+ });
765
+ return ()=>{
766
+ wrapperStylesCleanup();
767
+ timeoutIdRef.current = window.setTimeout(()=>{
768
+ if (initialBackgroundColor) {
769
+ document.body.style.background = initialBackgroundColor;
770
+ } else {
771
+ document.body.style.removeProperty('background');
772
+ }
773
+ }, TRANSITIONS.DURATION * 1000);
774
+ };
775
+ }
776
+ }, [
777
+ isOpen,
778
+ shouldScaleBackground,
779
+ initialBackgroundColor
780
+ ]);
781
+ }
782
+
783
+ let previousBodyPosition = null;
784
+ /**
785
+ * This hook is necessary to prevent buggy behavior on iOS devices (need to test on Android).
786
+ * I won't get into too much detail about what bugs it solves, but so far I've found that setting the body to `position: fixed` is the most reliable way to prevent those bugs.
787
+ * Issues that this hook solves:
788
+ * https://github.com/emilkowalski/vaul/issues/435
789
+ * https://github.com/emilkowalski/vaul/issues/433
790
+ * And more that I discovered, but were just not reported.
791
+ */ function usePositionFixed({ isOpen, modal, nested, hasBeenOpened, preventScrollRestoration, noBodyStyles }) {
792
+ const [activeUrl, setActiveUrl] = React__namespace.default.useState(()=>typeof window !== 'undefined' ? window.location.href : '');
793
+ const scrollPos = React__namespace.default.useRef(0);
794
+ const setPositionFixed = React__namespace.default.useCallback(()=>{
795
+ // All browsers on iOS will return true here.
796
+ if (!isSafari()) return;
797
+ // If previousBodyPosition is already set, don't set it again.
798
+ if (previousBodyPosition === null && isOpen && !noBodyStyles) {
799
+ previousBodyPosition = {
800
+ position: document.body.style.position,
801
+ top: document.body.style.top,
802
+ left: document.body.style.left,
803
+ height: document.body.style.height,
804
+ right: 'unset'
805
+ };
806
+ // Update the dom inside an animation frame
807
+ const { scrollX, innerHeight } = window;
808
+ document.body.style.setProperty('position', 'fixed', 'important');
809
+ Object.assign(document.body.style, {
810
+ top: `${-scrollPos.current}px`,
811
+ left: `${-scrollX}px`,
812
+ right: '0px',
813
+ height: 'auto'
814
+ });
815
+ window.setTimeout(()=>window.requestAnimationFrame(()=>{
816
+ // Attempt to check if the bottom bar appeared due to the position change
817
+ const bottomBarHeight = innerHeight - window.innerHeight;
818
+ if (bottomBarHeight && scrollPos.current >= innerHeight) {
819
+ // Move the content further up so that the bottom bar doesn't hide it
820
+ document.body.style.top = `${-(scrollPos.current + bottomBarHeight)}px`;
821
+ }
822
+ }), 300);
823
+ }
824
+ }, [
825
+ isOpen
826
+ ]);
827
+ const restorePositionSetting = React__namespace.default.useCallback(()=>{
828
+ // All browsers on iOS will return true here.
829
+ if (!isSafari()) return;
830
+ if (previousBodyPosition !== null && !noBodyStyles) {
831
+ // Convert the position from "px" to Int
832
+ const y = -parseInt(document.body.style.top, 10);
833
+ const x = -parseInt(document.body.style.left, 10);
834
+ // Restore styles
835
+ Object.assign(document.body.style, previousBodyPosition);
836
+ window.requestAnimationFrame(()=>{
837
+ if (preventScrollRestoration && activeUrl !== window.location.href) {
838
+ setActiveUrl(window.location.href);
839
+ return;
840
+ }
841
+ window.scrollTo(x, y);
842
+ });
843
+ previousBodyPosition = null;
844
+ }
845
+ }, [
846
+ activeUrl
847
+ ]);
848
+ React__namespace.default.useEffect(()=>{
849
+ function onScroll() {
850
+ scrollPos.current = window.scrollY;
851
+ }
852
+ onScroll();
853
+ window.addEventListener('scroll', onScroll);
854
+ return ()=>{
855
+ window.removeEventListener('scroll', onScroll);
856
+ };
857
+ }, []);
858
+ React__namespace.default.useEffect(()=>{
859
+ if (!modal) return;
860
+ return ()=>{
861
+ if (typeof document === 'undefined') return;
862
+ // Another drawer is opened, safe to ignore the execution
863
+ const hasDrawerOpened = !!document.querySelector('[data-vaul-drawer]');
864
+ if (hasDrawerOpened) return;
865
+ restorePositionSetting();
866
+ };
867
+ }, [
868
+ modal,
869
+ restorePositionSetting
870
+ ]);
871
+ React__namespace.default.useEffect(()=>{
872
+ if (nested || !hasBeenOpened) return;
873
+ // This is needed to force Safari toolbar to show **before** the drawer starts animating to prevent a gnarly shift from happening
874
+ if (isOpen) {
875
+ // avoid for standalone mode (PWA)
876
+ const isStandalone = window.matchMedia('(display-mode: standalone)').matches;
877
+ !isStandalone && setPositionFixed();
878
+ if (!modal) {
879
+ window.setTimeout(()=>{
880
+ restorePositionSetting();
881
+ }, 500);
882
+ }
883
+ } else {
884
+ restorePositionSetting();
885
+ }
886
+ }, [
887
+ isOpen,
888
+ hasBeenOpened,
889
+ activeUrl,
890
+ modal,
891
+ nested,
892
+ setPositionFixed,
893
+ restorePositionSetting
894
+ ]);
895
+ return {
896
+ restorePositionSetting
897
+ };
898
+ }
899
+
900
+ 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 }) {
901
+ var _drawerRef_current, _drawerRef_current1;
902
+ const [isOpen = false, setIsOpen] = useControllableState({
903
+ defaultProp: defaultOpen,
904
+ prop: openProp,
905
+ onChange: (o)=>{
906
+ onOpenChange == null ? void 0 : onOpenChange(o);
907
+ if (!o && !nested) {
908
+ restorePositionSetting();
909
+ }
910
+ setTimeout(()=>{
911
+ onAnimationEnd == null ? void 0 : onAnimationEnd(o);
912
+ }, TRANSITIONS.DURATION * 1000);
913
+ if (o && !modal) {
914
+ if (typeof window !== 'undefined') {
915
+ window.requestAnimationFrame(()=>{
916
+ document.body.style.pointerEvents = 'auto';
917
+ });
918
+ }
919
+ }
920
+ if (!o) {
921
+ // This will be removed when the exit animation ends (`500ms`)
922
+ document.body.style.pointerEvents = 'auto';
923
+ }
924
+ }
925
+ });
926
+ const [hasBeenOpened, setHasBeenOpened] = React__namespace.default.useState(false);
927
+ const [isDragging, setIsDragging] = React__namespace.default.useState(false);
928
+ const [justReleased, setJustReleased] = React__namespace.default.useState(false);
929
+ const overlayRef = React__namespace.default.useRef(null);
930
+ const openTime = React__namespace.default.useRef(null);
931
+ const dragStartTime = React__namespace.default.useRef(null);
932
+ const dragEndTime = React__namespace.default.useRef(null);
933
+ const lastTimeDragPrevented = React__namespace.default.useRef(null);
934
+ const isAllowedToDrag = React__namespace.default.useRef(false);
935
+ const nestedOpenChangeTimer = React__namespace.default.useRef(null);
936
+ const pointerStart = React__namespace.default.useRef(0);
937
+ const keyboardIsOpen = React__namespace.default.useRef(false);
938
+ const shouldAnimate = React__namespace.default.useRef(!defaultOpen);
939
+ const previousDiffFromInitial = React__namespace.default.useRef(0);
940
+ const drawerRef = React__namespace.default.useRef(null);
941
+ const drawerHeightRef = React__namespace.default.useRef(((_drawerRef_current = drawerRef.current) == null ? void 0 : _drawerRef_current.getBoundingClientRect().height) || 0);
942
+ const drawerWidthRef = React__namespace.default.useRef(((_drawerRef_current1 = drawerRef.current) == null ? void 0 : _drawerRef_current1.getBoundingClientRect().width) || 0);
943
+ const initialDrawerHeight = React__namespace.default.useRef(0);
944
+ const onSnapPointChange = React__namespace.default.useCallback((activeSnapPointIndex)=>{
945
+ // Change openTime ref when we reach the last snap point to prevent dragging for 500ms incase it's scrollable.
946
+ if (snapPoints && activeSnapPointIndex === snapPointsOffset.length - 1) openTime.current = new Date();
947
+ }, []);
948
+ const { activeSnapPoint, activeSnapPointIndex, setActiveSnapPoint, onRelease: onReleaseSnapPoints, snapPointsOffset, onDrag: onDragSnapPoints, shouldFade, getPercentageDragged: getSnapPointsPercentageDragged } = useSnapPoints({
949
+ snapPoints,
950
+ activeSnapPointProp,
951
+ setActiveSnapPointProp,
952
+ drawerRef,
953
+ fadeFromIndex,
954
+ overlayRef,
955
+ onSnapPointChange,
956
+ direction,
957
+ container,
958
+ snapToSequentialPoint
959
+ });
960
+ usePreventScroll({
961
+ isDisabled: !isOpen || isDragging || !modal || justReleased || !hasBeenOpened || !repositionInputs || !disablePreventScroll
962
+ });
963
+ const { restorePositionSetting } = usePositionFixed({
964
+ isOpen,
965
+ modal,
966
+ nested: nested != null ? nested : false,
967
+ hasBeenOpened,
968
+ preventScrollRestoration,
969
+ noBodyStyles
970
+ });
971
+ function getScale() {
972
+ return (window.innerWidth - WINDOW_TOP_OFFSET) / window.innerWidth;
973
+ }
974
+ function onPress(event) {
975
+ var _drawerRef_current, _drawerRef_current1;
976
+ if (!dismissible && !snapPoints) return;
977
+ if (drawerRef.current && !drawerRef.current.contains(event.target)) return;
978
+ drawerHeightRef.current = ((_drawerRef_current = drawerRef.current) == null ? void 0 : _drawerRef_current.getBoundingClientRect().height) || 0;
979
+ drawerWidthRef.current = ((_drawerRef_current1 = drawerRef.current) == null ? void 0 : _drawerRef_current1.getBoundingClientRect().width) || 0;
980
+ setIsDragging(true);
981
+ dragStartTime.current = new Date();
982
+ // iOS doesn't trigger mouseUp after scrolling so we need to listen to touched in order to disallow dragging
983
+ if (isIOS()) {
984
+ window.addEventListener('touchend', ()=>isAllowedToDrag.current = false, {
985
+ once: true
986
+ });
987
+ }
988
+ // Ensure we maintain correct pointer capture even when going outside of the drawer
989
+ event.target.setPointerCapture(event.pointerId);
990
+ pointerStart.current = isVertical(direction) ? event.pageY : event.pageX;
991
+ }
992
+ function shouldDrag(el, isDraggingInDirection) {
993
+ var _window_getSelection;
994
+ let element = el;
995
+ const highlightedText = (_window_getSelection = window.getSelection()) == null ? void 0 : _window_getSelection.toString();
996
+ const swipeAmount = drawerRef.current ? getTranslate(drawerRef.current, direction) : null;
997
+ const date = new Date();
998
+ // Fixes https://github.com/emilkowalski/vaul/issues/483
999
+ if (element.tagName === 'SELECT') {
1000
+ return false;
1001
+ }
1002
+ if (element.hasAttribute('data-vaul-no-drag') || element.closest('[data-vaul-no-drag]')) {
1003
+ return false;
1004
+ }
1005
+ if (direction === 'right' || direction === 'left') {
1006
+ return true;
1007
+ }
1008
+ // Allow scrolling when animating
1009
+ if (openTime.current && date.getTime() - openTime.current.getTime() < 500) {
1010
+ return false;
1011
+ }
1012
+ if (swipeAmount !== null) {
1013
+ if (direction === 'bottom' ? swipeAmount > 0 : swipeAmount < 0) {
1014
+ return true;
1015
+ }
1016
+ }
1017
+ // Don't drag if there's highlighted text
1018
+ if (highlightedText && highlightedText.length > 0) {
1019
+ return false;
1020
+ }
1021
+ // Disallow dragging if drawer was scrolled within `scrollLockTimeout`
1022
+ if (lastTimeDragPrevented.current && date.getTime() - lastTimeDragPrevented.current.getTime() < scrollLockTimeout && swipeAmount === 0) {
1023
+ lastTimeDragPrevented.current = date;
1024
+ return false;
1025
+ }
1026
+ if (isDraggingInDirection) {
1027
+ lastTimeDragPrevented.current = date;
1028
+ // We are dragging down so we should allow scrolling
1029
+ return false;
1030
+ }
1031
+ // Keep climbing up the DOM tree as long as there's a parent
1032
+ while(element){
1033
+ // Check if the element is scrollable
1034
+ if (element.scrollHeight > element.clientHeight) {
1035
+ if (element.scrollTop !== 0) {
1036
+ lastTimeDragPrevented.current = new Date();
1037
+ // The element is scrollable and not scrolled to the top, so don't drag
1038
+ return false;
1039
+ }
1040
+ if (element.getAttribute('role') === 'dialog') {
1041
+ return true;
1042
+ }
1043
+ }
1044
+ // Move up to the parent element
1045
+ element = element.parentNode;
1046
+ }
1047
+ // No scrollable parents not scrolled to the top found, so drag
1048
+ return true;
1049
+ }
1050
+ function onDrag(event) {
1051
+ if (!drawerRef.current) {
1052
+ return;
1053
+ }
1054
+ // We need to know how much of the drawer has been dragged in percentages so that we can transform background accordingly
1055
+ if (isDragging) {
1056
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
1057
+ const draggedDistance = (pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX)) * directionMultiplier;
1058
+ const isDraggingInDirection = draggedDistance > 0;
1059
+ // Pre condition for disallowing dragging in the close direction.
1060
+ const noCloseSnapPointsPreCondition = snapPoints && !dismissible && !isDraggingInDirection;
1061
+ // Disallow dragging down to close when first snap point is the active one and dismissible prop is set to false.
1062
+ if (noCloseSnapPointsPreCondition && activeSnapPointIndex === 0) return;
1063
+ // We need to capture last time when drag with scroll was triggered and have a timeout between
1064
+ const absDraggedDistance = Math.abs(draggedDistance);
1065
+ const wrapper = document.querySelector('[data-vaul-drawer-wrapper]');
1066
+ const drawerDimension = direction === 'bottom' || direction === 'top' ? drawerHeightRef.current : drawerWidthRef.current;
1067
+ // Calculate the percentage dragged, where 1 is the closed position
1068
+ let percentageDragged = absDraggedDistance / drawerDimension;
1069
+ const snapPointPercentageDragged = getSnapPointsPercentageDragged(absDraggedDistance, isDraggingInDirection);
1070
+ if (snapPointPercentageDragged !== null) {
1071
+ percentageDragged = snapPointPercentageDragged;
1072
+ }
1073
+ // Disallow close dragging beyond the smallest snap point.
1074
+ if (noCloseSnapPointsPreCondition && percentageDragged >= 1) {
1075
+ return;
1076
+ }
1077
+ if (!isAllowedToDrag.current && !shouldDrag(event.target, isDraggingInDirection)) return;
1078
+ drawerRef.current.classList.add(DRAG_CLASS);
1079
+ // 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
1080
+ isAllowedToDrag.current = true;
1081
+ set(drawerRef.current, {
1082
+ transition: 'none'
1083
+ });
1084
+ set(overlayRef.current, {
1085
+ transition: 'none'
1086
+ });
1087
+ if (snapPoints) {
1088
+ onDragSnapPoints({
1089
+ draggedDistance
1090
+ });
1091
+ }
1092
+ // Run this only if snapPoints are not defined or if we are at the last snap point (highest one)
1093
+ if (isDraggingInDirection && !snapPoints) {
1094
+ const dampenedDraggedDistance = dampenValue(draggedDistance);
1095
+ const translateValue = Math.min(dampenedDraggedDistance * -1, 0) * directionMultiplier;
1096
+ set(drawerRef.current, {
1097
+ transform: isVertical(direction) ? `translate3d(0, ${translateValue}px, 0)` : `translate3d(${translateValue}px, 0, 0)`
1098
+ });
1099
+ return;
1100
+ }
1101
+ const opacityValue = 1 - percentageDragged;
1102
+ if (shouldFade || fadeFromIndex && activeSnapPointIndex === fadeFromIndex - 1) {
1103
+ onDragProp == null ? void 0 : onDragProp(event, percentageDragged);
1104
+ set(overlayRef.current, {
1105
+ opacity: `${opacityValue}`,
1106
+ transition: 'none'
1107
+ }, true);
1108
+ }
1109
+ if (wrapper && overlayRef.current && shouldScaleBackground) {
1110
+ // Calculate percentageDragged as a fraction (0 to 1)
1111
+ const scaleValue = Math.min(getScale() + percentageDragged * (1 - getScale()), 1);
1112
+ const borderRadiusValue = 8 - percentageDragged * 8;
1113
+ const translateValue = Math.max(0, 14 - percentageDragged * 14);
1114
+ set(wrapper, {
1115
+ borderRadius: `${borderRadiusValue}px`,
1116
+ transform: isVertical(direction) ? `scale(${scaleValue}) translate3d(0, ${translateValue}px, 0)` : `scale(${scaleValue}) translate3d(${translateValue}px, 0, 0)`,
1117
+ transition: 'none'
1118
+ }, true);
1119
+ }
1120
+ if (!snapPoints) {
1121
+ const translateValue = absDraggedDistance * directionMultiplier;
1122
+ set(drawerRef.current, {
1123
+ transform: isVertical(direction) ? `translate3d(0, ${translateValue}px, 0)` : `translate3d(${translateValue}px, 0, 0)`
1124
+ });
1125
+ }
1126
+ }
1127
+ }
1128
+ React__namespace.default.useEffect(()=>{
1129
+ window.requestAnimationFrame(()=>{
1130
+ shouldAnimate.current = true;
1131
+ });
1132
+ }, []);
1133
+ React__namespace.default.useEffect(()=>{
1134
+ var _window_visualViewport;
1135
+ function onVisualViewportChange() {
1136
+ if (!drawerRef.current || !repositionInputs) return;
1137
+ const focusedElement = document.activeElement;
1138
+ if (isInput(focusedElement) || keyboardIsOpen.current) {
1139
+ var _window_visualViewport;
1140
+ const visualViewportHeight = ((_window_visualViewport = window.visualViewport) == null ? void 0 : _window_visualViewport.height) || 0;
1141
+ const totalHeight = window.innerHeight;
1142
+ // This is the height of the keyboard
1143
+ let diffFromInitial = totalHeight - visualViewportHeight;
1144
+ const drawerHeight = drawerRef.current.getBoundingClientRect().height || 0;
1145
+ // Adjust drawer height only if it's tall enough
1146
+ const isTallEnough = drawerHeight > totalHeight * 0.8;
1147
+ if (!initialDrawerHeight.current) {
1148
+ initialDrawerHeight.current = drawerHeight;
1149
+ }
1150
+ const offsetFromTop = drawerRef.current.getBoundingClientRect().top;
1151
+ // 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.
1152
+ if (Math.abs(previousDiffFromInitial.current - diffFromInitial) > 60) {
1153
+ keyboardIsOpen.current = !keyboardIsOpen.current;
1154
+ }
1155
+ if (snapPoints && snapPoints.length > 0 && snapPointsOffset && activeSnapPointIndex) {
1156
+ const activeSnapPointHeight = snapPointsOffset[activeSnapPointIndex] || 0;
1157
+ diffFromInitial += activeSnapPointHeight;
1158
+ }
1159
+ previousDiffFromInitial.current = diffFromInitial;
1160
+ // 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
1161
+ if (drawerHeight > visualViewportHeight || keyboardIsOpen.current) {
1162
+ const height = drawerRef.current.getBoundingClientRect().height;
1163
+ let newDrawerHeight = height;
1164
+ if (height > visualViewportHeight) {
1165
+ newDrawerHeight = visualViewportHeight - (isTallEnough ? offsetFromTop : WINDOW_TOP_OFFSET);
1166
+ }
1167
+ // 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
1168
+ if (fixed) {
1169
+ drawerRef.current.style.height = `${height - Math.max(diffFromInitial, 0)}px`;
1170
+ } else {
1171
+ drawerRef.current.style.height = `${Math.max(newDrawerHeight, visualViewportHeight - offsetFromTop)}px`;
1172
+ }
1173
+ } else if (!isMobileFirefox()) {
1174
+ drawerRef.current.style.height = `${initialDrawerHeight.current}px`;
1175
+ }
1176
+ if (snapPoints && snapPoints.length > 0 && !keyboardIsOpen.current) {
1177
+ drawerRef.current.style.bottom = `0px`;
1178
+ } else {
1179
+ // Negative bottom value would never make sense
1180
+ drawerRef.current.style.bottom = `${Math.max(diffFromInitial, 0)}px`;
1181
+ }
1182
+ }
1183
+ }
1184
+ (_window_visualViewport = window.visualViewport) == null ? void 0 : _window_visualViewport.addEventListener('resize', onVisualViewportChange);
1185
+ return ()=>{
1186
+ var _window_visualViewport;
1187
+ return (_window_visualViewport = window.visualViewport) == null ? void 0 : _window_visualViewport.removeEventListener('resize', onVisualViewportChange);
1188
+ };
1189
+ }, [
1190
+ activeSnapPointIndex,
1191
+ snapPoints,
1192
+ snapPointsOffset
1193
+ ]);
1194
+ function closeDrawer(fromWithin) {
1195
+ cancelDrag();
1196
+ onClose == null ? void 0 : onClose();
1197
+ if (!fromWithin) {
1198
+ setIsOpen(false);
1199
+ }
1200
+ setTimeout(()=>{
1201
+ if (snapPoints) {
1202
+ setActiveSnapPoint(snapPoints[0]);
1203
+ }
1204
+ }, TRANSITIONS.DURATION * 1000); // seconds to ms
1205
+ }
1206
+ function resetDrawer() {
1207
+ if (!drawerRef.current) return;
1208
+ const wrapper = document.querySelector('[data-vaul-drawer-wrapper]');
1209
+ const currentSwipeAmount = getTranslate(drawerRef.current, direction);
1210
+ set(drawerRef.current, {
1211
+ transform: 'translate3d(0, 0, 0)',
1212
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`
1213
+ });
1214
+ set(overlayRef.current, {
1215
+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
1216
+ opacity: '1'
1217
+ });
1218
+ // Don't reset background if swiped upwards
1219
+ if (shouldScaleBackground && currentSwipeAmount && currentSwipeAmount > 0 && isOpen) {
1220
+ set(wrapper, {
1221
+ borderRadius: `${BORDER_RADIUS}px`,
1222
+ overflow: 'hidden',
1223
+ ...isVertical(direction) ? {
1224
+ transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
1225
+ transformOrigin: 'top'
1226
+ } : {
1227
+ transform: `scale(${getScale()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,
1228
+ transformOrigin: 'left'
1229
+ },
1230
+ transitionProperty: 'transform, border-radius',
1231
+ transitionDuration: `${TRANSITIONS.DURATION}s`,
1232
+ transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`
1233
+ }, true);
1234
+ }
1235
+ }
1236
+ function cancelDrag() {
1237
+ if (!isDragging || !drawerRef.current) return;
1238
+ drawerRef.current.classList.remove(DRAG_CLASS);
1239
+ isAllowedToDrag.current = false;
1240
+ setIsDragging(false);
1241
+ dragEndTime.current = new Date();
1242
+ }
1243
+ function onRelease(event) {
1244
+ if (!isDragging || !drawerRef.current) return;
1245
+ drawerRef.current.classList.remove(DRAG_CLASS);
1246
+ isAllowedToDrag.current = false;
1247
+ setIsDragging(false);
1248
+ dragEndTime.current = new Date();
1249
+ const swipeAmount = getTranslate(drawerRef.current, direction);
1250
+ if (!event || !shouldDrag(event.target, false) || !swipeAmount || Number.isNaN(swipeAmount)) return;
1251
+ if (dragStartTime.current === null) return;
1252
+ const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
1253
+ const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
1254
+ const velocity = Math.abs(distMoved) / timeTaken;
1255
+ if (velocity > 0.05) {
1256
+ // `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.
1257
+ setJustReleased(true);
1258
+ setTimeout(()=>{
1259
+ setJustReleased(false);
1260
+ }, 200);
1261
+ }
1262
+ if (snapPoints) {
1263
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
1264
+ onReleaseSnapPoints({
1265
+ draggedDistance: distMoved * directionMultiplier,
1266
+ closeDrawer,
1267
+ velocity,
1268
+ dismissible
1269
+ });
1270
+ onReleaseProp == null ? void 0 : onReleaseProp(event, true);
1271
+ return;
1272
+ }
1273
+ // Moved upwards, don't do anything
1274
+ if (direction === 'bottom' || direction === 'right' ? distMoved > 0 : distMoved < 0) {
1275
+ resetDrawer();
1276
+ onReleaseProp == null ? void 0 : onReleaseProp(event, true);
1277
+ return;
1278
+ }
1279
+ if (velocity > VELOCITY_THRESHOLD) {
1280
+ closeDrawer();
1281
+ onReleaseProp == null ? void 0 : onReleaseProp(event, false);
1282
+ return;
1283
+ }
1284
+ var _drawerRef_current_getBoundingClientRect_height;
1285
+ const visibleDrawerHeight = Math.min((_drawerRef_current_getBoundingClientRect_height = drawerRef.current.getBoundingClientRect().height) != null ? _drawerRef_current_getBoundingClientRect_height : 0, window.innerHeight);
1286
+ var _drawerRef_current_getBoundingClientRect_width;
1287
+ const visibleDrawerWidth = Math.min((_drawerRef_current_getBoundingClientRect_width = drawerRef.current.getBoundingClientRect().width) != null ? _drawerRef_current_getBoundingClientRect_width : 0, window.innerWidth);
1288
+ const isHorizontalSwipe = direction === 'left' || direction === 'right';
1289
+ if (Math.abs(swipeAmount) >= (isHorizontalSwipe ? visibleDrawerWidth : visibleDrawerHeight) * closeThreshold) {
1290
+ closeDrawer();
1291
+ onReleaseProp == null ? void 0 : onReleaseProp(event, false);
1292
+ return;
1293
+ }
1294
+ onReleaseProp == null ? void 0 : onReleaseProp(event, true);
1295
+ resetDrawer();
1296
+ }
1297
+ React__namespace.default.useEffect(()=>{
1298
+ // Trigger enter animation without using CSS animation
1299
+ if (isOpen) {
1300
+ set(document.documentElement, {
1301
+ scrollBehavior: 'auto'
1302
+ });
1303
+ openTime.current = new Date();
1304
+ }
1305
+ return ()=>{
1306
+ reset(document.documentElement, 'scrollBehavior');
1307
+ };
1308
+ }, [
1309
+ isOpen
1310
+ ]);
1311
+ function onNestedOpenChange(o) {
1312
+ const scale = o ? (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth : 1;
1313
+ const initialTranslate = o ? -NESTED_DISPLACEMENT : 0;
1314
+ if (nestedOpenChangeTimer.current) {
1315
+ window.clearTimeout(nestedOpenChangeTimer.current);
1316
+ }
1317
+ set(drawerRef.current, {
1318
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
1319
+ transform: isVertical(direction) ? `scale(${scale}) translate3d(0, ${initialTranslate}px, 0)` : `scale(${scale}) translate3d(${initialTranslate}px, 0, 0)`
1320
+ });
1321
+ if (!o && drawerRef.current) {
1322
+ nestedOpenChangeTimer.current = setTimeout(()=>{
1323
+ const translateValue = getTranslate(drawerRef.current, direction);
1324
+ set(drawerRef.current, {
1325
+ transition: 'none',
1326
+ transform: isVertical(direction) ? `translate3d(0, ${translateValue}px, 0)` : `translate3d(${translateValue}px, 0, 0)`
1327
+ });
1328
+ }, 500);
1329
+ }
1330
+ }
1331
+ function onNestedDrag(_event, percentageDragged) {
1332
+ if (percentageDragged < 0) return;
1333
+ const initialScale = (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth;
1334
+ const newScale = initialScale + percentageDragged * (1 - initialScale);
1335
+ const newTranslate = -NESTED_DISPLACEMENT + percentageDragged * NESTED_DISPLACEMENT;
1336
+ set(drawerRef.current, {
1337
+ transform: isVertical(direction) ? `scale(${newScale}) translate3d(0, ${newTranslate}px, 0)` : `scale(${newScale}) translate3d(${newTranslate}px, 0, 0)`,
1338
+ transition: 'none'
1339
+ });
1340
+ }
1341
+ function onNestedRelease(_event, o) {
1342
+ const dim = isVertical(direction) ? window.innerHeight : window.innerWidth;
1343
+ const scale = o ? (dim - NESTED_DISPLACEMENT) / dim : 1;
1344
+ const translate = o ? -NESTED_DISPLACEMENT : 0;
1345
+ if (o) {
1346
+ set(drawerRef.current, {
1347
+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
1348
+ transform: isVertical(direction) ? `scale(${scale}) translate3d(0, ${translate}px, 0)` : `scale(${scale}) translate3d(${translate}px, 0, 0)`
1349
+ });
1350
+ }
1351
+ }
1352
+ React__namespace.default.useEffect(()=>{
1353
+ if (!modal) {
1354
+ // Need to do this manually unfortunately
1355
+ window.requestAnimationFrame(()=>{
1356
+ document.body.style.pointerEvents = 'auto';
1357
+ });
1358
+ }
1359
+ }, [
1360
+ modal
1361
+ ]);
1362
+ return /*#__PURE__*/ React__namespace.default.createElement(react.Dialog.Root, {
1363
+ defaultOpen: defaultOpen,
1364
+ onOpenChange: (open)=>{
1365
+ if (!dismissible && !open) return;
1366
+ if (open) {
1367
+ setHasBeenOpened(true);
1368
+ } else {
1369
+ closeDrawer(true);
1370
+ }
1371
+ setIsOpen(open);
1372
+ },
1373
+ open: isOpen,
1374
+ modal: modal
1375
+ }, /*#__PURE__*/ React__namespace.default.createElement(DrawerContext.Provider, {
1376
+ value: {
1377
+ activeSnapPoint,
1378
+ snapPoints,
1379
+ setActiveSnapPoint,
1380
+ drawerRef,
1381
+ overlayRef,
1382
+ onOpenChange,
1383
+ onPress,
1384
+ onRelease,
1385
+ onDrag,
1386
+ dismissible,
1387
+ shouldAnimate,
1388
+ handleOnly,
1389
+ isOpen,
1390
+ isDragging,
1391
+ shouldFade,
1392
+ closeDrawer,
1393
+ onNestedDrag,
1394
+ onNestedOpenChange,
1395
+ onNestedRelease,
1396
+ keyboardIsOpen,
1397
+ modal,
1398
+ snapPointsOffset,
1399
+ activeSnapPointIndex,
1400
+ direction,
1401
+ shouldScaleBackground,
1402
+ setBackgroundColorOnScale,
1403
+ noBodyStyles,
1404
+ container,
1405
+ autoFocus
1406
+ }
1407
+ }, children));
1408
+ }
1409
+ const Overlay = /*#__PURE__*/ React__namespace.default.forwardRef(function({ ...rest }, ref) {
1410
+ const { overlayRef, snapPoints, onRelease, shouldFade, isOpen, modal, shouldAnimate } = useDrawerContext();
1411
+ const composedRef = useComposedRefs(ref, overlayRef);
1412
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
1413
+ const onMouseUp = React__namespace.default.useCallback((event)=>onRelease(event), [
1414
+ onRelease
1415
+ ]);
1416
+ // Overlay is the component that is locking scroll, removing it will unlock the scroll without having to dig into Radix's Dialog library
1417
+ if (!modal) {
1418
+ return null;
1419
+ }
1420
+ return /*#__PURE__*/ React__namespace.default.createElement(react.Dialog.Backdrop, {
1421
+ onMouseUp: onMouseUp,
1422
+ ref: composedRef,
1423
+ "data-vaul-overlay": "",
1424
+ "data-vaul-snap-points": isOpen && hasSnapPoints ? 'true' : 'false',
1425
+ "data-vaul-snap-points-overlay": isOpen && shouldFade ? 'true' : 'false',
1426
+ "data-vaul-animate": (shouldAnimate == null ? void 0 : shouldAnimate.current) ? 'true' : 'false',
1427
+ ...rest
1428
+ });
1429
+ });
1430
+ Overlay.displayName = 'Drawer.Overlay';
1431
+ const Content = /*#__PURE__*/ React__namespace.default.forwardRef(function({ style, ...rest }, ref) {
1432
+ const { drawerRef, onPress, onRelease, onDrag, keyboardIsOpen, snapPointsOffset, activeSnapPointIndex, modal, isOpen, direction, snapPoints, container, handleOnly, shouldAnimate, autoFocus } = useDrawerContext();
1433
+ // Needed to use transition instead of animations
1434
+ const [delayedSnapPoints, setDelayedSnapPoints] = React__namespace.default.useState(false);
1435
+ const composedRef = useComposedRefs(ref, drawerRef);
1436
+ const pointerStartRef = React__namespace.default.useRef(null);
1437
+ const lastKnownPointerEventRef = React__namespace.default.useRef(null);
1438
+ const wasBeyondThePointRef = React__namespace.default.useRef(false);
1439
+ const hasSnapPoints = snapPoints && snapPoints.length > 0;
1440
+ useScaleBackground();
1441
+ const isDeltaInDirection = (delta, direction, threshold = 0)=>{
1442
+ if (wasBeyondThePointRef.current) return true;
1443
+ const deltaY = Math.abs(delta.y);
1444
+ const deltaX = Math.abs(delta.x);
1445
+ const isDeltaX = deltaX > deltaY;
1446
+ const dFactor = [
1447
+ 'bottom',
1448
+ 'right'
1449
+ ].includes(direction) ? 1 : -1;
1450
+ if (direction === 'left' || direction === 'right') {
1451
+ const isReverseDirection = delta.x * dFactor < 0;
1452
+ if (!isReverseDirection && deltaX >= 0 && deltaX <= threshold) {
1453
+ return isDeltaX;
1454
+ }
1455
+ } else {
1456
+ const isReverseDirection = delta.y * dFactor < 0;
1457
+ if (!isReverseDirection && deltaY >= 0 && deltaY <= threshold) {
1458
+ return !isDeltaX;
1459
+ }
1460
+ }
1461
+ wasBeyondThePointRef.current = true;
1462
+ return true;
1463
+ };
1464
+ React__namespace.default.useEffect(()=>{
1465
+ if (hasSnapPoints) {
1466
+ window.requestAnimationFrame(()=>{
1467
+ setDelayedSnapPoints(true);
1468
+ });
1469
+ }
1470
+ }, []);
1471
+ function handleOnPointerUp(event) {
1472
+ pointerStartRef.current = null;
1473
+ wasBeyondThePointRef.current = false;
1474
+ onRelease(event);
1475
+ }
1476
+ return /*#__PURE__*/ React__namespace.default.createElement(react.Dialog.Viewport, null, /*#__PURE__*/ React__namespace.default.createElement(react.Dialog.Popup, {
1477
+ "data-vaul-drawer-direction": direction,
1478
+ "data-vaul-drawer": "",
1479
+ "data-vaul-delayed-snap-points": delayedSnapPoints ? 'true' : 'false',
1480
+ "data-vaul-snap-points": isOpen && hasSnapPoints ? 'true' : 'false',
1481
+ "data-vaul-custom-container": container ? 'true' : 'false',
1482
+ "data-vaul-animate": (shouldAnimate == null ? void 0 : shouldAnimate.current) ? 'true' : 'false',
1483
+ ...rest,
1484
+ ref: composedRef,
1485
+ style: snapPointsOffset && snapPointsOffset.length > 0 ? {
1486
+ // @ts-ignore This should not be an error
1487
+ '--snap-point-height': `${snapPointsOffset[activeSnapPointIndex != null ? activeSnapPointIndex : 0]}px`,
1488
+ ...style
1489
+ } : style,
1490
+ onPointerDown: (event)=>{
1491
+ if (handleOnly) return;
1492
+ rest.onPointerDown == null ? void 0 : rest.onPointerDown.call(rest, event);
1493
+ pointerStartRef.current = {
1494
+ x: event.pageX,
1495
+ y: event.pageY
1496
+ };
1497
+ onPress(event);
1498
+ },
1499
+ onPointerMove: (event)=>{
1500
+ lastKnownPointerEventRef.current = event;
1501
+ if (handleOnly) return;
1502
+ rest.onPointerMove == null ? void 0 : rest.onPointerMove.call(rest, event);
1503
+ if (!pointerStartRef.current) return;
1504
+ const yPosition = event.pageY - pointerStartRef.current.y;
1505
+ const xPosition = event.pageX - pointerStartRef.current.x;
1506
+ const swipeStartThreshold = event.pointerType === 'touch' ? 10 : 2;
1507
+ const delta = {
1508
+ x: xPosition,
1509
+ y: yPosition
1510
+ };
1511
+ const isAllowedToSwipe = isDeltaInDirection(delta, direction, swipeStartThreshold);
1512
+ if (isAllowedToSwipe) onDrag(event);
1513
+ else if (Math.abs(xPosition) > swipeStartThreshold || Math.abs(yPosition) > swipeStartThreshold) {
1514
+ pointerStartRef.current = null;
1515
+ }
1516
+ },
1517
+ onPointerUp: (event)=>{
1518
+ rest.onPointerUp == null ? void 0 : rest.onPointerUp.call(rest, event);
1519
+ pointerStartRef.current = null;
1520
+ wasBeyondThePointRef.current = false;
1521
+ onRelease(event);
1522
+ },
1523
+ onPointerOut: (event)=>{
1524
+ rest.onPointerOut == null ? void 0 : rest.onPointerOut.call(rest, event);
1525
+ handleOnPointerUp(lastKnownPointerEventRef.current);
1526
+ },
1527
+ onContextMenu: (event)=>{
1528
+ rest.onContextMenu == null ? void 0 : rest.onContextMenu.call(rest, event);
1529
+ if (lastKnownPointerEventRef.current) {
1530
+ handleOnPointerUp(lastKnownPointerEventRef.current);
1531
+ }
1532
+ }
1533
+ }));
1534
+ });
1535
+ Content.displayName = 'Drawer.Content';
1536
+ const LONG_HANDLE_PRESS_TIMEOUT = 250;
1537
+ const DOUBLE_TAP_TIMEOUT = 120;
1538
+ const Handle = /*#__PURE__*/ React__namespace.default.forwardRef(function({ preventCycle = false, children, ...rest }, ref) {
1539
+ const { closeDrawer, isDragging, snapPoints, activeSnapPoint, setActiveSnapPoint, dismissible, handleOnly, isOpen, onPress, onDrag } = useDrawerContext();
1540
+ const closeTimeoutIdRef = React__namespace.default.useRef(null);
1541
+ const shouldCancelInteractionRef = React__namespace.default.useRef(false);
1542
+ function handleStartCycle() {
1543
+ // Stop if this is the second click of a double click
1544
+ if (shouldCancelInteractionRef.current) {
1545
+ handleCancelInteraction();
1546
+ return;
1547
+ }
1548
+ window.setTimeout(()=>{
1549
+ handleCycleSnapPoints();
1550
+ }, DOUBLE_TAP_TIMEOUT);
1551
+ }
1552
+ function handleCycleSnapPoints() {
1553
+ // Prevent accidental taps while resizing drawer
1554
+ if (isDragging || preventCycle || shouldCancelInteractionRef.current) {
1555
+ handleCancelInteraction();
1556
+ return;
1557
+ }
1558
+ // Make sure to clear the timeout id if the user releases the handle before the cancel timeout
1559
+ handleCancelInteraction();
1560
+ if (!snapPoints || snapPoints.length === 0) {
1561
+ if (!dismissible) {
1562
+ closeDrawer();
1563
+ }
1564
+ return;
1565
+ }
1566
+ const isLastSnapPoint = activeSnapPoint === snapPoints[snapPoints.length - 1];
1567
+ if (isLastSnapPoint && dismissible) {
1568
+ closeDrawer();
1569
+ return;
1570
+ }
1571
+ const currentSnapIndex = snapPoints.findIndex((point)=>point === activeSnapPoint);
1572
+ if (currentSnapIndex === -1) return; // activeSnapPoint not found in snapPoints
1573
+ const nextSnapPoint = snapPoints[currentSnapIndex + 1];
1574
+ setActiveSnapPoint(nextSnapPoint);
1575
+ }
1576
+ function handleStartInteraction() {
1577
+ closeTimeoutIdRef.current = window.setTimeout(()=>{
1578
+ // Cancel click interaction on a long press
1579
+ shouldCancelInteractionRef.current = true;
1580
+ }, LONG_HANDLE_PRESS_TIMEOUT);
1581
+ }
1582
+ function handleCancelInteraction() {
1583
+ if (closeTimeoutIdRef.current) {
1584
+ window.clearTimeout(closeTimeoutIdRef.current);
1585
+ }
1586
+ shouldCancelInteractionRef.current = false;
1587
+ }
1588
+ return /*#__PURE__*/ React__namespace.default.createElement("div", {
1589
+ onClick: handleStartCycle,
1590
+ onPointerCancel: handleCancelInteraction,
1591
+ onPointerDown: (e)=>{
1592
+ if (handleOnly) onPress({
1593
+ ...e,
1594
+ preventBaseUIHandler: ()=>{}
1595
+ });
1596
+ handleStartInteraction();
1597
+ },
1598
+ onPointerMove: (e)=>{
1599
+ if (handleOnly) onDrag({
1600
+ ...e,
1601
+ preventBaseUIHandler: ()=>{}
1602
+ });
1603
+ },
1604
+ // onPointerUp is already handled by the content component
1605
+ ref: ref,
1606
+ "data-vaul-drawer-visible": isOpen ? 'true' : 'false',
1607
+ "data-vaul-handle": "",
1608
+ "aria-hidden": "true",
1609
+ ...rest
1610
+ }, /*#__PURE__*/ React__namespace.default.createElement("span", {
1611
+ "data-vaul-handle-hitarea": "",
1612
+ "aria-hidden": "true"
1613
+ }, children));
1614
+ });
1615
+ Handle.displayName = 'Drawer.Handle';
1616
+ function NestedRoot({ onDrag, onOpenChange, open: nestedIsOpen, ...rest }) {
1617
+ const { onNestedDrag, onNestedOpenChange, onNestedRelease } = useDrawerContext();
1618
+ if (!onNestedDrag) {
1619
+ throw new Error('Drawer.NestedRoot must be placed in another drawer');
1620
+ }
1621
+ return /*#__PURE__*/ React__namespace.default.createElement(Root, {
1622
+ nested: true,
1623
+ open: nestedIsOpen,
1624
+ onClose: ()=>{
1625
+ onNestedOpenChange(false);
1626
+ },
1627
+ onDrag: (e, p)=>{
1628
+ onNestedDrag(e, p);
1629
+ onDrag == null ? void 0 : onDrag(e, p);
1630
+ },
1631
+ onOpenChange: (o)=>{
1632
+ if (o) {
1633
+ onNestedOpenChange(o);
1634
+ }
1635
+ onOpenChange == null ? void 0 : onOpenChange(o);
1636
+ },
1637
+ onRelease: onNestedRelease,
1638
+ ...rest
1639
+ });
1640
+ }
1641
+ function Portal(props) {
1642
+ const context = useDrawerContext();
1643
+ const { container = context.container, ...portalProps } = props;
1644
+ return /*#__PURE__*/ React__namespace.default.createElement(react.Dialog.Portal, {
1645
+ container: container,
1646
+ ...portalProps
1647
+ });
1648
+ }
1649
+ const Drawer = {
1650
+ Root,
1651
+ NestedRoot,
1652
+ Content,
1653
+ Overlay,
1654
+ Trigger: react.Dialog.Trigger,
1655
+ Portal,
1656
+ Handle,
1657
+ Close: react.Dialog.Close,
1658
+ Title: react.Dialog.Title,
1659
+ Description: react.Dialog.Description
1660
+ };
1661
+
1662
+ exports.Content = Content;
1663
+ exports.Drawer = Drawer;
1664
+ exports.Handle = Handle;
1665
+ exports.NestedRoot = NestedRoot;
1666
+ exports.Overlay = Overlay;
1667
+ exports.Portal = Portal;
1668
+ exports.Root = Root;