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