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