@samline/drawer 2.0.0

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