index.mjs 77 KB

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