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