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