JAVASCRIPT   109

close.js

Guest on 29th July 2021 03:17:11 PM

  1. import { undoScrollbar } from '../utils/scrollbarFix'
  2. import { undoIOSfix } from '../utils/iosFix'
  3. import { unsetAriaHidden } from '../utils/aria'
  4. import * as dom from '../utils/dom/index'
  5. import { swalClasses } from '../utils/classes.js'
  6. import globalState, { restoreActiveElement } from '../globalState'
  7.  
  8. /*
  9.  * Global function to close sweetAlert
  10.  */
  11. const close = (onClose, onAfterClose) => {
  12.   const container = dom.getContainer()
  13.   const popup = dom.getPopup()
  14.   if (!popup) {
  15.     return
  16.   }
  17.  
  18.   if (onClose !== null && typeof onClose === 'function') {
  19.     onClose(popup)
  20.   }
  21.  
  22.   dom.removeClass(popup, swalClasses.show)
  23.   dom.addClass(popup, swalClasses.hide)
  24.  
  25.   const removePopupAndResetState = () => {
  26.     if (!dom.isToast()) {
  27.       restoreActiveElement().then(() => triggerOnAfterClose(onAfterClose))
  28.       globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture })
  29.       globalState.keydownHandlerAdded = false
  30.     } else {
  31.       triggerOnAfterClose(onAfterClose)
  32.     }
  33.  
  34.     if (container.parentNode) {
  35.       container.parentNode.removeChild(container)
  36.     }
  37.     dom.removeClass(
  38.       [document.documentElement, document.body],
  39.       [
  40.         swalClasses.shown,
  41.         swalClasses['height-auto'],
  42.         swalClasses['no-backdrop'],
  43.         swalClasses['toast-shown'],
  44.         swalClasses['toast-column']
  45.       ]
  46.     )
  47.  
  48.     if (dom.isModal()) {
  49.       undoScrollbar()
  50.       undoIOSfix()
  51.       unsetAriaHidden()
  52.     }
  53.   }
  54.  
  55.   // If animation is supported, animate
  56.   if (dom.animationEndEvent && !dom.hasClass(popup, swalClasses.noanimation)) {
  57.     popup.addEventListener(dom.animationEndEvent, function swalCloseEventFinished () {
  58.       popup.removeEventListener(dom.animationEndEvent, swalCloseEventFinished)
  59.       if (dom.hasClass(popup, swalClasses.hide)) {
  60.         removePopupAndResetState()
  61.       }
  62.     })
  63.   } else {
  64.     // Otherwise, remove immediately
  65.     removePopupAndResetState()
  66.   }
  67. }
  68.  
  69. const triggerOnAfterClose = (onAfterClose) => {
  70.   if (onAfterClose !== null && typeof onAfterClose === 'function') {
  71.     setTimeout(() => {
  72.       onAfterClose()
  73.     })
  74.   }
  75. }
  76.  
  77. export {
  78.   close,
  79.   close as closePopup,
  80.   close as closeModal,
  81.   close as closeToast
  82. }

Raw Paste


Login or Register to edit or fork this paste. It's free.