@seed-design/react-drawer 1.0.0 → 1.0.1

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