Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

4490 řádky
150 KiB

  1. /*!
  2. * sweetalert2 v11.14.4
  3. * Released under the MIT License.
  4. */
  5. function _assertClassBrand(e, t, n) {
  6. if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
  7. throw new TypeError("Private element is not present on this object");
  8. }
  9. function _checkPrivateRedeclaration(e, t) {
  10. if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
  11. }
  12. function _classPrivateFieldGet2(s, a) {
  13. return s.get(_assertClassBrand(s, a));
  14. }
  15. function _classPrivateFieldInitSpec(e, t, a) {
  16. _checkPrivateRedeclaration(e, t), t.set(e, a);
  17. }
  18. function _classPrivateFieldSet2(s, a, r) {
  19. return s.set(_assertClassBrand(s, a), r), r;
  20. }
  21. const RESTORE_FOCUS_TIMEOUT = 100;
  22. /** @type {GlobalState} */
  23. const globalState = {};
  24. const focusPreviousActiveElement = () => {
  25. if (globalState.previousActiveElement instanceof HTMLElement) {
  26. globalState.previousActiveElement.focus();
  27. globalState.previousActiveElement = null;
  28. } else if (document.body) {
  29. document.body.focus();
  30. }
  31. };
  32. /**
  33. * Restore previous active (focused) element
  34. *
  35. * @param {boolean} returnFocus
  36. * @returns {Promise<void>}
  37. */
  38. const restoreActiveElement = returnFocus => {
  39. return new Promise(resolve => {
  40. if (!returnFocus) {
  41. return resolve();
  42. }
  43. const x = window.scrollX;
  44. const y = window.scrollY;
  45. globalState.restoreFocusTimeout = setTimeout(() => {
  46. focusPreviousActiveElement();
  47. resolve();
  48. }, RESTORE_FOCUS_TIMEOUT); // issues/900
  49. window.scrollTo(x, y);
  50. });
  51. };
  52. const swalPrefix = 'swal2-';
  53. /**
  54. * @typedef {Record<SwalClass, string>} SwalClasses
  55. */
  56. /**
  57. * @typedef {'success' | 'warning' | 'info' | 'question' | 'error'} SwalIcon
  58. * @typedef {Record<SwalIcon, string>} SwalIcons
  59. */
  60. /** @type {SwalClass[]} */
  61. const classNames = ['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error'];
  62. const swalClasses = classNames.reduce((acc, className) => {
  63. acc[className] = swalPrefix + className;
  64. return acc;
  65. }, /** @type {SwalClasses} */{});
  66. /** @type {SwalIcon[]} */
  67. const icons = ['success', 'warning', 'info', 'question', 'error'];
  68. const iconTypes = icons.reduce((acc, icon) => {
  69. acc[icon] = swalPrefix + icon;
  70. return acc;
  71. }, /** @type {SwalIcons} */{});
  72. const consolePrefix = 'SweetAlert2:';
  73. /**
  74. * Capitalize the first letter of a string
  75. *
  76. * @param {string} str
  77. * @returns {string}
  78. */
  79. const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
  80. /**
  81. * Standardize console warnings
  82. *
  83. * @param {string | string[]} message
  84. */
  85. const warn = message => {
  86. console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`);
  87. };
  88. /**
  89. * Standardize console errors
  90. *
  91. * @param {string} message
  92. */
  93. const error = message => {
  94. console.error(`${consolePrefix} ${message}`);
  95. };
  96. /**
  97. * Private global state for `warnOnce`
  98. *
  99. * @type {string[]}
  100. * @private
  101. */
  102. const previousWarnOnceMessages = [];
  103. /**
  104. * Show a console warning, but only if it hasn't already been shown
  105. *
  106. * @param {string} message
  107. */
  108. const warnOnce = message => {
  109. if (!previousWarnOnceMessages.includes(message)) {
  110. previousWarnOnceMessages.push(message);
  111. warn(message);
  112. }
  113. };
  114. /**
  115. * Show a one-time console warning about deprecated params/methods
  116. *
  117. * @param {string} deprecatedParam
  118. * @param {string?} useInstead
  119. */
  120. const warnAboutDeprecation = function (deprecatedParam) {
  121. let useInstead = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  122. warnOnce(`"${deprecatedParam}" is deprecated and will be removed in the next major release.${useInstead ? ` Use "${useInstead}" instead.` : ''}`);
  123. };
  124. /**
  125. * If `arg` is a function, call it (with no arguments or context) and return the result.
  126. * Otherwise, just pass the value through
  127. *
  128. * @param {Function | any} arg
  129. * @returns {any}
  130. */
  131. const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
  132. /**
  133. * @param {any} arg
  134. * @returns {boolean}
  135. */
  136. const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
  137. /**
  138. * @param {any} arg
  139. * @returns {Promise<any>}
  140. */
  141. const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
  142. /**
  143. * @param {any} arg
  144. * @returns {boolean}
  145. */
  146. const isPromise = arg => arg && Promise.resolve(arg) === arg;
  147. /**
  148. * Gets the popup container which contains the backdrop and the popup itself.
  149. *
  150. * @returns {HTMLElement | null}
  151. */
  152. const getContainer = () => document.body.querySelector(`.${swalClasses.container}`);
  153. /**
  154. * @param {string} selectorString
  155. * @returns {HTMLElement | null}
  156. */
  157. const elementBySelector = selectorString => {
  158. const container = getContainer();
  159. return container ? container.querySelector(selectorString) : null;
  160. };
  161. /**
  162. * @param {string} className
  163. * @returns {HTMLElement | null}
  164. */
  165. const elementByClass = className => {
  166. return elementBySelector(`.${className}`);
  167. };
  168. /**
  169. * @returns {HTMLElement | null}
  170. */
  171. const getPopup = () => elementByClass(swalClasses.popup);
  172. /**
  173. * @returns {HTMLElement | null}
  174. */
  175. const getIcon = () => elementByClass(swalClasses.icon);
  176. /**
  177. * @returns {HTMLElement | null}
  178. */
  179. const getIconContent = () => elementByClass(swalClasses['icon-content']);
  180. /**
  181. * @returns {HTMLElement | null}
  182. */
  183. const getTitle = () => elementByClass(swalClasses.title);
  184. /**
  185. * @returns {HTMLElement | null}
  186. */
  187. const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
  188. /**
  189. * @returns {HTMLElement | null}
  190. */
  191. const getImage = () => elementByClass(swalClasses.image);
  192. /**
  193. * @returns {HTMLElement | null}
  194. */
  195. const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
  196. /**
  197. * @returns {HTMLElement | null}
  198. */
  199. const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
  200. /**
  201. * @returns {HTMLButtonElement | null}
  202. */
  203. const getConfirmButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`));
  204. /**
  205. * @returns {HTMLButtonElement | null}
  206. */
  207. const getCancelButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`));
  208. /**
  209. * @returns {HTMLButtonElement | null}
  210. */
  211. const getDenyButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`));
  212. /**
  213. * @returns {HTMLElement | null}
  214. */
  215. const getInputLabel = () => elementByClass(swalClasses['input-label']);
  216. /**
  217. * @returns {HTMLElement | null}
  218. */
  219. const getLoader = () => elementBySelector(`.${swalClasses.loader}`);
  220. /**
  221. * @returns {HTMLElement | null}
  222. */
  223. const getActions = () => elementByClass(swalClasses.actions);
  224. /**
  225. * @returns {HTMLElement | null}
  226. */
  227. const getFooter = () => elementByClass(swalClasses.footer);
  228. /**
  229. * @returns {HTMLElement | null}
  230. */
  231. const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
  232. /**
  233. * @returns {HTMLElement | null}
  234. */
  235. const getCloseButton = () => elementByClass(swalClasses.close);
  236. // https://github.com/jkup/focusable/blob/master/index.js
  237. const focusable = `
  238. a[href],
  239. area[href],
  240. input:not([disabled]),
  241. select:not([disabled]),
  242. textarea:not([disabled]),
  243. button:not([disabled]),
  244. iframe,
  245. object,
  246. embed,
  247. [tabindex="0"],
  248. [contenteditable],
  249. audio[controls],
  250. video[controls],
  251. summary
  252. `;
  253. /**
  254. * @returns {HTMLElement[]}
  255. */
  256. const getFocusableElements = () => {
  257. const popup = getPopup();
  258. if (!popup) {
  259. return [];
  260. }
  261. /** @type {NodeListOf<HTMLElement>} */
  262. const focusableElementsWithTabindex = popup.querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])');
  263. const focusableElementsWithTabindexSorted = Array.from(focusableElementsWithTabindex)
  264. // sort according to tabindex
  265. .sort((a, b) => {
  266. const tabindexA = parseInt(a.getAttribute('tabindex') || '0');
  267. const tabindexB = parseInt(b.getAttribute('tabindex') || '0');
  268. if (tabindexA > tabindexB) {
  269. return 1;
  270. } else if (tabindexA < tabindexB) {
  271. return -1;
  272. }
  273. return 0;
  274. });
  275. /** @type {NodeListOf<HTMLElement>} */
  276. const otherFocusableElements = popup.querySelectorAll(focusable);
  277. const otherFocusableElementsFiltered = Array.from(otherFocusableElements).filter(el => el.getAttribute('tabindex') !== '-1');
  278. return [...new Set(focusableElementsWithTabindexSorted.concat(otherFocusableElementsFiltered))].filter(el => isVisible$1(el));
  279. };
  280. /**
  281. * @returns {boolean}
  282. */
  283. const isModal = () => {
  284. return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
  285. };
  286. /**
  287. * @returns {boolean}
  288. */
  289. const isToast = () => {
  290. const popup = getPopup();
  291. if (!popup) {
  292. return false;
  293. }
  294. return hasClass(popup, swalClasses.toast);
  295. };
  296. /**
  297. * @returns {boolean}
  298. */
  299. const isLoading = () => {
  300. const popup = getPopup();
  301. if (!popup) {
  302. return false;
  303. }
  304. return popup.hasAttribute('data-loading');
  305. };
  306. /**
  307. * Securely set innerHTML of an element
  308. * https://github.com/sweetalert2/sweetalert2/issues/1926
  309. *
  310. * @param {HTMLElement} elem
  311. * @param {string} html
  312. */
  313. const setInnerHtml = (elem, html) => {
  314. elem.textContent = '';
  315. if (html) {
  316. const parser = new DOMParser();
  317. const parsed = parser.parseFromString(html, `text/html`);
  318. const head = parsed.querySelector('head');
  319. if (head) {
  320. Array.from(head.childNodes).forEach(child => {
  321. elem.appendChild(child);
  322. });
  323. }
  324. const body = parsed.querySelector('body');
  325. if (body) {
  326. Array.from(body.childNodes).forEach(child => {
  327. if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) {
  328. elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507
  329. } else {
  330. elem.appendChild(child);
  331. }
  332. });
  333. }
  334. }
  335. };
  336. /**
  337. * @param {HTMLElement} elem
  338. * @param {string} className
  339. * @returns {boolean}
  340. */
  341. const hasClass = (elem, className) => {
  342. if (!className) {
  343. return false;
  344. }
  345. const classList = className.split(/\s+/);
  346. for (let i = 0; i < classList.length; i++) {
  347. if (!elem.classList.contains(classList[i])) {
  348. return false;
  349. }
  350. }
  351. return true;
  352. };
  353. /**
  354. * @param {HTMLElement} elem
  355. * @param {SweetAlertOptions} params
  356. */
  357. const removeCustomClasses = (elem, params) => {
  358. Array.from(elem.classList).forEach(className => {
  359. if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass || {}).includes(className)) {
  360. elem.classList.remove(className);
  361. }
  362. });
  363. };
  364. /**
  365. * @param {HTMLElement} elem
  366. * @param {SweetAlertOptions} params
  367. * @param {string} className
  368. */
  369. const applyCustomClass = (elem, params, className) => {
  370. removeCustomClasses(elem, params);
  371. if (!params.customClass) {
  372. return;
  373. }
  374. const customClass = params.customClass[(/** @type {keyof SweetAlertCustomClass} */className)];
  375. if (!customClass) {
  376. return;
  377. }
  378. if (typeof customClass !== 'string' && !customClass.forEach) {
  379. warn(`Invalid type of customClass.${className}! Expected string or iterable object, got "${typeof customClass}"`);
  380. return;
  381. }
  382. addClass(elem, customClass);
  383. };
  384. /**
  385. * @param {HTMLElement} popup
  386. * @param {import('./renderers/renderInput').InputClass | SweetAlertInput} inputClass
  387. * @returns {HTMLInputElement | null}
  388. */
  389. const getInput$1 = (popup, inputClass) => {
  390. if (!inputClass) {
  391. return null;
  392. }
  393. switch (inputClass) {
  394. case 'select':
  395. case 'textarea':
  396. case 'file':
  397. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`);
  398. case 'checkbox':
  399. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`);
  400. case 'radio':
  401. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`);
  402. case 'range':
  403. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`);
  404. default:
  405. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`);
  406. }
  407. };
  408. /**
  409. * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input
  410. */
  411. const focusInput = input => {
  412. input.focus();
  413. // place cursor at end of text in text input
  414. if (input.type !== 'file') {
  415. // http://stackoverflow.com/a/2345915
  416. const val = input.value;
  417. input.value = '';
  418. input.value = val;
  419. }
  420. };
  421. /**
  422. * @param {HTMLElement | HTMLElement[] | null} target
  423. * @param {string | string[] | readonly string[] | undefined} classList
  424. * @param {boolean} condition
  425. */
  426. const toggleClass = (target, classList, condition) => {
  427. if (!target || !classList) {
  428. return;
  429. }
  430. if (typeof classList === 'string') {
  431. classList = classList.split(/\s+/).filter(Boolean);
  432. }
  433. classList.forEach(className => {
  434. if (Array.isArray(target)) {
  435. target.forEach(elem => {
  436. if (condition) {
  437. elem.classList.add(className);
  438. } else {
  439. elem.classList.remove(className);
  440. }
  441. });
  442. } else {
  443. if (condition) {
  444. target.classList.add(className);
  445. } else {
  446. target.classList.remove(className);
  447. }
  448. }
  449. });
  450. };
  451. /**
  452. * @param {HTMLElement | HTMLElement[] | null} target
  453. * @param {string | string[] | readonly string[] | undefined} classList
  454. */
  455. const addClass = (target, classList) => {
  456. toggleClass(target, classList, true);
  457. };
  458. /**
  459. * @param {HTMLElement | HTMLElement[] | null} target
  460. * @param {string | string[] | readonly string[] | undefined} classList
  461. */
  462. const removeClass = (target, classList) => {
  463. toggleClass(target, classList, false);
  464. };
  465. /**
  466. * Get direct child of an element by class name
  467. *
  468. * @param {HTMLElement} elem
  469. * @param {string} className
  470. * @returns {HTMLElement | undefined}
  471. */
  472. const getDirectChildByClass = (elem, className) => {
  473. const children = Array.from(elem.children);
  474. for (let i = 0; i < children.length; i++) {
  475. const child = children[i];
  476. if (child instanceof HTMLElement && hasClass(child, className)) {
  477. return child;
  478. }
  479. }
  480. };
  481. /**
  482. * @param {HTMLElement} elem
  483. * @param {string} property
  484. * @param {*} value
  485. */
  486. const applyNumericalStyle = (elem, property, value) => {
  487. if (value === `${parseInt(value)}`) {
  488. value = parseInt(value);
  489. }
  490. if (value || parseInt(value) === 0) {
  491. elem.style.setProperty(property, typeof value === 'number' ? `${value}px` : value);
  492. } else {
  493. elem.style.removeProperty(property);
  494. }
  495. };
  496. /**
  497. * @param {HTMLElement | null} elem
  498. * @param {string} display
  499. */
  500. const show = function (elem) {
  501. let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
  502. if (!elem) {
  503. return;
  504. }
  505. elem.style.display = display;
  506. };
  507. /**
  508. * @param {HTMLElement | null} elem
  509. */
  510. const hide = elem => {
  511. if (!elem) {
  512. return;
  513. }
  514. elem.style.display = 'none';
  515. };
  516. /**
  517. * @param {HTMLElement | null} elem
  518. * @param {string} display
  519. */
  520. const showWhenInnerHtmlPresent = function (elem) {
  521. let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'block';
  522. if (!elem) {
  523. return;
  524. }
  525. new MutationObserver(() => {
  526. toggle(elem, elem.innerHTML, display);
  527. }).observe(elem, {
  528. childList: true,
  529. subtree: true
  530. });
  531. };
  532. /**
  533. * @param {HTMLElement} parent
  534. * @param {string} selector
  535. * @param {string} property
  536. * @param {string} value
  537. */
  538. const setStyle = (parent, selector, property, value) => {
  539. /** @type {HTMLElement | null} */
  540. const el = parent.querySelector(selector);
  541. if (el) {
  542. el.style.setProperty(property, value);
  543. }
  544. };
  545. /**
  546. * @param {HTMLElement} elem
  547. * @param {any} condition
  548. * @param {string} display
  549. */
  550. const toggle = function (elem, condition) {
  551. let display = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'flex';
  552. if (condition) {
  553. show(elem, display);
  554. } else {
  555. hide(elem);
  556. }
  557. };
  558. /**
  559. * borrowed from jquery $(elem).is(':visible') implementation
  560. *
  561. * @param {HTMLElement | null} elem
  562. * @returns {boolean}
  563. */
  564. const isVisible$1 = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
  565. /**
  566. * @returns {boolean}
  567. */
  568. const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton());
  569. /**
  570. * @param {HTMLElement} elem
  571. * @returns {boolean}
  572. */
  573. const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight);
  574. /**
  575. * borrowed from https://stackoverflow.com/a/46352119
  576. *
  577. * @param {HTMLElement} elem
  578. * @returns {boolean}
  579. */
  580. const hasCssAnimation = elem => {
  581. const style = window.getComputedStyle(elem);
  582. const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
  583. const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
  584. return animDuration > 0 || transDuration > 0;
  585. };
  586. /**
  587. * @param {number} timer
  588. * @param {boolean} reset
  589. */
  590. const animateTimerProgressBar = function (timer) {
  591. let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  592. const timerProgressBar = getTimerProgressBar();
  593. if (!timerProgressBar) {
  594. return;
  595. }
  596. if (isVisible$1(timerProgressBar)) {
  597. if (reset) {
  598. timerProgressBar.style.transition = 'none';
  599. timerProgressBar.style.width = '100%';
  600. }
  601. setTimeout(() => {
  602. timerProgressBar.style.transition = `width ${timer / 1000}s linear`;
  603. timerProgressBar.style.width = '0%';
  604. }, 10);
  605. }
  606. };
  607. const stopTimerProgressBar = () => {
  608. const timerProgressBar = getTimerProgressBar();
  609. if (!timerProgressBar) {
  610. return;
  611. }
  612. const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  613. timerProgressBar.style.removeProperty('transition');
  614. timerProgressBar.style.width = '100%';
  615. const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  616. const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
  617. timerProgressBar.style.width = `${timerProgressBarPercent}%`;
  618. };
  619. /**
  620. * Detect Node env
  621. *
  622. * @returns {boolean}
  623. */
  624. const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
  625. const sweetHTML = `
  626. <div aria-labelledby="${swalClasses.title}" aria-describedby="${swalClasses['html-container']}" class="${swalClasses.popup}" tabindex="-1">
  627. <button type="button" class="${swalClasses.close}"></button>
  628. <ul class="${swalClasses['progress-steps']}"></ul>
  629. <div class="${swalClasses.icon}"></div>
  630. <img class="${swalClasses.image}" />
  631. <h2 class="${swalClasses.title}" id="${swalClasses.title}"></h2>
  632. <div class="${swalClasses['html-container']}" id="${swalClasses['html-container']}"></div>
  633. <input class="${swalClasses.input}" id="${swalClasses.input}" />
  634. <input type="file" class="${swalClasses.file}" />
  635. <div class="${swalClasses.range}">
  636. <input type="range" />
  637. <output></output>
  638. </div>
  639. <select class="${swalClasses.select}" id="${swalClasses.select}"></select>
  640. <div class="${swalClasses.radio}"></div>
  641. <label class="${swalClasses.checkbox}">
  642. <input type="checkbox" id="${swalClasses.checkbox}" />
  643. <span class="${swalClasses.label}"></span>
  644. </label>
  645. <textarea class="${swalClasses.textarea}" id="${swalClasses.textarea}"></textarea>
  646. <div class="${swalClasses['validation-message']}" id="${swalClasses['validation-message']}"></div>
  647. <div class="${swalClasses.actions}">
  648. <div class="${swalClasses.loader}"></div>
  649. <button type="button" class="${swalClasses.confirm}"></button>
  650. <button type="button" class="${swalClasses.deny}"></button>
  651. <button type="button" class="${swalClasses.cancel}"></button>
  652. </div>
  653. <div class="${swalClasses.footer}"></div>
  654. <div class="${swalClasses['timer-progress-bar-container']}">
  655. <div class="${swalClasses['timer-progress-bar']}"></div>
  656. </div>
  657. </div>
  658. `.replace(/(^|\n)\s*/g, '');
  659. /**
  660. * @returns {boolean}
  661. */
  662. const resetOldContainer = () => {
  663. const oldContainer = getContainer();
  664. if (!oldContainer) {
  665. return false;
  666. }
  667. oldContainer.remove();
  668. removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
  669. return true;
  670. };
  671. const resetValidationMessage$1 = () => {
  672. globalState.currentInstance.resetValidationMessage();
  673. };
  674. const addInputChangeListeners = () => {
  675. const popup = getPopup();
  676. const input = getDirectChildByClass(popup, swalClasses.input);
  677. const file = getDirectChildByClass(popup, swalClasses.file);
  678. /** @type {HTMLInputElement} */
  679. const range = popup.querySelector(`.${swalClasses.range} input`);
  680. /** @type {HTMLOutputElement} */
  681. const rangeOutput = popup.querySelector(`.${swalClasses.range} output`);
  682. const select = getDirectChildByClass(popup, swalClasses.select);
  683. /** @type {HTMLInputElement} */
  684. const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`);
  685. const textarea = getDirectChildByClass(popup, swalClasses.textarea);
  686. input.oninput = resetValidationMessage$1;
  687. file.onchange = resetValidationMessage$1;
  688. select.onchange = resetValidationMessage$1;
  689. checkbox.onchange = resetValidationMessage$1;
  690. textarea.oninput = resetValidationMessage$1;
  691. range.oninput = () => {
  692. resetValidationMessage$1();
  693. rangeOutput.value = range.value;
  694. };
  695. range.onchange = () => {
  696. resetValidationMessage$1();
  697. rangeOutput.value = range.value;
  698. };
  699. };
  700. /**
  701. * @param {string | HTMLElement} target
  702. * @returns {HTMLElement}
  703. */
  704. const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;
  705. /**
  706. * @param {SweetAlertOptions} params
  707. */
  708. const setupAccessibility = params => {
  709. const popup = getPopup();
  710. popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
  711. popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
  712. if (!params.toast) {
  713. popup.setAttribute('aria-modal', 'true');
  714. }
  715. };
  716. /**
  717. * @param {HTMLElement} targetElement
  718. */
  719. const setupRTL = targetElement => {
  720. if (window.getComputedStyle(targetElement).direction === 'rtl') {
  721. addClass(getContainer(), swalClasses.rtl);
  722. }
  723. };
  724. /**
  725. * Add modal + backdrop + no-war message for Russians to DOM
  726. *
  727. * @param {SweetAlertOptions} params
  728. */
  729. const init = params => {
  730. // Clean up the old popup container if it exists
  731. const oldContainerExisted = resetOldContainer();
  732. if (isNodeEnv()) {
  733. error('SweetAlert2 requires document to initialize');
  734. return;
  735. }
  736. const container = document.createElement('div');
  737. container.className = swalClasses.container;
  738. if (oldContainerExisted) {
  739. addClass(container, swalClasses['no-transition']);
  740. }
  741. setInnerHtml(container, sweetHTML);
  742. const targetElement = getTarget(params.target);
  743. targetElement.appendChild(container);
  744. setupAccessibility(params);
  745. setupRTL(targetElement);
  746. addInputChangeListeners();
  747. };
  748. /**
  749. * @param {HTMLElement | object | string} param
  750. * @param {HTMLElement} target
  751. */
  752. const parseHtmlToContainer = (param, target) => {
  753. // DOM element
  754. if (param instanceof HTMLElement) {
  755. target.appendChild(param);
  756. }
  757. // Object
  758. else if (typeof param === 'object') {
  759. handleObject(param, target);
  760. }
  761. // Plain string
  762. else if (param) {
  763. setInnerHtml(target, param);
  764. }
  765. };
  766. /**
  767. * @param {any} param
  768. * @param {HTMLElement} target
  769. */
  770. const handleObject = (param, target) => {
  771. // JQuery element(s)
  772. if (param.jquery) {
  773. handleJqueryElem(target, param);
  774. }
  775. // For other objects use their string representation
  776. else {
  777. setInnerHtml(target, param.toString());
  778. }
  779. };
  780. /**
  781. * @param {HTMLElement} target
  782. * @param {any} elem
  783. */
  784. const handleJqueryElem = (target, elem) => {
  785. target.textContent = '';
  786. if (0 in elem) {
  787. for (let i = 0; i in elem; i++) {
  788. target.appendChild(elem[i].cloneNode(true));
  789. }
  790. } else {
  791. target.appendChild(elem.cloneNode(true));
  792. }
  793. };
  794. /**
  795. * @param {SweetAlert} instance
  796. * @param {SweetAlertOptions} params
  797. */
  798. const renderActions = (instance, params) => {
  799. const actions = getActions();
  800. const loader = getLoader();
  801. if (!actions || !loader) {
  802. return;
  803. }
  804. // Actions (buttons) wrapper
  805. if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
  806. hide(actions);
  807. } else {
  808. show(actions);
  809. }
  810. // Custom class
  811. applyCustomClass(actions, params, 'actions');
  812. // Render all the buttons
  813. renderButtons(actions, loader, params);
  814. // Loader
  815. setInnerHtml(loader, params.loaderHtml || '');
  816. applyCustomClass(loader, params, 'loader');
  817. };
  818. /**
  819. * @param {HTMLElement} actions
  820. * @param {HTMLElement} loader
  821. * @param {SweetAlertOptions} params
  822. */
  823. function renderButtons(actions, loader, params) {
  824. const confirmButton = getConfirmButton();
  825. const denyButton = getDenyButton();
  826. const cancelButton = getCancelButton();
  827. if (!confirmButton || !denyButton || !cancelButton) {
  828. return;
  829. }
  830. // Render buttons
  831. renderButton(confirmButton, 'confirm', params);
  832. renderButton(denyButton, 'deny', params);
  833. renderButton(cancelButton, 'cancel', params);
  834. handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
  835. if (params.reverseButtons) {
  836. if (params.toast) {
  837. actions.insertBefore(cancelButton, confirmButton);
  838. actions.insertBefore(denyButton, confirmButton);
  839. } else {
  840. actions.insertBefore(cancelButton, loader);
  841. actions.insertBefore(denyButton, loader);
  842. actions.insertBefore(confirmButton, loader);
  843. }
  844. }
  845. }
  846. /**
  847. * @param {HTMLElement} confirmButton
  848. * @param {HTMLElement} denyButton
  849. * @param {HTMLElement} cancelButton
  850. * @param {SweetAlertOptions} params
  851. */
  852. function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
  853. if (!params.buttonsStyling) {
  854. removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
  855. return;
  856. }
  857. addClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
  858. // Buttons background colors
  859. if (params.confirmButtonColor) {
  860. confirmButton.style.backgroundColor = params.confirmButtonColor;
  861. addClass(confirmButton, swalClasses['default-outline']);
  862. }
  863. if (params.denyButtonColor) {
  864. denyButton.style.backgroundColor = params.denyButtonColor;
  865. addClass(denyButton, swalClasses['default-outline']);
  866. }
  867. if (params.cancelButtonColor) {
  868. cancelButton.style.backgroundColor = params.cancelButtonColor;
  869. addClass(cancelButton, swalClasses['default-outline']);
  870. }
  871. }
  872. /**
  873. * @param {HTMLElement} button
  874. * @param {'confirm' | 'deny' | 'cancel'} buttonType
  875. * @param {SweetAlertOptions} params
  876. */
  877. function renderButton(button, buttonType, params) {
  878. const buttonName = /** @type {'Confirm' | 'Deny' | 'Cancel'} */capitalizeFirstLetter(buttonType);
  879. toggle(button, params[`show${buttonName}Button`], 'inline-block');
  880. setInnerHtml(button, params[`${buttonType}ButtonText`] || ''); // Set caption text
  881. button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`] || ''); // ARIA label
  882. // Add buttons custom classes
  883. button.className = swalClasses[buttonType];
  884. applyCustomClass(button, params, `${buttonType}Button`);
  885. }
  886. /**
  887. * @param {SweetAlert} instance
  888. * @param {SweetAlertOptions} params
  889. */
  890. const renderCloseButton = (instance, params) => {
  891. const closeButton = getCloseButton();
  892. if (!closeButton) {
  893. return;
  894. }
  895. setInnerHtml(closeButton, params.closeButtonHtml || '');
  896. // Custom class
  897. applyCustomClass(closeButton, params, 'closeButton');
  898. toggle(closeButton, params.showCloseButton);
  899. closeButton.setAttribute('aria-label', params.closeButtonAriaLabel || '');
  900. };
  901. /**
  902. * @param {SweetAlert} instance
  903. * @param {SweetAlertOptions} params
  904. */
  905. const renderContainer = (instance, params) => {
  906. const container = getContainer();
  907. if (!container) {
  908. return;
  909. }
  910. handleBackdropParam(container, params.backdrop);
  911. handlePositionParam(container, params.position);
  912. handleGrowParam(container, params.grow);
  913. // Custom class
  914. applyCustomClass(container, params, 'container');
  915. };
  916. /**
  917. * @param {HTMLElement} container
  918. * @param {SweetAlertOptions['backdrop']} backdrop
  919. */
  920. function handleBackdropParam(container, backdrop) {
  921. if (typeof backdrop === 'string') {
  922. container.style.background = backdrop;
  923. } else if (!backdrop) {
  924. addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
  925. }
  926. }
  927. /**
  928. * @param {HTMLElement} container
  929. * @param {SweetAlertOptions['position']} position
  930. */
  931. function handlePositionParam(container, position) {
  932. if (!position) {
  933. return;
  934. }
  935. if (position in swalClasses) {
  936. addClass(container, swalClasses[position]);
  937. } else {
  938. warn('The "position" parameter is not valid, defaulting to "center"');
  939. addClass(container, swalClasses.center);
  940. }
  941. }
  942. /**
  943. * @param {HTMLElement} container
  944. * @param {SweetAlertOptions['grow']} grow
  945. */
  946. function handleGrowParam(container, grow) {
  947. if (!grow) {
  948. return;
  949. }
  950. addClass(container, swalClasses[`grow-${grow}`]);
  951. }
  952. /**
  953. * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
  954. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  955. * This is the approach that Babel will probably take to implement private methods/fields
  956. * https://github.com/tc39/proposal-private-methods
  957. * https://github.com/babel/babel/pull/7555
  958. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  959. * then we can use that language feature.
  960. */
  961. var privateProps = {
  962. innerParams: new WeakMap(),
  963. domCache: new WeakMap()
  964. };
  965. /// <reference path="../../../../sweetalert2.d.ts"/>
  966. /** @type {InputClass[]} */
  967. const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
  968. /**
  969. * @param {SweetAlert} instance
  970. * @param {SweetAlertOptions} params
  971. */
  972. const renderInput = (instance, params) => {
  973. const popup = getPopup();
  974. if (!popup) {
  975. return;
  976. }
  977. const innerParams = privateProps.innerParams.get(instance);
  978. const rerender = !innerParams || params.input !== innerParams.input;
  979. inputClasses.forEach(inputClass => {
  980. const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]);
  981. if (!inputContainer) {
  982. return;
  983. }
  984. // set attributes
  985. setAttributes(inputClass, params.inputAttributes);
  986. // set class
  987. inputContainer.className = swalClasses[inputClass];
  988. if (rerender) {
  989. hide(inputContainer);
  990. }
  991. });
  992. if (params.input) {
  993. if (rerender) {
  994. showInput(params);
  995. }
  996. // set custom class
  997. setCustomClass(params);
  998. }
  999. };
  1000. /**
  1001. * @param {SweetAlertOptions} params
  1002. */
  1003. const showInput = params => {
  1004. if (!params.input) {
  1005. return;
  1006. }
  1007. if (!renderInputType[params.input]) {
  1008. error(`Unexpected type of input! Expected ${Object.keys(renderInputType).join(' | ')}, got "${params.input}"`);
  1009. return;
  1010. }
  1011. const inputContainer = getInputContainer(params.input);
  1012. if (!inputContainer) {
  1013. return;
  1014. }
  1015. const input = renderInputType[params.input](inputContainer, params);
  1016. show(inputContainer);
  1017. // input autofocus
  1018. if (params.inputAutoFocus) {
  1019. setTimeout(() => {
  1020. focusInput(input);
  1021. });
  1022. }
  1023. };
  1024. /**
  1025. * @param {HTMLInputElement} input
  1026. */
  1027. const removeAttributes = input => {
  1028. for (let i = 0; i < input.attributes.length; i++) {
  1029. const attrName = input.attributes[i].name;
  1030. if (!['id', 'type', 'value', 'style'].includes(attrName)) {
  1031. input.removeAttribute(attrName);
  1032. }
  1033. }
  1034. };
  1035. /**
  1036. * @param {InputClass} inputClass
  1037. * @param {SweetAlertOptions['inputAttributes']} inputAttributes
  1038. */
  1039. const setAttributes = (inputClass, inputAttributes) => {
  1040. const popup = getPopup();
  1041. if (!popup) {
  1042. return;
  1043. }
  1044. const input = getInput$1(popup, inputClass);
  1045. if (!input) {
  1046. return;
  1047. }
  1048. removeAttributes(input);
  1049. for (const attr in inputAttributes) {
  1050. input.setAttribute(attr, inputAttributes[attr]);
  1051. }
  1052. };
  1053. /**
  1054. * @param {SweetAlertOptions} params
  1055. */
  1056. const setCustomClass = params => {
  1057. if (!params.input) {
  1058. return;
  1059. }
  1060. const inputContainer = getInputContainer(params.input);
  1061. if (inputContainer) {
  1062. applyCustomClass(inputContainer, params, 'input');
  1063. }
  1064. };
  1065. /**
  1066. * @param {HTMLInputElement | HTMLTextAreaElement} input
  1067. * @param {SweetAlertOptions} params
  1068. */
  1069. const setInputPlaceholder = (input, params) => {
  1070. if (!input.placeholder && params.inputPlaceholder) {
  1071. input.placeholder = params.inputPlaceholder;
  1072. }
  1073. };
  1074. /**
  1075. * @param {Input} input
  1076. * @param {Input} prependTo
  1077. * @param {SweetAlertOptions} params
  1078. */
  1079. const setInputLabel = (input, prependTo, params) => {
  1080. if (params.inputLabel) {
  1081. const label = document.createElement('label');
  1082. const labelClass = swalClasses['input-label'];
  1083. label.setAttribute('for', input.id);
  1084. label.className = labelClass;
  1085. if (typeof params.customClass === 'object') {
  1086. addClass(label, params.customClass.inputLabel);
  1087. }
  1088. label.innerText = params.inputLabel;
  1089. prependTo.insertAdjacentElement('beforebegin', label);
  1090. }
  1091. };
  1092. /**
  1093. * @param {SweetAlertInput} inputType
  1094. * @returns {HTMLElement | undefined}
  1095. */
  1096. const getInputContainer = inputType => {
  1097. const popup = getPopup();
  1098. if (!popup) {
  1099. return;
  1100. }
  1101. return getDirectChildByClass(popup, swalClasses[(/** @type {SwalClass} */inputType)] || swalClasses.input);
  1102. };
  1103. /**
  1104. * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input
  1105. * @param {SweetAlertOptions['inputValue']} inputValue
  1106. */
  1107. const checkAndSetInputValue = (input, inputValue) => {
  1108. if (['string', 'number'].includes(typeof inputValue)) {
  1109. input.value = `${inputValue}`;
  1110. } else if (!isPromise(inputValue)) {
  1111. warn(`Unexpected type of inputValue! Expected "string", "number" or "Promise", got "${typeof inputValue}"`);
  1112. }
  1113. };
  1114. /** @type {Record<SweetAlertInput, (input: Input | HTMLElement, params: SweetAlertOptions) => Input>} */
  1115. const renderInputType = {};
  1116. /**
  1117. * @param {HTMLInputElement} input
  1118. * @param {SweetAlertOptions} params
  1119. * @returns {HTMLInputElement}
  1120. */
  1121. renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = renderInputType.search = renderInputType.date = renderInputType['datetime-local'] = renderInputType.time = renderInputType.week = renderInputType.month = /** @type {(input: Input | HTMLElement, params: SweetAlertOptions) => Input} */
  1122. (input, params) => {
  1123. checkAndSetInputValue(input, params.inputValue);
  1124. setInputLabel(input, input, params);
  1125. setInputPlaceholder(input, params);
  1126. input.type = params.input;
  1127. return input;
  1128. };
  1129. /**
  1130. * @param {HTMLInputElement} input
  1131. * @param {SweetAlertOptions} params
  1132. * @returns {HTMLInputElement}
  1133. */
  1134. renderInputType.file = (input, params) => {
  1135. setInputLabel(input, input, params);
  1136. setInputPlaceholder(input, params);
  1137. return input;
  1138. };
  1139. /**
  1140. * @param {HTMLInputElement} range
  1141. * @param {SweetAlertOptions} params
  1142. * @returns {HTMLInputElement}
  1143. */
  1144. renderInputType.range = (range, params) => {
  1145. const rangeInput = range.querySelector('input');
  1146. const rangeOutput = range.querySelector('output');
  1147. checkAndSetInputValue(rangeInput, params.inputValue);
  1148. rangeInput.type = params.input;
  1149. checkAndSetInputValue(rangeOutput, params.inputValue);
  1150. setInputLabel(rangeInput, range, params);
  1151. return range;
  1152. };
  1153. /**
  1154. * @param {HTMLSelectElement} select
  1155. * @param {SweetAlertOptions} params
  1156. * @returns {HTMLSelectElement}
  1157. */
  1158. renderInputType.select = (select, params) => {
  1159. select.textContent = '';
  1160. if (params.inputPlaceholder) {
  1161. const placeholder = document.createElement('option');
  1162. setInnerHtml(placeholder, params.inputPlaceholder);
  1163. placeholder.value = '';
  1164. placeholder.disabled = true;
  1165. placeholder.selected = true;
  1166. select.appendChild(placeholder);
  1167. }
  1168. setInputLabel(select, select, params);
  1169. return select;
  1170. };
  1171. /**
  1172. * @param {HTMLInputElement} radio
  1173. * @returns {HTMLInputElement}
  1174. */
  1175. renderInputType.radio = radio => {
  1176. radio.textContent = '';
  1177. return radio;
  1178. };
  1179. /**
  1180. * @param {HTMLLabelElement} checkboxContainer
  1181. * @param {SweetAlertOptions} params
  1182. * @returns {HTMLInputElement}
  1183. */
  1184. renderInputType.checkbox = (checkboxContainer, params) => {
  1185. const checkbox = getInput$1(getPopup(), 'checkbox');
  1186. checkbox.value = '1';
  1187. checkbox.checked = Boolean(params.inputValue);
  1188. const label = checkboxContainer.querySelector('span');
  1189. setInnerHtml(label, params.inputPlaceholder || params.inputLabel);
  1190. return checkbox;
  1191. };
  1192. /**
  1193. * @param {HTMLTextAreaElement} textarea
  1194. * @param {SweetAlertOptions} params
  1195. * @returns {HTMLTextAreaElement}
  1196. */
  1197. renderInputType.textarea = (textarea, params) => {
  1198. checkAndSetInputValue(textarea, params.inputValue);
  1199. setInputPlaceholder(textarea, params);
  1200. setInputLabel(textarea, textarea, params);
  1201. /**
  1202. * @param {HTMLElement} el
  1203. * @returns {number}
  1204. */
  1205. const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);
  1206. // https://github.com/sweetalert2/sweetalert2/issues/2291
  1207. setTimeout(() => {
  1208. // https://github.com/sweetalert2/sweetalert2/issues/1699
  1209. if ('MutationObserver' in window) {
  1210. const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
  1211. const textareaResizeHandler = () => {
  1212. // check if texarea is still in document (i.e. popup wasn't closed in the meantime)
  1213. if (!document.body.contains(textarea)) {
  1214. return;
  1215. }
  1216. const textareaWidth = textarea.offsetWidth + getMargin(textarea);
  1217. if (textareaWidth > initialPopupWidth) {
  1218. getPopup().style.width = `${textareaWidth}px`;
  1219. } else {
  1220. applyNumericalStyle(getPopup(), 'width', params.width);
  1221. }
  1222. };
  1223. new MutationObserver(textareaResizeHandler).observe(textarea, {
  1224. attributes: true,
  1225. attributeFilter: ['style']
  1226. });
  1227. }
  1228. });
  1229. return textarea;
  1230. };
  1231. /**
  1232. * @param {SweetAlert} instance
  1233. * @param {SweetAlertOptions} params
  1234. */
  1235. const renderContent = (instance, params) => {
  1236. const htmlContainer = getHtmlContainer();
  1237. if (!htmlContainer) {
  1238. return;
  1239. }
  1240. showWhenInnerHtmlPresent(htmlContainer);
  1241. applyCustomClass(htmlContainer, params, 'htmlContainer');
  1242. // Content as HTML
  1243. if (params.html) {
  1244. parseHtmlToContainer(params.html, htmlContainer);
  1245. show(htmlContainer, 'block');
  1246. }
  1247. // Content as plain text
  1248. else if (params.text) {
  1249. htmlContainer.textContent = params.text;
  1250. show(htmlContainer, 'block');
  1251. }
  1252. // No content
  1253. else {
  1254. hide(htmlContainer);
  1255. }
  1256. renderInput(instance, params);
  1257. };
  1258. /**
  1259. * @param {SweetAlert} instance
  1260. * @param {SweetAlertOptions} params
  1261. */
  1262. const renderFooter = (instance, params) => {
  1263. const footer = getFooter();
  1264. if (!footer) {
  1265. return;
  1266. }
  1267. showWhenInnerHtmlPresent(footer);
  1268. toggle(footer, params.footer, 'block');
  1269. if (params.footer) {
  1270. parseHtmlToContainer(params.footer, footer);
  1271. }
  1272. // Custom class
  1273. applyCustomClass(footer, params, 'footer');
  1274. };
  1275. /**
  1276. * @param {SweetAlert} instance
  1277. * @param {SweetAlertOptions} params
  1278. */
  1279. const renderIcon = (instance, params) => {
  1280. const innerParams = privateProps.innerParams.get(instance);
  1281. const icon = getIcon();
  1282. if (!icon) {
  1283. return;
  1284. }
  1285. // if the given icon already rendered, apply the styling without re-rendering the icon
  1286. if (innerParams && params.icon === innerParams.icon) {
  1287. // Custom or default content
  1288. setContent(icon, params);
  1289. applyStyles(icon, params);
  1290. return;
  1291. }
  1292. if (!params.icon && !params.iconHtml) {
  1293. hide(icon);
  1294. return;
  1295. }
  1296. if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
  1297. error(`Unknown icon! Expected "success", "error", "warning", "info" or "question", got "${params.icon}"`);
  1298. hide(icon);
  1299. return;
  1300. }
  1301. show(icon);
  1302. // Custom or default content
  1303. setContent(icon, params);
  1304. applyStyles(icon, params);
  1305. // Animate icon
  1306. addClass(icon, params.showClass && params.showClass.icon);
  1307. };
  1308. /**
  1309. * @param {HTMLElement} icon
  1310. * @param {SweetAlertOptions} params
  1311. */
  1312. const applyStyles = (icon, params) => {
  1313. for (const [iconType, iconClassName] of Object.entries(iconTypes)) {
  1314. if (params.icon !== iconType) {
  1315. removeClass(icon, iconClassName);
  1316. }
  1317. }
  1318. addClass(icon, params.icon && iconTypes[params.icon]);
  1319. // Icon color
  1320. setColor(icon, params);
  1321. // Success icon background color
  1322. adjustSuccessIconBackgroundColor();
  1323. // Custom class
  1324. applyCustomClass(icon, params, 'icon');
  1325. };
  1326. // Adjust success icon background color to match the popup background color
  1327. const adjustSuccessIconBackgroundColor = () => {
  1328. const popup = getPopup();
  1329. if (!popup) {
  1330. return;
  1331. }
  1332. const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
  1333. /** @type {NodeListOf<HTMLElement>} */
  1334. const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
  1335. for (let i = 0; i < successIconParts.length; i++) {
  1336. successIconParts[i].style.backgroundColor = popupBackgroundColor;
  1337. }
  1338. };
  1339. const successIconHtml = `
  1340. <div class="swal2-success-circular-line-left"></div>
  1341. <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>
  1342. <div class="swal2-success-ring"></div> <div class="swal2-success-fix"></div>
  1343. <div class="swal2-success-circular-line-right"></div>
  1344. `;
  1345. const errorIconHtml = `
  1346. <span class="swal2-x-mark">
  1347. <span class="swal2-x-mark-line-left"></span>
  1348. <span class="swal2-x-mark-line-right"></span>
  1349. </span>
  1350. `;
  1351. /**
  1352. * @param {HTMLElement} icon
  1353. * @param {SweetAlertOptions} params
  1354. */
  1355. const setContent = (icon, params) => {
  1356. if (!params.icon && !params.iconHtml) {
  1357. return;
  1358. }
  1359. let oldContent = icon.innerHTML;
  1360. let newContent = '';
  1361. if (params.iconHtml) {
  1362. newContent = iconContent(params.iconHtml);
  1363. } else if (params.icon === 'success') {
  1364. newContent = successIconHtml;
  1365. oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor()
  1366. } else if (params.icon === 'error') {
  1367. newContent = errorIconHtml;
  1368. } else if (params.icon) {
  1369. const defaultIconHtml = {
  1370. question: '?',
  1371. warning: '!',
  1372. info: 'i'
  1373. };
  1374. newContent = iconContent(defaultIconHtml[params.icon]);
  1375. }
  1376. if (oldContent.trim() !== newContent.trim()) {
  1377. setInnerHtml(icon, newContent);
  1378. }
  1379. };
  1380. /**
  1381. * @param {HTMLElement} icon
  1382. * @param {SweetAlertOptions} params
  1383. */
  1384. const setColor = (icon, params) => {
  1385. if (!params.iconColor) {
  1386. return;
  1387. }
  1388. icon.style.color = params.iconColor;
  1389. icon.style.borderColor = params.iconColor;
  1390. for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
  1391. setStyle(icon, sel, 'background-color', params.iconColor);
  1392. }
  1393. setStyle(icon, '.swal2-success-ring', 'border-color', params.iconColor);
  1394. };
  1395. /**
  1396. * @param {string} content
  1397. * @returns {string}
  1398. */
  1399. const iconContent = content => `<div class="${swalClasses['icon-content']}">${content}</div>`;
  1400. /**
  1401. * @param {SweetAlert} instance
  1402. * @param {SweetAlertOptions} params
  1403. */
  1404. const renderImage = (instance, params) => {
  1405. const image = getImage();
  1406. if (!image) {
  1407. return;
  1408. }
  1409. if (!params.imageUrl) {
  1410. hide(image);
  1411. return;
  1412. }
  1413. show(image, '');
  1414. // Src, alt
  1415. image.setAttribute('src', params.imageUrl);
  1416. image.setAttribute('alt', params.imageAlt || '');
  1417. // Width, height
  1418. applyNumericalStyle(image, 'width', params.imageWidth);
  1419. applyNumericalStyle(image, 'height', params.imageHeight);
  1420. // Class
  1421. image.className = swalClasses.image;
  1422. applyCustomClass(image, params, 'image');
  1423. };
  1424. /**
  1425. * @param {SweetAlert} instance
  1426. * @param {SweetAlertOptions} params
  1427. */
  1428. const renderPopup = (instance, params) => {
  1429. const container = getContainer();
  1430. const popup = getPopup();
  1431. if (!container || !popup) {
  1432. return;
  1433. }
  1434. // Width
  1435. // https://github.com/sweetalert2/sweetalert2/issues/2170
  1436. if (params.toast) {
  1437. applyNumericalStyle(container, 'width', params.width);
  1438. popup.style.width = '100%';
  1439. const loader = getLoader();
  1440. if (loader) {
  1441. popup.insertBefore(loader, getIcon());
  1442. }
  1443. } else {
  1444. applyNumericalStyle(popup, 'width', params.width);
  1445. }
  1446. // Padding
  1447. applyNumericalStyle(popup, 'padding', params.padding);
  1448. // Color
  1449. if (params.color) {
  1450. popup.style.color = params.color;
  1451. }
  1452. // Background
  1453. if (params.background) {
  1454. popup.style.background = params.background;
  1455. }
  1456. hide(getValidationMessage());
  1457. // Classes
  1458. addClasses$1(popup, params);
  1459. };
  1460. /**
  1461. * @param {HTMLElement} popup
  1462. * @param {SweetAlertOptions} params
  1463. */
  1464. const addClasses$1 = (popup, params) => {
  1465. const showClass = params.showClass || {};
  1466. // Default Class + showClass when updating Swal.update({})
  1467. popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? showClass.popup : ''}`;
  1468. if (params.toast) {
  1469. addClass([document.documentElement, document.body], swalClasses['toast-shown']);
  1470. addClass(popup, swalClasses.toast);
  1471. } else {
  1472. addClass(popup, swalClasses.modal);
  1473. }
  1474. // Custom class
  1475. applyCustomClass(popup, params, 'popup');
  1476. // TODO: remove in the next major
  1477. if (typeof params.customClass === 'string') {
  1478. addClass(popup, params.customClass);
  1479. }
  1480. // Icon class (#1842)
  1481. if (params.icon) {
  1482. addClass(popup, swalClasses[`icon-${params.icon}`]);
  1483. }
  1484. };
  1485. /**
  1486. * @param {SweetAlert} instance
  1487. * @param {SweetAlertOptions} params
  1488. */
  1489. const renderProgressSteps = (instance, params) => {
  1490. const progressStepsContainer = getProgressSteps();
  1491. if (!progressStepsContainer) {
  1492. return;
  1493. }
  1494. const {
  1495. progressSteps,
  1496. currentProgressStep
  1497. } = params;
  1498. if (!progressSteps || progressSteps.length === 0 || currentProgressStep === undefined) {
  1499. hide(progressStepsContainer);
  1500. return;
  1501. }
  1502. show(progressStepsContainer);
  1503. progressStepsContainer.textContent = '';
  1504. if (currentProgressStep >= progressSteps.length) {
  1505. warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
  1506. }
  1507. progressSteps.forEach((step, index) => {
  1508. const stepEl = createStepElement(step);
  1509. progressStepsContainer.appendChild(stepEl);
  1510. if (index === currentProgressStep) {
  1511. addClass(stepEl, swalClasses['active-progress-step']);
  1512. }
  1513. if (index !== progressSteps.length - 1) {
  1514. const lineEl = createLineElement(params);
  1515. progressStepsContainer.appendChild(lineEl);
  1516. }
  1517. });
  1518. };
  1519. /**
  1520. * @param {string} step
  1521. * @returns {HTMLLIElement}
  1522. */
  1523. const createStepElement = step => {
  1524. const stepEl = document.createElement('li');
  1525. addClass(stepEl, swalClasses['progress-step']);
  1526. setInnerHtml(stepEl, step);
  1527. return stepEl;
  1528. };
  1529. /**
  1530. * @param {SweetAlertOptions} params
  1531. * @returns {HTMLLIElement}
  1532. */
  1533. const createLineElement = params => {
  1534. const lineEl = document.createElement('li');
  1535. addClass(lineEl, swalClasses['progress-step-line']);
  1536. if (params.progressStepsDistance) {
  1537. applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);
  1538. }
  1539. return lineEl;
  1540. };
  1541. /**
  1542. * @param {SweetAlert} instance
  1543. * @param {SweetAlertOptions} params
  1544. */
  1545. const renderTitle = (instance, params) => {
  1546. const title = getTitle();
  1547. if (!title) {
  1548. return;
  1549. }
  1550. showWhenInnerHtmlPresent(title);
  1551. toggle(title, params.title || params.titleText, 'block');
  1552. if (params.title) {
  1553. parseHtmlToContainer(params.title, title);
  1554. }
  1555. if (params.titleText) {
  1556. title.innerText = params.titleText;
  1557. }
  1558. // Custom class
  1559. applyCustomClass(title, params, 'title');
  1560. };
  1561. /**
  1562. * @param {SweetAlert} instance
  1563. * @param {SweetAlertOptions} params
  1564. */
  1565. const render = (instance, params) => {
  1566. renderPopup(instance, params);
  1567. renderContainer(instance, params);
  1568. renderProgressSteps(instance, params);
  1569. renderIcon(instance, params);
  1570. renderImage(instance, params);
  1571. renderTitle(instance, params);
  1572. renderCloseButton(instance, params);
  1573. renderContent(instance, params);
  1574. renderActions(instance, params);
  1575. renderFooter(instance, params);
  1576. const popup = getPopup();
  1577. if (typeof params.didRender === 'function' && popup) {
  1578. params.didRender(popup);
  1579. }
  1580. globalState.eventEmitter.emit('didRender', popup);
  1581. };
  1582. /*
  1583. * Global function to determine if SweetAlert2 popup is shown
  1584. */
  1585. const isVisible = () => {
  1586. return isVisible$1(getPopup());
  1587. };
  1588. /*
  1589. * Global function to click 'Confirm' button
  1590. */
  1591. const clickConfirm = () => {
  1592. var _dom$getConfirmButton;
  1593. return (_dom$getConfirmButton = getConfirmButton()) === null || _dom$getConfirmButton === void 0 ? void 0 : _dom$getConfirmButton.click();
  1594. };
  1595. /*
  1596. * Global function to click 'Deny' button
  1597. */
  1598. const clickDeny = () => {
  1599. var _dom$getDenyButton;
  1600. return (_dom$getDenyButton = getDenyButton()) === null || _dom$getDenyButton === void 0 ? void 0 : _dom$getDenyButton.click();
  1601. };
  1602. /*
  1603. * Global function to click 'Cancel' button
  1604. */
  1605. const clickCancel = () => {
  1606. var _dom$getCancelButton;
  1607. return (_dom$getCancelButton = getCancelButton()) === null || _dom$getCancelButton === void 0 ? void 0 : _dom$getCancelButton.click();
  1608. };
  1609. /** @typedef {'cancel' | 'backdrop' | 'close' | 'esc' | 'timer'} DismissReason */
  1610. /** @type {Record<DismissReason, DismissReason>} */
  1611. const DismissReason = Object.freeze({
  1612. cancel: 'cancel',
  1613. backdrop: 'backdrop',
  1614. close: 'close',
  1615. esc: 'esc',
  1616. timer: 'timer'
  1617. });
  1618. /**
  1619. * @param {GlobalState} globalState
  1620. */
  1621. const removeKeydownHandler = globalState => {
  1622. if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
  1623. globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
  1624. capture: globalState.keydownListenerCapture
  1625. });
  1626. globalState.keydownHandlerAdded = false;
  1627. }
  1628. };
  1629. /**
  1630. * @param {GlobalState} globalState
  1631. * @param {SweetAlertOptions} innerParams
  1632. * @param {*} dismissWith
  1633. */
  1634. const addKeydownHandler = (globalState, innerParams, dismissWith) => {
  1635. removeKeydownHandler(globalState);
  1636. if (!innerParams.toast) {
  1637. globalState.keydownHandler = e => keydownHandler(innerParams, e, dismissWith);
  1638. globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
  1639. globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
  1640. globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
  1641. capture: globalState.keydownListenerCapture
  1642. });
  1643. globalState.keydownHandlerAdded = true;
  1644. }
  1645. };
  1646. /**
  1647. * @param {number} index
  1648. * @param {number} increment
  1649. */
  1650. const setFocus = (index, increment) => {
  1651. var _dom$getPopup;
  1652. const focusableElements = getFocusableElements();
  1653. // search for visible elements and select the next possible match
  1654. if (focusableElements.length) {
  1655. index = index + increment;
  1656. // rollover to first item
  1657. if (index === focusableElements.length) {
  1658. index = 0;
  1659. // go to last item
  1660. } else if (index === -1) {
  1661. index = focusableElements.length - 1;
  1662. }
  1663. focusableElements[index].focus();
  1664. return;
  1665. }
  1666. // no visible focusable elements, focus the popup
  1667. (_dom$getPopup = getPopup()) === null || _dom$getPopup === void 0 || _dom$getPopup.focus();
  1668. };
  1669. const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
  1670. const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
  1671. /**
  1672. * @param {SweetAlertOptions} innerParams
  1673. * @param {KeyboardEvent} event
  1674. * @param {Function} dismissWith
  1675. */
  1676. const keydownHandler = (innerParams, event, dismissWith) => {
  1677. if (!innerParams) {
  1678. return; // This instance has already been destroyed
  1679. }
  1680. // Ignore keydown during IME composition
  1681. // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition
  1682. // https://github.com/sweetalert2/sweetalert2/issues/720
  1683. // https://github.com/sweetalert2/sweetalert2/issues/2406
  1684. if (event.isComposing || event.keyCode === 229) {
  1685. return;
  1686. }
  1687. if (innerParams.stopKeydownPropagation) {
  1688. event.stopPropagation();
  1689. }
  1690. // ENTER
  1691. if (event.key === 'Enter') {
  1692. handleEnter(event, innerParams);
  1693. }
  1694. // TAB
  1695. else if (event.key === 'Tab') {
  1696. handleTab(event);
  1697. }
  1698. // ARROWS - switch focus between buttons
  1699. else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) {
  1700. handleArrows(event.key);
  1701. }
  1702. // ESC
  1703. else if (event.key === 'Escape') {
  1704. handleEsc(event, innerParams, dismissWith);
  1705. }
  1706. };
  1707. /**
  1708. * @param {KeyboardEvent} event
  1709. * @param {SweetAlertOptions} innerParams
  1710. */
  1711. const handleEnter = (event, innerParams) => {
  1712. // https://github.com/sweetalert2/sweetalert2/issues/2386
  1713. if (!callIfFunction(innerParams.allowEnterKey)) {
  1714. return;
  1715. }
  1716. const input = getInput$1(getPopup(), innerParams.input);
  1717. if (event.target && input && event.target instanceof HTMLElement && event.target.outerHTML === input.outerHTML) {
  1718. if (['textarea', 'file'].includes(innerParams.input)) {
  1719. return; // do not submit
  1720. }
  1721. clickConfirm();
  1722. event.preventDefault();
  1723. }
  1724. };
  1725. /**
  1726. * @param {KeyboardEvent} event
  1727. */
  1728. const handleTab = event => {
  1729. const targetElement = event.target;
  1730. const focusableElements = getFocusableElements();
  1731. let btnIndex = -1;
  1732. for (let i = 0; i < focusableElements.length; i++) {
  1733. if (targetElement === focusableElements[i]) {
  1734. btnIndex = i;
  1735. break;
  1736. }
  1737. }
  1738. // Cycle to the next button
  1739. if (!event.shiftKey) {
  1740. setFocus(btnIndex, 1);
  1741. }
  1742. // Cycle to the prev button
  1743. else {
  1744. setFocus(btnIndex, -1);
  1745. }
  1746. event.stopPropagation();
  1747. event.preventDefault();
  1748. };
  1749. /**
  1750. * @param {string} key
  1751. */
  1752. const handleArrows = key => {
  1753. const actions = getActions();
  1754. const confirmButton = getConfirmButton();
  1755. const denyButton = getDenyButton();
  1756. const cancelButton = getCancelButton();
  1757. if (!actions || !confirmButton || !denyButton || !cancelButton) {
  1758. return;
  1759. }
  1760. /** @type HTMLElement[] */
  1761. const buttons = [confirmButton, denyButton, cancelButton];
  1762. if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) {
  1763. return;
  1764. }
  1765. const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
  1766. let buttonToFocus = document.activeElement;
  1767. if (!buttonToFocus) {
  1768. return;
  1769. }
  1770. for (let i = 0; i < actions.children.length; i++) {
  1771. buttonToFocus = buttonToFocus[sibling];
  1772. if (!buttonToFocus) {
  1773. return;
  1774. }
  1775. if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) {
  1776. break;
  1777. }
  1778. }
  1779. if (buttonToFocus instanceof HTMLButtonElement) {
  1780. buttonToFocus.focus();
  1781. }
  1782. };
  1783. /**
  1784. * @param {KeyboardEvent} event
  1785. * @param {SweetAlertOptions} innerParams
  1786. * @param {Function} dismissWith
  1787. */
  1788. const handleEsc = (event, innerParams, dismissWith) => {
  1789. if (callIfFunction(innerParams.allowEscapeKey)) {
  1790. event.preventDefault();
  1791. dismissWith(DismissReason.esc);
  1792. }
  1793. };
  1794. /**
  1795. * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
  1796. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  1797. * This is the approach that Babel will probably take to implement private methods/fields
  1798. * https://github.com/tc39/proposal-private-methods
  1799. * https://github.com/babel/babel/pull/7555
  1800. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  1801. * then we can use that language feature.
  1802. */
  1803. var privateMethods = {
  1804. swalPromiseResolve: new WeakMap(),
  1805. swalPromiseReject: new WeakMap()
  1806. };
  1807. // From https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/
  1808. // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
  1809. // elements not within the active modal dialog will not be surfaced if a user opens a screen
  1810. // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
  1811. const setAriaHidden = () => {
  1812. const container = getContainer();
  1813. const bodyChildren = Array.from(document.body.children);
  1814. bodyChildren.forEach(el => {
  1815. if (el.contains(container)) {
  1816. return;
  1817. }
  1818. if (el.hasAttribute('aria-hidden')) {
  1819. el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden') || '');
  1820. }
  1821. el.setAttribute('aria-hidden', 'true');
  1822. });
  1823. };
  1824. const unsetAriaHidden = () => {
  1825. const bodyChildren = Array.from(document.body.children);
  1826. bodyChildren.forEach(el => {
  1827. if (el.hasAttribute('data-previous-aria-hidden')) {
  1828. el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden') || '');
  1829. el.removeAttribute('data-previous-aria-hidden');
  1830. } else {
  1831. el.removeAttribute('aria-hidden');
  1832. }
  1833. });
  1834. };
  1835. // @ts-ignore
  1836. const isSafariOrIOS = typeof window !== 'undefined' && !!window.GestureEvent; // true for Safari desktop + all iOS browsers https://stackoverflow.com/a/70585394
  1837. /**
  1838. * Fix iOS scrolling
  1839. * http://stackoverflow.com/q/39626302
  1840. */
  1841. const iOSfix = () => {
  1842. if (isSafariOrIOS && !hasClass(document.body, swalClasses.iosfix)) {
  1843. const offset = document.body.scrollTop;
  1844. document.body.style.top = `${offset * -1}px`;
  1845. addClass(document.body, swalClasses.iosfix);
  1846. lockBodyScroll();
  1847. }
  1848. };
  1849. /**
  1850. * https://github.com/sweetalert2/sweetalert2/issues/1246
  1851. */
  1852. const lockBodyScroll = () => {
  1853. const container = getContainer();
  1854. if (!container) {
  1855. return;
  1856. }
  1857. /** @type {boolean} */
  1858. let preventTouchMove;
  1859. /**
  1860. * @param {TouchEvent} event
  1861. */
  1862. container.ontouchstart = event => {
  1863. preventTouchMove = shouldPreventTouchMove(event);
  1864. };
  1865. /**
  1866. * @param {TouchEvent} event
  1867. */
  1868. container.ontouchmove = event => {
  1869. if (preventTouchMove) {
  1870. event.preventDefault();
  1871. event.stopPropagation();
  1872. }
  1873. };
  1874. };
  1875. /**
  1876. * @param {TouchEvent} event
  1877. * @returns {boolean}
  1878. */
  1879. const shouldPreventTouchMove = event => {
  1880. const target = event.target;
  1881. const container = getContainer();
  1882. const htmlContainer = getHtmlContainer();
  1883. if (!container || !htmlContainer) {
  1884. return false;
  1885. }
  1886. if (isStylus(event) || isZoom(event)) {
  1887. return false;
  1888. }
  1889. if (target === container) {
  1890. return true;
  1891. }
  1892. if (!isScrollable(container) && target instanceof HTMLElement && target.tagName !== 'INPUT' &&
  1893. // #1603
  1894. target.tagName !== 'TEXTAREA' &&
  1895. // #2266
  1896. !(isScrollable(htmlContainer) &&
  1897. // #1944
  1898. htmlContainer.contains(target))) {
  1899. return true;
  1900. }
  1901. return false;
  1902. };
  1903. /**
  1904. * https://github.com/sweetalert2/sweetalert2/issues/1786
  1905. *
  1906. * @param {*} event
  1907. * @returns {boolean}
  1908. */
  1909. const isStylus = event => {
  1910. return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
  1911. };
  1912. /**
  1913. * https://github.com/sweetalert2/sweetalert2/issues/1891
  1914. *
  1915. * @param {TouchEvent} event
  1916. * @returns {boolean}
  1917. */
  1918. const isZoom = event => {
  1919. return event.touches && event.touches.length > 1;
  1920. };
  1921. const undoIOSfix = () => {
  1922. if (hasClass(document.body, swalClasses.iosfix)) {
  1923. const offset = parseInt(document.body.style.top, 10);
  1924. removeClass(document.body, swalClasses.iosfix);
  1925. document.body.style.top = '';
  1926. document.body.scrollTop = offset * -1;
  1927. }
  1928. };
  1929. /**
  1930. * Measure scrollbar width for padding body during modal show/hide
  1931. * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
  1932. *
  1933. * @returns {number}
  1934. */
  1935. const measureScrollbar = () => {
  1936. const scrollDiv = document.createElement('div');
  1937. scrollDiv.className = swalClasses['scrollbar-measure'];
  1938. document.body.appendChild(scrollDiv);
  1939. const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
  1940. document.body.removeChild(scrollDiv);
  1941. return scrollbarWidth;
  1942. };
  1943. /**
  1944. * Remember state in cases where opening and handling a modal will fiddle with it.
  1945. * @type {number | null}
  1946. */
  1947. let previousBodyPadding = null;
  1948. /**
  1949. * @param {string} initialBodyOverflow
  1950. */
  1951. const replaceScrollbarWithPadding = initialBodyOverflow => {
  1952. // for queues, do not do this more than once
  1953. if (previousBodyPadding !== null) {
  1954. return;
  1955. }
  1956. // if the body has overflow
  1957. if (document.body.scrollHeight > window.innerHeight || initialBodyOverflow === 'scroll' // https://github.com/sweetalert2/sweetalert2/issues/2663
  1958. ) {
  1959. // add padding so the content doesn't shift after removal of scrollbar
  1960. previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
  1961. document.body.style.paddingRight = `${previousBodyPadding + measureScrollbar()}px`;
  1962. }
  1963. };
  1964. const undoReplaceScrollbarWithPadding = () => {
  1965. if (previousBodyPadding !== null) {
  1966. document.body.style.paddingRight = `${previousBodyPadding}px`;
  1967. previousBodyPadding = null;
  1968. }
  1969. };
  1970. /**
  1971. * @param {SweetAlert} instance
  1972. * @param {HTMLElement} container
  1973. * @param {boolean} returnFocus
  1974. * @param {Function} didClose
  1975. */
  1976. function removePopupAndResetState(instance, container, returnFocus, didClose) {
  1977. if (isToast()) {
  1978. triggerDidCloseAndDispose(instance, didClose);
  1979. } else {
  1980. restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
  1981. removeKeydownHandler(globalState);
  1982. }
  1983. // workaround for https://github.com/sweetalert2/sweetalert2/issues/2088
  1984. // for some reason removing the container in Safari will scroll the document to bottom
  1985. if (isSafariOrIOS) {
  1986. container.setAttribute('style', 'display:none !important');
  1987. container.removeAttribute('class');
  1988. container.innerHTML = '';
  1989. } else {
  1990. container.remove();
  1991. }
  1992. if (isModal()) {
  1993. undoReplaceScrollbarWithPadding();
  1994. undoIOSfix();
  1995. unsetAriaHidden();
  1996. }
  1997. removeBodyClasses();
  1998. }
  1999. /**
  2000. * Remove SweetAlert2 classes from body
  2001. */
  2002. function removeBodyClasses() {
  2003. removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
  2004. }
  2005. /**
  2006. * Instance method to close sweetAlert
  2007. *
  2008. * @param {any} resolveValue
  2009. */
  2010. function close(resolveValue) {
  2011. resolveValue = prepareResolveValue(resolveValue);
  2012. const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
  2013. const didClose = triggerClosePopup(this);
  2014. if (this.isAwaitingPromise) {
  2015. // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
  2016. if (!resolveValue.isDismissed) {
  2017. handleAwaitingPromise(this);
  2018. swalPromiseResolve(resolveValue);
  2019. }
  2020. } else if (didClose) {
  2021. // Resolve Swal promise
  2022. swalPromiseResolve(resolveValue);
  2023. }
  2024. }
  2025. const triggerClosePopup = instance => {
  2026. const popup = getPopup();
  2027. if (!popup) {
  2028. return false;
  2029. }
  2030. const innerParams = privateProps.innerParams.get(instance);
  2031. if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
  2032. return false;
  2033. }
  2034. removeClass(popup, innerParams.showClass.popup);
  2035. addClass(popup, innerParams.hideClass.popup);
  2036. const backdrop = getContainer();
  2037. removeClass(backdrop, innerParams.showClass.backdrop);
  2038. addClass(backdrop, innerParams.hideClass.backdrop);
  2039. handlePopupAnimation(instance, popup, innerParams);
  2040. return true;
  2041. };
  2042. /**
  2043. * @param {any} error
  2044. */
  2045. function rejectPromise(error) {
  2046. const rejectPromise = privateMethods.swalPromiseReject.get(this);
  2047. handleAwaitingPromise(this);
  2048. if (rejectPromise) {
  2049. // Reject Swal promise
  2050. rejectPromise(error);
  2051. }
  2052. }
  2053. /**
  2054. * @param {SweetAlert} instance
  2055. */
  2056. const handleAwaitingPromise = instance => {
  2057. if (instance.isAwaitingPromise) {
  2058. delete instance.isAwaitingPromise;
  2059. // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
  2060. if (!privateProps.innerParams.get(instance)) {
  2061. instance._destroy();
  2062. }
  2063. }
  2064. };
  2065. /**
  2066. * @param {any} resolveValue
  2067. * @returns {SweetAlertResult}
  2068. */
  2069. const prepareResolveValue = resolveValue => {
  2070. // When user calls Swal.close()
  2071. if (typeof resolveValue === 'undefined') {
  2072. return {
  2073. isConfirmed: false,
  2074. isDenied: false,
  2075. isDismissed: true
  2076. };
  2077. }
  2078. return Object.assign({
  2079. isConfirmed: false,
  2080. isDenied: false,
  2081. isDismissed: false
  2082. }, resolveValue);
  2083. };
  2084. /**
  2085. * @param {SweetAlert} instance
  2086. * @param {HTMLElement} popup
  2087. * @param {SweetAlertOptions} innerParams
  2088. */
  2089. const handlePopupAnimation = (instance, popup, innerParams) => {
  2090. const container = getContainer();
  2091. // If animation is supported, animate
  2092. const animationIsSupported = hasCssAnimation(popup);
  2093. if (typeof innerParams.willClose === 'function') {
  2094. innerParams.willClose(popup);
  2095. }
  2096. globalState.eventEmitter.emit('willClose', popup);
  2097. if (animationIsSupported) {
  2098. animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
  2099. } else {
  2100. // Otherwise, remove immediately
  2101. removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
  2102. }
  2103. };
  2104. /**
  2105. * @param {SweetAlert} instance
  2106. * @param {HTMLElement} popup
  2107. * @param {HTMLElement} container
  2108. * @param {boolean} returnFocus
  2109. * @param {Function} didClose
  2110. */
  2111. const animatePopup = (instance, popup, container, returnFocus, didClose) => {
  2112. globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
  2113. const swalCloseAnimationFinished = function (e) {
  2114. if (e.target === popup) {
  2115. globalState.swalCloseEventFinishedCallback();
  2116. delete globalState.swalCloseEventFinishedCallback;
  2117. popup.removeEventListener('animationend', swalCloseAnimationFinished);
  2118. popup.removeEventListener('transitionend', swalCloseAnimationFinished);
  2119. }
  2120. };
  2121. popup.addEventListener('animationend', swalCloseAnimationFinished);
  2122. popup.addEventListener('transitionend', swalCloseAnimationFinished);
  2123. };
  2124. /**
  2125. * @param {SweetAlert} instance
  2126. * @param {Function} didClose
  2127. */
  2128. const triggerDidCloseAndDispose = (instance, didClose) => {
  2129. setTimeout(() => {
  2130. if (typeof didClose === 'function') {
  2131. didClose.bind(instance.params)();
  2132. }
  2133. globalState.eventEmitter.emit('didClose');
  2134. // instance might have been destroyed already
  2135. if (instance._destroy) {
  2136. instance._destroy();
  2137. }
  2138. });
  2139. };
  2140. /**
  2141. * Shows loader (spinner), this is useful with AJAX requests.
  2142. * By default the loader be shown instead of the "Confirm" button.
  2143. *
  2144. * @param {HTMLButtonElement | null} [buttonToReplace]
  2145. */
  2146. const showLoading = buttonToReplace => {
  2147. let popup = getPopup();
  2148. if (!popup) {
  2149. new Swal();
  2150. }
  2151. popup = getPopup();
  2152. if (!popup) {
  2153. return;
  2154. }
  2155. const loader = getLoader();
  2156. if (isToast()) {
  2157. hide(getIcon());
  2158. } else {
  2159. replaceButton(popup, buttonToReplace);
  2160. }
  2161. show(loader);
  2162. popup.setAttribute('data-loading', 'true');
  2163. popup.setAttribute('aria-busy', 'true');
  2164. popup.focus();
  2165. };
  2166. /**
  2167. * @param {HTMLElement} popup
  2168. * @param {HTMLButtonElement | null} [buttonToReplace]
  2169. */
  2170. const replaceButton = (popup, buttonToReplace) => {
  2171. const actions = getActions();
  2172. const loader = getLoader();
  2173. if (!actions || !loader) {
  2174. return;
  2175. }
  2176. if (!buttonToReplace && isVisible$1(getConfirmButton())) {
  2177. buttonToReplace = getConfirmButton();
  2178. }
  2179. show(actions);
  2180. if (buttonToReplace) {
  2181. hide(buttonToReplace);
  2182. loader.setAttribute('data-button-to-replace', buttonToReplace.className);
  2183. actions.insertBefore(loader, buttonToReplace);
  2184. }
  2185. addClass([popup, actions], swalClasses.loading);
  2186. };
  2187. /**
  2188. * @param {SweetAlert} instance
  2189. * @param {SweetAlertOptions} params
  2190. */
  2191. const handleInputOptionsAndValue = (instance, params) => {
  2192. if (params.input === 'select' || params.input === 'radio') {
  2193. handleInputOptions(instance, params);
  2194. } else if (['text', 'email', 'number', 'tel', 'textarea'].some(i => i === params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
  2195. showLoading(getConfirmButton());
  2196. handleInputValue(instance, params);
  2197. }
  2198. };
  2199. /**
  2200. * @param {SweetAlert} instance
  2201. * @param {SweetAlertOptions} innerParams
  2202. * @returns {SweetAlertInputValue}
  2203. */
  2204. const getInputValue = (instance, innerParams) => {
  2205. const input = instance.getInput();
  2206. if (!input) {
  2207. return null;
  2208. }
  2209. switch (innerParams.input) {
  2210. case 'checkbox':
  2211. return getCheckboxValue(input);
  2212. case 'radio':
  2213. return getRadioValue(input);
  2214. case 'file':
  2215. return getFileValue(input);
  2216. default:
  2217. return innerParams.inputAutoTrim ? input.value.trim() : input.value;
  2218. }
  2219. };
  2220. /**
  2221. * @param {HTMLInputElement} input
  2222. * @returns {number}
  2223. */
  2224. const getCheckboxValue = input => input.checked ? 1 : 0;
  2225. /**
  2226. * @param {HTMLInputElement} input
  2227. * @returns {string | null}
  2228. */
  2229. const getRadioValue = input => input.checked ? input.value : null;
  2230. /**
  2231. * @param {HTMLInputElement} input
  2232. * @returns {FileList | File | null}
  2233. */
  2234. const getFileValue = input => input.files && input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
  2235. /**
  2236. * @param {SweetAlert} instance
  2237. * @param {SweetAlertOptions} params
  2238. */
  2239. const handleInputOptions = (instance, params) => {
  2240. const popup = getPopup();
  2241. if (!popup) {
  2242. return;
  2243. }
  2244. /**
  2245. * @param {Record<string, any>} inputOptions
  2246. */
  2247. const processInputOptions = inputOptions => {
  2248. if (params.input === 'select') {
  2249. populateSelectOptions(popup, formatInputOptions(inputOptions), params);
  2250. } else if (params.input === 'radio') {
  2251. populateRadioOptions(popup, formatInputOptions(inputOptions), params);
  2252. }
  2253. };
  2254. if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
  2255. showLoading(getConfirmButton());
  2256. asPromise(params.inputOptions).then(inputOptions => {
  2257. instance.hideLoading();
  2258. processInputOptions(inputOptions);
  2259. });
  2260. } else if (typeof params.inputOptions === 'object') {
  2261. processInputOptions(params.inputOptions);
  2262. } else {
  2263. error(`Unexpected type of inputOptions! Expected object, Map or Promise, got ${typeof params.inputOptions}`);
  2264. }
  2265. };
  2266. /**
  2267. * @param {SweetAlert} instance
  2268. * @param {SweetAlertOptions} params
  2269. */
  2270. const handleInputValue = (instance, params) => {
  2271. const input = instance.getInput();
  2272. if (!input) {
  2273. return;
  2274. }
  2275. hide(input);
  2276. asPromise(params.inputValue).then(inputValue => {
  2277. input.value = params.input === 'number' ? `${parseFloat(inputValue) || 0}` : `${inputValue}`;
  2278. show(input);
  2279. input.focus();
  2280. instance.hideLoading();
  2281. }).catch(err => {
  2282. error(`Error in inputValue promise: ${err}`);
  2283. input.value = '';
  2284. show(input);
  2285. input.focus();
  2286. instance.hideLoading();
  2287. });
  2288. };
  2289. /**
  2290. * @param {HTMLElement} popup
  2291. * @param {InputOptionFlattened[]} inputOptions
  2292. * @param {SweetAlertOptions} params
  2293. */
  2294. function populateSelectOptions(popup, inputOptions, params) {
  2295. const select = getDirectChildByClass(popup, swalClasses.select);
  2296. if (!select) {
  2297. return;
  2298. }
  2299. /**
  2300. * @param {HTMLElement} parent
  2301. * @param {string} optionLabel
  2302. * @param {string} optionValue
  2303. */
  2304. const renderOption = (parent, optionLabel, optionValue) => {
  2305. const option = document.createElement('option');
  2306. option.value = optionValue;
  2307. setInnerHtml(option, optionLabel);
  2308. option.selected = isSelected(optionValue, params.inputValue);
  2309. parent.appendChild(option);
  2310. };
  2311. inputOptions.forEach(inputOption => {
  2312. const optionValue = inputOption[0];
  2313. const optionLabel = inputOption[1];
  2314. // <optgroup> spec:
  2315. // https://www.w3.org/TR/html401/interact/forms.html#h-17.6
  2316. // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
  2317. // check whether this is a <optgroup>
  2318. if (Array.isArray(optionLabel)) {
  2319. // if it is an array, then it is an <optgroup>
  2320. const optgroup = document.createElement('optgroup');
  2321. optgroup.label = optionValue;
  2322. optgroup.disabled = false; // not configurable for now
  2323. select.appendChild(optgroup);
  2324. optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
  2325. } else {
  2326. // case of <option>
  2327. renderOption(select, optionLabel, optionValue);
  2328. }
  2329. });
  2330. select.focus();
  2331. }
  2332. /**
  2333. * @param {HTMLElement} popup
  2334. * @param {InputOptionFlattened[]} inputOptions
  2335. * @param {SweetAlertOptions} params
  2336. */
  2337. function populateRadioOptions(popup, inputOptions, params) {
  2338. const radio = getDirectChildByClass(popup, swalClasses.radio);
  2339. if (!radio) {
  2340. return;
  2341. }
  2342. inputOptions.forEach(inputOption => {
  2343. const radioValue = inputOption[0];
  2344. const radioLabel = inputOption[1];
  2345. const radioInput = document.createElement('input');
  2346. const radioLabelElement = document.createElement('label');
  2347. radioInput.type = 'radio';
  2348. radioInput.name = swalClasses.radio;
  2349. radioInput.value = radioValue;
  2350. if (isSelected(radioValue, params.inputValue)) {
  2351. radioInput.checked = true;
  2352. }
  2353. const label = document.createElement('span');
  2354. setInnerHtml(label, radioLabel);
  2355. label.className = swalClasses.label;
  2356. radioLabelElement.appendChild(radioInput);
  2357. radioLabelElement.appendChild(label);
  2358. radio.appendChild(radioLabelElement);
  2359. });
  2360. const radios = radio.querySelectorAll('input');
  2361. if (radios.length) {
  2362. radios[0].focus();
  2363. }
  2364. }
  2365. /**
  2366. * Converts `inputOptions` into an array of `[value, label]`s
  2367. *
  2368. * @param {Record<string, any>} inputOptions
  2369. * @typedef {string[]} InputOptionFlattened
  2370. * @returns {InputOptionFlattened[]}
  2371. */
  2372. const formatInputOptions = inputOptions => {
  2373. /** @type {InputOptionFlattened[]} */
  2374. const result = [];
  2375. if (inputOptions instanceof Map) {
  2376. inputOptions.forEach((value, key) => {
  2377. let valueFormatted = value;
  2378. if (typeof valueFormatted === 'object') {
  2379. // case of <optgroup>
  2380. valueFormatted = formatInputOptions(valueFormatted);
  2381. }
  2382. result.push([key, valueFormatted]);
  2383. });
  2384. } else {
  2385. Object.keys(inputOptions).forEach(key => {
  2386. let valueFormatted = inputOptions[key];
  2387. if (typeof valueFormatted === 'object') {
  2388. // case of <optgroup>
  2389. valueFormatted = formatInputOptions(valueFormatted);
  2390. }
  2391. result.push([key, valueFormatted]);
  2392. });
  2393. }
  2394. return result;
  2395. };
  2396. /**
  2397. * @param {string} optionValue
  2398. * @param {SweetAlertInputValue} inputValue
  2399. * @returns {boolean}
  2400. */
  2401. const isSelected = (optionValue, inputValue) => {
  2402. return !!inputValue && inputValue.toString() === optionValue.toString();
  2403. };
  2404. /**
  2405. * @param {SweetAlert} instance
  2406. */
  2407. const handleConfirmButtonClick = instance => {
  2408. const innerParams = privateProps.innerParams.get(instance);
  2409. instance.disableButtons();
  2410. if (innerParams.input) {
  2411. handleConfirmOrDenyWithInput(instance, 'confirm');
  2412. } else {
  2413. confirm(instance, true);
  2414. }
  2415. };
  2416. /**
  2417. * @param {SweetAlert} instance
  2418. */
  2419. const handleDenyButtonClick = instance => {
  2420. const innerParams = privateProps.innerParams.get(instance);
  2421. instance.disableButtons();
  2422. if (innerParams.returnInputValueOnDeny) {
  2423. handleConfirmOrDenyWithInput(instance, 'deny');
  2424. } else {
  2425. deny(instance, false);
  2426. }
  2427. };
  2428. /**
  2429. * @param {SweetAlert} instance
  2430. * @param {Function} dismissWith
  2431. */
  2432. const handleCancelButtonClick = (instance, dismissWith) => {
  2433. instance.disableButtons();
  2434. dismissWith(DismissReason.cancel);
  2435. };
  2436. /**
  2437. * @param {SweetAlert} instance
  2438. * @param {'confirm' | 'deny'} type
  2439. */
  2440. const handleConfirmOrDenyWithInput = (instance, type) => {
  2441. const innerParams = privateProps.innerParams.get(instance);
  2442. if (!innerParams.input) {
  2443. error(`The "input" parameter is needed to be set when using returnInputValueOn${capitalizeFirstLetter(type)}`);
  2444. return;
  2445. }
  2446. const input = instance.getInput();
  2447. const inputValue = getInputValue(instance, innerParams);
  2448. if (innerParams.inputValidator) {
  2449. handleInputValidator(instance, inputValue, type);
  2450. } else if (input && !input.checkValidity()) {
  2451. instance.enableButtons();
  2452. instance.showValidationMessage(innerParams.validationMessage || input.validationMessage);
  2453. } else if (type === 'deny') {
  2454. deny(instance, inputValue);
  2455. } else {
  2456. confirm(instance, inputValue);
  2457. }
  2458. };
  2459. /**
  2460. * @param {SweetAlert} instance
  2461. * @param {SweetAlertInputValue} inputValue
  2462. * @param {'confirm' | 'deny'} type
  2463. */
  2464. const handleInputValidator = (instance, inputValue, type) => {
  2465. const innerParams = privateProps.innerParams.get(instance);
  2466. instance.disableInput();
  2467. const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
  2468. validationPromise.then(validationMessage => {
  2469. instance.enableButtons();
  2470. instance.enableInput();
  2471. if (validationMessage) {
  2472. instance.showValidationMessage(validationMessage);
  2473. } else if (type === 'deny') {
  2474. deny(instance, inputValue);
  2475. } else {
  2476. confirm(instance, inputValue);
  2477. }
  2478. });
  2479. };
  2480. /**
  2481. * @param {SweetAlert} instance
  2482. * @param {any} value
  2483. */
  2484. const deny = (instance, value) => {
  2485. const innerParams = privateProps.innerParams.get(instance || undefined);
  2486. if (innerParams.showLoaderOnDeny) {
  2487. showLoading(getDenyButton());
  2488. }
  2489. if (innerParams.preDeny) {
  2490. instance.isAwaitingPromise = true; // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received
  2491. const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
  2492. preDenyPromise.then(preDenyValue => {
  2493. if (preDenyValue === false) {
  2494. instance.hideLoading();
  2495. handleAwaitingPromise(instance);
  2496. } else {
  2497. instance.close({
  2498. isDenied: true,
  2499. value: typeof preDenyValue === 'undefined' ? value : preDenyValue
  2500. });
  2501. }
  2502. }).catch(error => rejectWith(instance || undefined, error));
  2503. } else {
  2504. instance.close({
  2505. isDenied: true,
  2506. value
  2507. });
  2508. }
  2509. };
  2510. /**
  2511. * @param {SweetAlert} instance
  2512. * @param {any} value
  2513. */
  2514. const succeedWith = (instance, value) => {
  2515. instance.close({
  2516. isConfirmed: true,
  2517. value
  2518. });
  2519. };
  2520. /**
  2521. *
  2522. * @param {SweetAlert} instance
  2523. * @param {string} error
  2524. */
  2525. const rejectWith = (instance, error) => {
  2526. instance.rejectPromise(error);
  2527. };
  2528. /**
  2529. *
  2530. * @param {SweetAlert} instance
  2531. * @param {any} value
  2532. */
  2533. const confirm = (instance, value) => {
  2534. const innerParams = privateProps.innerParams.get(instance || undefined);
  2535. if (innerParams.showLoaderOnConfirm) {
  2536. showLoading();
  2537. }
  2538. if (innerParams.preConfirm) {
  2539. instance.resetValidationMessage();
  2540. instance.isAwaitingPromise = true; // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received
  2541. const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
  2542. preConfirmPromise.then(preConfirmValue => {
  2543. if (isVisible$1(getValidationMessage()) || preConfirmValue === false) {
  2544. instance.hideLoading();
  2545. handleAwaitingPromise(instance);
  2546. } else {
  2547. succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
  2548. }
  2549. }).catch(error => rejectWith(instance || undefined, error));
  2550. } else {
  2551. succeedWith(instance, value);
  2552. }
  2553. };
  2554. /**
  2555. * Hides loader and shows back the button which was hidden by .showLoading()
  2556. */
  2557. function hideLoading() {
  2558. // do nothing if popup is closed
  2559. const innerParams = privateProps.innerParams.get(this);
  2560. if (!innerParams) {
  2561. return;
  2562. }
  2563. const domCache = privateProps.domCache.get(this);
  2564. hide(domCache.loader);
  2565. if (isToast()) {
  2566. if (innerParams.icon) {
  2567. show(getIcon());
  2568. }
  2569. } else {
  2570. showRelatedButton(domCache);
  2571. }
  2572. removeClass([domCache.popup, domCache.actions], swalClasses.loading);
  2573. domCache.popup.removeAttribute('aria-busy');
  2574. domCache.popup.removeAttribute('data-loading');
  2575. domCache.confirmButton.disabled = false;
  2576. domCache.denyButton.disabled = false;
  2577. domCache.cancelButton.disabled = false;
  2578. }
  2579. const showRelatedButton = domCache => {
  2580. const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
  2581. if (buttonToReplace.length) {
  2582. show(buttonToReplace[0], 'inline-block');
  2583. } else if (allButtonsAreHidden()) {
  2584. hide(domCache.actions);
  2585. }
  2586. };
  2587. /**
  2588. * Gets the input DOM node, this method works with input parameter.
  2589. *
  2590. * @returns {HTMLInputElement | null}
  2591. */
  2592. function getInput() {
  2593. const innerParams = privateProps.innerParams.get(this);
  2594. const domCache = privateProps.domCache.get(this);
  2595. if (!domCache) {
  2596. return null;
  2597. }
  2598. return getInput$1(domCache.popup, innerParams.input);
  2599. }
  2600. /**
  2601. * @param {SweetAlert} instance
  2602. * @param {string[]} buttons
  2603. * @param {boolean} disabled
  2604. */
  2605. function setButtonsDisabled(instance, buttons, disabled) {
  2606. const domCache = privateProps.domCache.get(instance);
  2607. buttons.forEach(button => {
  2608. domCache[button].disabled = disabled;
  2609. });
  2610. }
  2611. /**
  2612. * @param {HTMLInputElement | null} input
  2613. * @param {boolean} disabled
  2614. */
  2615. function setInputDisabled(input, disabled) {
  2616. const popup = getPopup();
  2617. if (!popup || !input) {
  2618. return;
  2619. }
  2620. if (input.type === 'radio') {
  2621. /** @type {NodeListOf<HTMLInputElement>} */
  2622. const radios = popup.querySelectorAll(`[name="${swalClasses.radio}"]`);
  2623. for (let i = 0; i < radios.length; i++) {
  2624. radios[i].disabled = disabled;
  2625. }
  2626. } else {
  2627. input.disabled = disabled;
  2628. }
  2629. }
  2630. /**
  2631. * Enable all the buttons
  2632. * @this {SweetAlert}
  2633. */
  2634. function enableButtons() {
  2635. setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
  2636. }
  2637. /**
  2638. * Disable all the buttons
  2639. * @this {SweetAlert}
  2640. */
  2641. function disableButtons() {
  2642. setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
  2643. }
  2644. /**
  2645. * Enable the input field
  2646. * @this {SweetAlert}
  2647. */
  2648. function enableInput() {
  2649. setInputDisabled(this.getInput(), false);
  2650. }
  2651. /**
  2652. * Disable the input field
  2653. * @this {SweetAlert}
  2654. */
  2655. function disableInput() {
  2656. setInputDisabled(this.getInput(), true);
  2657. }
  2658. /**
  2659. * Show block with validation message
  2660. *
  2661. * @param {string} error
  2662. * @this {SweetAlert}
  2663. */
  2664. function showValidationMessage(error) {
  2665. const domCache = privateProps.domCache.get(this);
  2666. const params = privateProps.innerParams.get(this);
  2667. setInnerHtml(domCache.validationMessage, error);
  2668. domCache.validationMessage.className = swalClasses['validation-message'];
  2669. if (params.customClass && params.customClass.validationMessage) {
  2670. addClass(domCache.validationMessage, params.customClass.validationMessage);
  2671. }
  2672. show(domCache.validationMessage);
  2673. const input = this.getInput();
  2674. if (input) {
  2675. input.setAttribute('aria-invalid', 'true');
  2676. input.setAttribute('aria-describedby', swalClasses['validation-message']);
  2677. focusInput(input);
  2678. addClass(input, swalClasses.inputerror);
  2679. }
  2680. }
  2681. /**
  2682. * Hide block with validation message
  2683. *
  2684. * @this {SweetAlert}
  2685. */
  2686. function resetValidationMessage() {
  2687. const domCache = privateProps.domCache.get(this);
  2688. if (domCache.validationMessage) {
  2689. hide(domCache.validationMessage);
  2690. }
  2691. const input = this.getInput();
  2692. if (input) {
  2693. input.removeAttribute('aria-invalid');
  2694. input.removeAttribute('aria-describedby');
  2695. removeClass(input, swalClasses.inputerror);
  2696. }
  2697. }
  2698. const defaultParams = {
  2699. title: '',
  2700. titleText: '',
  2701. text: '',
  2702. html: '',
  2703. footer: '',
  2704. icon: undefined,
  2705. iconColor: undefined,
  2706. iconHtml: undefined,
  2707. template: undefined,
  2708. toast: false,
  2709. animation: true,
  2710. showClass: {
  2711. popup: 'swal2-show',
  2712. backdrop: 'swal2-backdrop-show',
  2713. icon: 'swal2-icon-show'
  2714. },
  2715. hideClass: {
  2716. popup: 'swal2-hide',
  2717. backdrop: 'swal2-backdrop-hide',
  2718. icon: 'swal2-icon-hide'
  2719. },
  2720. customClass: {},
  2721. target: 'body',
  2722. color: undefined,
  2723. backdrop: true,
  2724. heightAuto: true,
  2725. allowOutsideClick: true,
  2726. allowEscapeKey: true,
  2727. allowEnterKey: true,
  2728. stopKeydownPropagation: true,
  2729. keydownListenerCapture: false,
  2730. showConfirmButton: true,
  2731. showDenyButton: false,
  2732. showCancelButton: false,
  2733. preConfirm: undefined,
  2734. preDeny: undefined,
  2735. confirmButtonText: 'OK',
  2736. confirmButtonAriaLabel: '',
  2737. confirmButtonColor: undefined,
  2738. denyButtonText: 'No',
  2739. denyButtonAriaLabel: '',
  2740. denyButtonColor: undefined,
  2741. cancelButtonText: 'Cancel',
  2742. cancelButtonAriaLabel: '',
  2743. cancelButtonColor: undefined,
  2744. buttonsStyling: true,
  2745. reverseButtons: false,
  2746. focusConfirm: true,
  2747. focusDeny: false,
  2748. focusCancel: false,
  2749. returnFocus: true,
  2750. showCloseButton: false,
  2751. closeButtonHtml: '&times;',
  2752. closeButtonAriaLabel: 'Close this dialog',
  2753. loaderHtml: '',
  2754. showLoaderOnConfirm: false,
  2755. showLoaderOnDeny: false,
  2756. imageUrl: undefined,
  2757. imageWidth: undefined,
  2758. imageHeight: undefined,
  2759. imageAlt: '',
  2760. timer: undefined,
  2761. timerProgressBar: false,
  2762. width: undefined,
  2763. padding: undefined,
  2764. background: undefined,
  2765. input: undefined,
  2766. inputPlaceholder: '',
  2767. inputLabel: '',
  2768. inputValue: '',
  2769. inputOptions: {},
  2770. inputAutoFocus: true,
  2771. inputAutoTrim: true,
  2772. inputAttributes: {},
  2773. inputValidator: undefined,
  2774. returnInputValueOnDeny: false,
  2775. validationMessage: undefined,
  2776. grow: false,
  2777. position: 'center',
  2778. progressSteps: [],
  2779. currentProgressStep: undefined,
  2780. progressStepsDistance: undefined,
  2781. willOpen: undefined,
  2782. didOpen: undefined,
  2783. didRender: undefined,
  2784. willClose: undefined,
  2785. didClose: undefined,
  2786. didDestroy: undefined,
  2787. scrollbarPadding: true
  2788. };
  2789. const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];
  2790. /** @type {Record<string, string | undefined>} */
  2791. const deprecatedParams = {
  2792. allowEnterKey: undefined
  2793. };
  2794. const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
  2795. /**
  2796. * Is valid parameter
  2797. *
  2798. * @param {string} paramName
  2799. * @returns {boolean}
  2800. */
  2801. const isValidParameter = paramName => {
  2802. return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
  2803. };
  2804. /**
  2805. * Is valid parameter for Swal.update() method
  2806. *
  2807. * @param {string} paramName
  2808. * @returns {boolean}
  2809. */
  2810. const isUpdatableParameter = paramName => {
  2811. return updatableParams.indexOf(paramName) !== -1;
  2812. };
  2813. /**
  2814. * Is deprecated parameter
  2815. *
  2816. * @param {string} paramName
  2817. * @returns {string | undefined}
  2818. */
  2819. const isDeprecatedParameter = paramName => {
  2820. return deprecatedParams[paramName];
  2821. };
  2822. /**
  2823. * @param {string} param
  2824. */
  2825. const checkIfParamIsValid = param => {
  2826. if (!isValidParameter(param)) {
  2827. warn(`Unknown parameter "${param}"`);
  2828. }
  2829. };
  2830. /**
  2831. * @param {string} param
  2832. */
  2833. const checkIfToastParamIsValid = param => {
  2834. if (toastIncompatibleParams.includes(param)) {
  2835. warn(`The parameter "${param}" is incompatible with toasts`);
  2836. }
  2837. };
  2838. /**
  2839. * @param {string} param
  2840. */
  2841. const checkIfParamIsDeprecated = param => {
  2842. const isDeprecated = isDeprecatedParameter(param);
  2843. if (isDeprecated) {
  2844. warnAboutDeprecation(param, isDeprecated);
  2845. }
  2846. };
  2847. /**
  2848. * Show relevant warnings for given params
  2849. *
  2850. * @param {SweetAlertOptions} params
  2851. */
  2852. const showWarningsForParams = params => {
  2853. if (params.backdrop === false && params.allowOutsideClick) {
  2854. warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
  2855. }
  2856. for (const param in params) {
  2857. checkIfParamIsValid(param);
  2858. if (params.toast) {
  2859. checkIfToastParamIsValid(param);
  2860. }
  2861. checkIfParamIsDeprecated(param);
  2862. }
  2863. };
  2864. /**
  2865. * Updates popup parameters.
  2866. *
  2867. * @param {SweetAlertOptions} params
  2868. */
  2869. function update(params) {
  2870. const popup = getPopup();
  2871. const innerParams = privateProps.innerParams.get(this);
  2872. if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
  2873. warn(`You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.`);
  2874. return;
  2875. }
  2876. const validUpdatableParams = filterValidParams(params);
  2877. const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
  2878. render(this, updatedParams);
  2879. privateProps.innerParams.set(this, updatedParams);
  2880. Object.defineProperties(this, {
  2881. params: {
  2882. value: Object.assign({}, this.params, params),
  2883. writable: false,
  2884. enumerable: true
  2885. }
  2886. });
  2887. }
  2888. /**
  2889. * @param {SweetAlertOptions} params
  2890. * @returns {SweetAlertOptions}
  2891. */
  2892. const filterValidParams = params => {
  2893. const validUpdatableParams = {};
  2894. Object.keys(params).forEach(param => {
  2895. if (isUpdatableParameter(param)) {
  2896. validUpdatableParams[param] = params[param];
  2897. } else {
  2898. warn(`Invalid parameter to update: ${param}`);
  2899. }
  2900. });
  2901. return validUpdatableParams;
  2902. };
  2903. /**
  2904. * Dispose the current SweetAlert2 instance
  2905. */
  2906. function _destroy() {
  2907. const domCache = privateProps.domCache.get(this);
  2908. const innerParams = privateProps.innerParams.get(this);
  2909. if (!innerParams) {
  2910. disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
  2911. return; // This instance has already been destroyed
  2912. }
  2913. // Check if there is another Swal closing
  2914. if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
  2915. globalState.swalCloseEventFinishedCallback();
  2916. delete globalState.swalCloseEventFinishedCallback;
  2917. }
  2918. if (typeof innerParams.didDestroy === 'function') {
  2919. innerParams.didDestroy();
  2920. }
  2921. globalState.eventEmitter.emit('didDestroy');
  2922. disposeSwal(this);
  2923. }
  2924. /**
  2925. * @param {SweetAlert} instance
  2926. */
  2927. const disposeSwal = instance => {
  2928. disposeWeakMaps(instance);
  2929. // Unset this.params so GC will dispose it (#1569)
  2930. delete instance.params;
  2931. // Unset globalState props so GC will dispose globalState (#1569)
  2932. delete globalState.keydownHandler;
  2933. delete globalState.keydownTarget;
  2934. // Unset currentInstance
  2935. delete globalState.currentInstance;
  2936. };
  2937. /**
  2938. * @param {SweetAlert} instance
  2939. */
  2940. const disposeWeakMaps = instance => {
  2941. // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
  2942. if (instance.isAwaitingPromise) {
  2943. unsetWeakMaps(privateProps, instance);
  2944. instance.isAwaitingPromise = true;
  2945. } else {
  2946. unsetWeakMaps(privateMethods, instance);
  2947. unsetWeakMaps(privateProps, instance);
  2948. delete instance.isAwaitingPromise;
  2949. // Unset instance methods
  2950. delete instance.disableButtons;
  2951. delete instance.enableButtons;
  2952. delete instance.getInput;
  2953. delete instance.disableInput;
  2954. delete instance.enableInput;
  2955. delete instance.hideLoading;
  2956. delete instance.disableLoading;
  2957. delete instance.showValidationMessage;
  2958. delete instance.resetValidationMessage;
  2959. delete instance.close;
  2960. delete instance.closePopup;
  2961. delete instance.closeModal;
  2962. delete instance.closeToast;
  2963. delete instance.rejectPromise;
  2964. delete instance.update;
  2965. delete instance._destroy;
  2966. }
  2967. };
  2968. /**
  2969. * @param {object} obj
  2970. * @param {SweetAlert} instance
  2971. */
  2972. const unsetWeakMaps = (obj, instance) => {
  2973. for (const i in obj) {
  2974. obj[i].delete(instance);
  2975. }
  2976. };
  2977. var instanceMethods = /*#__PURE__*/Object.freeze({
  2978. __proto__: null,
  2979. _destroy: _destroy,
  2980. close: close,
  2981. closeModal: close,
  2982. closePopup: close,
  2983. closeToast: close,
  2984. disableButtons: disableButtons,
  2985. disableInput: disableInput,
  2986. disableLoading: hideLoading,
  2987. enableButtons: enableButtons,
  2988. enableInput: enableInput,
  2989. getInput: getInput,
  2990. handleAwaitingPromise: handleAwaitingPromise,
  2991. hideLoading: hideLoading,
  2992. rejectPromise: rejectPromise,
  2993. resetValidationMessage: resetValidationMessage,
  2994. showValidationMessage: showValidationMessage,
  2995. update: update
  2996. });
  2997. /**
  2998. * @param {SweetAlertOptions} innerParams
  2999. * @param {DomCache} domCache
  3000. * @param {Function} dismissWith
  3001. */
  3002. const handlePopupClick = (innerParams, domCache, dismissWith) => {
  3003. if (innerParams.toast) {
  3004. handleToastClick(innerParams, domCache, dismissWith);
  3005. } else {
  3006. // Ignore click events that had mousedown on the popup but mouseup on the container
  3007. // This can happen when the user drags a slider
  3008. handleModalMousedown(domCache);
  3009. // Ignore click events that had mousedown on the container but mouseup on the popup
  3010. handleContainerMousedown(domCache);
  3011. handleModalClick(innerParams, domCache, dismissWith);
  3012. }
  3013. };
  3014. /**
  3015. * @param {SweetAlertOptions} innerParams
  3016. * @param {DomCache} domCache
  3017. * @param {Function} dismissWith
  3018. */
  3019. const handleToastClick = (innerParams, domCache, dismissWith) => {
  3020. // Closing toast by internal click
  3021. domCache.popup.onclick = () => {
  3022. if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
  3023. return;
  3024. }
  3025. dismissWith(DismissReason.close);
  3026. };
  3027. };
  3028. /**
  3029. * @param {SweetAlertOptions} innerParams
  3030. * @returns {boolean}
  3031. */
  3032. const isAnyButtonShown = innerParams => {
  3033. return !!(innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton);
  3034. };
  3035. let ignoreOutsideClick = false;
  3036. /**
  3037. * @param {DomCache} domCache
  3038. */
  3039. const handleModalMousedown = domCache => {
  3040. domCache.popup.onmousedown = () => {
  3041. domCache.container.onmouseup = function (e) {
  3042. domCache.container.onmouseup = () => {};
  3043. // We only check if the mouseup target is the container because usually it doesn't
  3044. // have any other direct children aside of the popup
  3045. if (e.target === domCache.container) {
  3046. ignoreOutsideClick = true;
  3047. }
  3048. };
  3049. };
  3050. };
  3051. /**
  3052. * @param {DomCache} domCache
  3053. */
  3054. const handleContainerMousedown = domCache => {
  3055. domCache.container.onmousedown = e => {
  3056. // prevent the modal text from being selected on double click on the container (allowOutsideClick: false)
  3057. if (e.target === domCache.container) {
  3058. e.preventDefault();
  3059. }
  3060. domCache.popup.onmouseup = function (e) {
  3061. domCache.popup.onmouseup = () => {};
  3062. // We also need to check if the mouseup target is a child of the popup
  3063. if (e.target === domCache.popup || e.target instanceof HTMLElement && domCache.popup.contains(e.target)) {
  3064. ignoreOutsideClick = true;
  3065. }
  3066. };
  3067. };
  3068. };
  3069. /**
  3070. * @param {SweetAlertOptions} innerParams
  3071. * @param {DomCache} domCache
  3072. * @param {Function} dismissWith
  3073. */
  3074. const handleModalClick = (innerParams, domCache, dismissWith) => {
  3075. domCache.container.onclick = e => {
  3076. if (ignoreOutsideClick) {
  3077. ignoreOutsideClick = false;
  3078. return;
  3079. }
  3080. if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
  3081. dismissWith(DismissReason.backdrop);
  3082. }
  3083. };
  3084. };
  3085. const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
  3086. const isElement = elem => elem instanceof Element || isJqueryElement(elem);
  3087. const argsToParams = args => {
  3088. const params = {};
  3089. if (typeof args[0] === 'object' && !isElement(args[0])) {
  3090. Object.assign(params, args[0]);
  3091. } else {
  3092. ['title', 'html', 'icon'].forEach((name, index) => {
  3093. const arg = args[index];
  3094. if (typeof arg === 'string' || isElement(arg)) {
  3095. params[name] = arg;
  3096. } else if (arg !== undefined) {
  3097. error(`Unexpected type of ${name}! Expected "string" or "Element", got ${typeof arg}`);
  3098. }
  3099. });
  3100. }
  3101. return params;
  3102. };
  3103. /**
  3104. * Main method to create a new SweetAlert2 popup
  3105. *
  3106. * @param {...SweetAlertOptions} args
  3107. * @returns {Promise<SweetAlertResult>}
  3108. */
  3109. function fire() {
  3110. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3111. args[_key] = arguments[_key];
  3112. }
  3113. return new this(...args);
  3114. }
  3115. /**
  3116. * Returns an extended version of `Swal` containing `params` as defaults.
  3117. * Useful for reusing Swal configuration.
  3118. *
  3119. * For example:
  3120. *
  3121. * Before:
  3122. * const textPromptOptions = { input: 'text', showCancelButton: true }
  3123. * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
  3124. * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
  3125. *
  3126. * After:
  3127. * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
  3128. * const {value: firstName} = await TextPrompt('What is your first name?')
  3129. * const {value: lastName} = await TextPrompt('What is your last name?')
  3130. *
  3131. * @param {SweetAlertOptions} mixinParams
  3132. * @returns {SweetAlert}
  3133. */
  3134. function mixin(mixinParams) {
  3135. class MixinSwal extends this {
  3136. _main(params, priorityMixinParams) {
  3137. return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
  3138. }
  3139. }
  3140. // @ts-ignore
  3141. return MixinSwal;
  3142. }
  3143. /**
  3144. * If `timer` parameter is set, returns number of milliseconds of timer remained.
  3145. * Otherwise, returns undefined.
  3146. *
  3147. * @returns {number | undefined}
  3148. */
  3149. const getTimerLeft = () => {
  3150. return globalState.timeout && globalState.timeout.getTimerLeft();
  3151. };
  3152. /**
  3153. * Stop timer. Returns number of milliseconds of timer remained.
  3154. * If `timer` parameter isn't set, returns undefined.
  3155. *
  3156. * @returns {number | undefined}
  3157. */
  3158. const stopTimer = () => {
  3159. if (globalState.timeout) {
  3160. stopTimerProgressBar();
  3161. return globalState.timeout.stop();
  3162. }
  3163. };
  3164. /**
  3165. * Resume timer. Returns number of milliseconds of timer remained.
  3166. * If `timer` parameter isn't set, returns undefined.
  3167. *
  3168. * @returns {number | undefined}
  3169. */
  3170. const resumeTimer = () => {
  3171. if (globalState.timeout) {
  3172. const remaining = globalState.timeout.start();
  3173. animateTimerProgressBar(remaining);
  3174. return remaining;
  3175. }
  3176. };
  3177. /**
  3178. * Resume timer. Returns number of milliseconds of timer remained.
  3179. * If `timer` parameter isn't set, returns undefined.
  3180. *
  3181. * @returns {number | undefined}
  3182. */
  3183. const toggleTimer = () => {
  3184. const timer = globalState.timeout;
  3185. return timer && (timer.running ? stopTimer() : resumeTimer());
  3186. };
  3187. /**
  3188. * Increase timer. Returns number of milliseconds of an updated timer.
  3189. * If `timer` parameter isn't set, returns undefined.
  3190. *
  3191. * @param {number} ms
  3192. * @returns {number | undefined}
  3193. */
  3194. const increaseTimer = ms => {
  3195. if (globalState.timeout) {
  3196. const remaining = globalState.timeout.increase(ms);
  3197. animateTimerProgressBar(remaining, true);
  3198. return remaining;
  3199. }
  3200. };
  3201. /**
  3202. * Check if timer is running. Returns true if timer is running
  3203. * or false if timer is paused or stopped.
  3204. * If `timer` parameter isn't set, returns undefined
  3205. *
  3206. * @returns {boolean}
  3207. */
  3208. const isTimerRunning = () => {
  3209. return !!(globalState.timeout && globalState.timeout.isRunning());
  3210. };
  3211. let bodyClickListenerAdded = false;
  3212. const clickHandlers = {};
  3213. /**
  3214. * @param {string} attr
  3215. */
  3216. function bindClickHandler() {
  3217. let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
  3218. clickHandlers[attr] = this;
  3219. if (!bodyClickListenerAdded) {
  3220. document.body.addEventListener('click', bodyClickListener);
  3221. bodyClickListenerAdded = true;
  3222. }
  3223. }
  3224. const bodyClickListener = event => {
  3225. for (let el = event.target; el && el !== document; el = el.parentNode) {
  3226. for (const attr in clickHandlers) {
  3227. const template = el.getAttribute(attr);
  3228. if (template) {
  3229. clickHandlers[attr].fire({
  3230. template
  3231. });
  3232. return;
  3233. }
  3234. }
  3235. }
  3236. };
  3237. // Source: https://gist.github.com/mudge/5830382?permalink_comment_id=2691957#gistcomment-2691957
  3238. class EventEmitter {
  3239. constructor() {
  3240. /** @type {Events} */
  3241. this.events = {};
  3242. }
  3243. /**
  3244. * @param {string} eventName
  3245. * @returns {EventHandlers}
  3246. */
  3247. _getHandlersByEventName(eventName) {
  3248. if (typeof this.events[eventName] === 'undefined') {
  3249. // not Set because we need to keep the FIFO order
  3250. // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1748990334
  3251. this.events[eventName] = [];
  3252. }
  3253. return this.events[eventName];
  3254. }
  3255. /**
  3256. * @param {string} eventName
  3257. * @param {EventHandler} eventHandler
  3258. */
  3259. on(eventName, eventHandler) {
  3260. const currentHandlers = this._getHandlersByEventName(eventName);
  3261. if (!currentHandlers.includes(eventHandler)) {
  3262. currentHandlers.push(eventHandler);
  3263. }
  3264. }
  3265. /**
  3266. * @param {string} eventName
  3267. * @param {EventHandler} eventHandler
  3268. */
  3269. once(eventName, eventHandler) {
  3270. var _this = this;
  3271. /**
  3272. * @param {Array} args
  3273. */
  3274. const onceFn = function () {
  3275. _this.removeListener(eventName, onceFn);
  3276. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3277. args[_key] = arguments[_key];
  3278. }
  3279. eventHandler.apply(_this, args);
  3280. };
  3281. this.on(eventName, onceFn);
  3282. }
  3283. /**
  3284. * @param {string} eventName
  3285. * @param {Array} args
  3286. */
  3287. emit(eventName) {
  3288. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  3289. args[_key2 - 1] = arguments[_key2];
  3290. }
  3291. this._getHandlersByEventName(eventName).forEach(
  3292. /**
  3293. * @param {EventHandler} eventHandler
  3294. */
  3295. eventHandler => {
  3296. try {
  3297. eventHandler.apply(this, args);
  3298. } catch (error) {
  3299. console.error(error);
  3300. }
  3301. });
  3302. }
  3303. /**
  3304. * @param {string} eventName
  3305. * @param {EventHandler} eventHandler
  3306. */
  3307. removeListener(eventName, eventHandler) {
  3308. const currentHandlers = this._getHandlersByEventName(eventName);
  3309. const index = currentHandlers.indexOf(eventHandler);
  3310. if (index > -1) {
  3311. currentHandlers.splice(index, 1);
  3312. }
  3313. }
  3314. /**
  3315. * @param {string} eventName
  3316. */
  3317. removeAllListeners(eventName) {
  3318. if (this.events[eventName] !== undefined) {
  3319. // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1749239222
  3320. this.events[eventName].length = 0;
  3321. }
  3322. }
  3323. reset() {
  3324. this.events = {};
  3325. }
  3326. }
  3327. globalState.eventEmitter = new EventEmitter();
  3328. /**
  3329. * @param {string} eventName
  3330. * @param {EventHandler} eventHandler
  3331. */
  3332. const on = (eventName, eventHandler) => {
  3333. globalState.eventEmitter.on(eventName, eventHandler);
  3334. };
  3335. /**
  3336. * @param {string} eventName
  3337. * @param {EventHandler} eventHandler
  3338. */
  3339. const once = (eventName, eventHandler) => {
  3340. globalState.eventEmitter.once(eventName, eventHandler);
  3341. };
  3342. /**
  3343. * @param {string} [eventName]
  3344. * @param {EventHandler} [eventHandler]
  3345. */
  3346. const off = (eventName, eventHandler) => {
  3347. // Remove all handlers for all events
  3348. if (!eventName) {
  3349. globalState.eventEmitter.reset();
  3350. return;
  3351. }
  3352. if (eventHandler) {
  3353. // Remove a specific handler
  3354. globalState.eventEmitter.removeListener(eventName, eventHandler);
  3355. } else {
  3356. // Remove all handlers for a specific event
  3357. globalState.eventEmitter.removeAllListeners(eventName);
  3358. }
  3359. };
  3360. var staticMethods = /*#__PURE__*/Object.freeze({
  3361. __proto__: null,
  3362. argsToParams: argsToParams,
  3363. bindClickHandler: bindClickHandler,
  3364. clickCancel: clickCancel,
  3365. clickConfirm: clickConfirm,
  3366. clickDeny: clickDeny,
  3367. enableLoading: showLoading,
  3368. fire: fire,
  3369. getActions: getActions,
  3370. getCancelButton: getCancelButton,
  3371. getCloseButton: getCloseButton,
  3372. getConfirmButton: getConfirmButton,
  3373. getContainer: getContainer,
  3374. getDenyButton: getDenyButton,
  3375. getFocusableElements: getFocusableElements,
  3376. getFooter: getFooter,
  3377. getHtmlContainer: getHtmlContainer,
  3378. getIcon: getIcon,
  3379. getIconContent: getIconContent,
  3380. getImage: getImage,
  3381. getInputLabel: getInputLabel,
  3382. getLoader: getLoader,
  3383. getPopup: getPopup,
  3384. getProgressSteps: getProgressSteps,
  3385. getTimerLeft: getTimerLeft,
  3386. getTimerProgressBar: getTimerProgressBar,
  3387. getTitle: getTitle,
  3388. getValidationMessage: getValidationMessage,
  3389. increaseTimer: increaseTimer,
  3390. isDeprecatedParameter: isDeprecatedParameter,
  3391. isLoading: isLoading,
  3392. isTimerRunning: isTimerRunning,
  3393. isUpdatableParameter: isUpdatableParameter,
  3394. isValidParameter: isValidParameter,
  3395. isVisible: isVisible,
  3396. mixin: mixin,
  3397. off: off,
  3398. on: on,
  3399. once: once,
  3400. resumeTimer: resumeTimer,
  3401. showLoading: showLoading,
  3402. stopTimer: stopTimer,
  3403. toggleTimer: toggleTimer
  3404. });
  3405. class Timer {
  3406. /**
  3407. * @param {Function} callback
  3408. * @param {number} delay
  3409. */
  3410. constructor(callback, delay) {
  3411. this.callback = callback;
  3412. this.remaining = delay;
  3413. this.running = false;
  3414. this.start();
  3415. }
  3416. /**
  3417. * @returns {number}
  3418. */
  3419. start() {
  3420. if (!this.running) {
  3421. this.running = true;
  3422. this.started = new Date();
  3423. this.id = setTimeout(this.callback, this.remaining);
  3424. }
  3425. return this.remaining;
  3426. }
  3427. /**
  3428. * @returns {number}
  3429. */
  3430. stop() {
  3431. if (this.started && this.running) {
  3432. this.running = false;
  3433. clearTimeout(this.id);
  3434. this.remaining -= new Date().getTime() - this.started.getTime();
  3435. }
  3436. return this.remaining;
  3437. }
  3438. /**
  3439. * @param {number} n
  3440. * @returns {number}
  3441. */
  3442. increase(n) {
  3443. const running = this.running;
  3444. if (running) {
  3445. this.stop();
  3446. }
  3447. this.remaining += n;
  3448. if (running) {
  3449. this.start();
  3450. }
  3451. return this.remaining;
  3452. }
  3453. /**
  3454. * @returns {number}
  3455. */
  3456. getTimerLeft() {
  3457. if (this.running) {
  3458. this.stop();
  3459. this.start();
  3460. }
  3461. return this.remaining;
  3462. }
  3463. /**
  3464. * @returns {boolean}
  3465. */
  3466. isRunning() {
  3467. return this.running;
  3468. }
  3469. }
  3470. const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
  3471. /**
  3472. * @param {SweetAlertOptions} params
  3473. * @returns {SweetAlertOptions}
  3474. */
  3475. const getTemplateParams = params => {
  3476. const template = typeof params.template === 'string' ? (/** @type {HTMLTemplateElement} */document.querySelector(params.template)) : params.template;
  3477. if (!template) {
  3478. return {};
  3479. }
  3480. /** @type {DocumentFragment} */
  3481. const templateContent = template.content;
  3482. showWarningsForElements(templateContent);
  3483. const result = Object.assign(getSwalParams(templateContent), getSwalFunctionParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
  3484. return result;
  3485. };
  3486. /**
  3487. * @param {DocumentFragment} templateContent
  3488. * @returns {Record<string, any>}
  3489. */
  3490. const getSwalParams = templateContent => {
  3491. /** @type {Record<string, any>} */
  3492. const result = {};
  3493. /** @type {HTMLElement[]} */
  3494. const swalParams = Array.from(templateContent.querySelectorAll('swal-param'));
  3495. swalParams.forEach(param => {
  3496. showWarningsForAttributes(param, ['name', 'value']);
  3497. const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
  3498. const value = param.getAttribute('value');
  3499. if (!paramName || !value) {
  3500. return;
  3501. }
  3502. if (typeof defaultParams[paramName] === 'boolean') {
  3503. result[paramName] = value !== 'false';
  3504. } else if (typeof defaultParams[paramName] === 'object') {
  3505. result[paramName] = JSON.parse(value);
  3506. } else {
  3507. result[paramName] = value;
  3508. }
  3509. });
  3510. return result;
  3511. };
  3512. /**
  3513. * @param {DocumentFragment} templateContent
  3514. * @returns {Record<string, any>}
  3515. */
  3516. const getSwalFunctionParams = templateContent => {
  3517. /** @type {Record<string, any>} */
  3518. const result = {};
  3519. /** @type {HTMLElement[]} */
  3520. const swalFunctions = Array.from(templateContent.querySelectorAll('swal-function-param'));
  3521. swalFunctions.forEach(param => {
  3522. const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
  3523. const value = param.getAttribute('value');
  3524. if (!paramName || !value) {
  3525. return;
  3526. }
  3527. result[paramName] = new Function(`return ${value}`)();
  3528. });
  3529. return result;
  3530. };
  3531. /**
  3532. * @param {DocumentFragment} templateContent
  3533. * @returns {Record<string, any>}
  3534. */
  3535. const getSwalButtons = templateContent => {
  3536. /** @type {Record<string, any>} */
  3537. const result = {};
  3538. /** @type {HTMLElement[]} */
  3539. const swalButtons = Array.from(templateContent.querySelectorAll('swal-button'));
  3540. swalButtons.forEach(button => {
  3541. showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
  3542. const type = button.getAttribute('type');
  3543. if (!type || !['confirm', 'cancel', 'deny'].includes(type)) {
  3544. return;
  3545. }
  3546. result[`${type}ButtonText`] = button.innerHTML;
  3547. result[`show${capitalizeFirstLetter(type)}Button`] = true;
  3548. if (button.hasAttribute('color')) {
  3549. result[`${type}ButtonColor`] = button.getAttribute('color');
  3550. }
  3551. if (button.hasAttribute('aria-label')) {
  3552. result[`${type}ButtonAriaLabel`] = button.getAttribute('aria-label');
  3553. }
  3554. });
  3555. return result;
  3556. };
  3557. /**
  3558. * @param {DocumentFragment} templateContent
  3559. * @returns {Pick<SweetAlertOptions, 'imageUrl' | 'imageWidth' | 'imageHeight' | 'imageAlt'>}
  3560. */
  3561. const getSwalImage = templateContent => {
  3562. const result = {};
  3563. /** @type {HTMLElement | null} */
  3564. const image = templateContent.querySelector('swal-image');
  3565. if (image) {
  3566. showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
  3567. if (image.hasAttribute('src')) {
  3568. result.imageUrl = image.getAttribute('src') || undefined;
  3569. }
  3570. if (image.hasAttribute('width')) {
  3571. result.imageWidth = image.getAttribute('width') || undefined;
  3572. }
  3573. if (image.hasAttribute('height')) {
  3574. result.imageHeight = image.getAttribute('height') || undefined;
  3575. }
  3576. if (image.hasAttribute('alt')) {
  3577. result.imageAlt = image.getAttribute('alt') || undefined;
  3578. }
  3579. }
  3580. return result;
  3581. };
  3582. /**
  3583. * @param {DocumentFragment} templateContent
  3584. * @returns {Record<string, any>}
  3585. */
  3586. const getSwalIcon = templateContent => {
  3587. const result = {};
  3588. /** @type {HTMLElement | null} */
  3589. const icon = templateContent.querySelector('swal-icon');
  3590. if (icon) {
  3591. showWarningsForAttributes(icon, ['type', 'color']);
  3592. if (icon.hasAttribute('type')) {
  3593. result.icon = icon.getAttribute('type');
  3594. }
  3595. if (icon.hasAttribute('color')) {
  3596. result.iconColor = icon.getAttribute('color');
  3597. }
  3598. result.iconHtml = icon.innerHTML;
  3599. }
  3600. return result;
  3601. };
  3602. /**
  3603. * @param {DocumentFragment} templateContent
  3604. * @returns {Record<string, any>}
  3605. */
  3606. const getSwalInput = templateContent => {
  3607. /** @type {Record<string, any>} */
  3608. const result = {};
  3609. /** @type {HTMLElement | null} */
  3610. const input = templateContent.querySelector('swal-input');
  3611. if (input) {
  3612. showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
  3613. result.input = input.getAttribute('type') || 'text';
  3614. if (input.hasAttribute('label')) {
  3615. result.inputLabel = input.getAttribute('label');
  3616. }
  3617. if (input.hasAttribute('placeholder')) {
  3618. result.inputPlaceholder = input.getAttribute('placeholder');
  3619. }
  3620. if (input.hasAttribute('value')) {
  3621. result.inputValue = input.getAttribute('value');
  3622. }
  3623. }
  3624. /** @type {HTMLElement[]} */
  3625. const inputOptions = Array.from(templateContent.querySelectorAll('swal-input-option'));
  3626. if (inputOptions.length) {
  3627. result.inputOptions = {};
  3628. inputOptions.forEach(option => {
  3629. showWarningsForAttributes(option, ['value']);
  3630. const optionValue = option.getAttribute('value');
  3631. if (!optionValue) {
  3632. return;
  3633. }
  3634. const optionName = option.innerHTML;
  3635. result.inputOptions[optionValue] = optionName;
  3636. });
  3637. }
  3638. return result;
  3639. };
  3640. /**
  3641. * @param {DocumentFragment} templateContent
  3642. * @param {string[]} paramNames
  3643. * @returns {Record<string, any>}
  3644. */
  3645. const getSwalStringParams = (templateContent, paramNames) => {
  3646. /** @type {Record<string, any>} */
  3647. const result = {};
  3648. for (const i in paramNames) {
  3649. const paramName = paramNames[i];
  3650. /** @type {HTMLElement | null} */
  3651. const tag = templateContent.querySelector(paramName);
  3652. if (tag) {
  3653. showWarningsForAttributes(tag, []);
  3654. result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
  3655. }
  3656. }
  3657. return result;
  3658. };
  3659. /**
  3660. * @param {DocumentFragment} templateContent
  3661. */
  3662. const showWarningsForElements = templateContent => {
  3663. const allowedElements = swalStringParams.concat(['swal-param', 'swal-function-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
  3664. Array.from(templateContent.children).forEach(el => {
  3665. const tagName = el.tagName.toLowerCase();
  3666. if (!allowedElements.includes(tagName)) {
  3667. warn(`Unrecognized element <${tagName}>`);
  3668. }
  3669. });
  3670. };
  3671. /**
  3672. * @param {HTMLElement} el
  3673. * @param {string[]} allowedAttributes
  3674. */
  3675. const showWarningsForAttributes = (el, allowedAttributes) => {
  3676. Array.from(el.attributes).forEach(attribute => {
  3677. if (allowedAttributes.indexOf(attribute.name) === -1) {
  3678. warn([`Unrecognized attribute "${attribute.name}" on <${el.tagName.toLowerCase()}>.`, `${allowedAttributes.length ? `Allowed attributes are: ${allowedAttributes.join(', ')}` : 'To set the value, use HTML within the element.'}`]);
  3679. }
  3680. });
  3681. };
  3682. const SHOW_CLASS_TIMEOUT = 10;
  3683. /**
  3684. * Open popup, add necessary classes and styles, fix scrollbar
  3685. *
  3686. * @param {SweetAlertOptions} params
  3687. */
  3688. const openPopup = params => {
  3689. const container = getContainer();
  3690. const popup = getPopup();
  3691. if (typeof params.willOpen === 'function') {
  3692. params.willOpen(popup);
  3693. }
  3694. globalState.eventEmitter.emit('willOpen', popup);
  3695. const bodyStyles = window.getComputedStyle(document.body);
  3696. const initialBodyOverflow = bodyStyles.overflowY;
  3697. addClasses(container, popup, params);
  3698. // scrolling is 'hidden' until animation is done, after that 'auto'
  3699. setTimeout(() => {
  3700. setScrollingVisibility(container, popup);
  3701. }, SHOW_CLASS_TIMEOUT);
  3702. if (isModal()) {
  3703. fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
  3704. setAriaHidden();
  3705. }
  3706. if (!isToast() && !globalState.previousActiveElement) {
  3707. globalState.previousActiveElement = document.activeElement;
  3708. }
  3709. if (typeof params.didOpen === 'function') {
  3710. setTimeout(() => params.didOpen(popup));
  3711. }
  3712. globalState.eventEmitter.emit('didOpen', popup);
  3713. removeClass(container, swalClasses['no-transition']);
  3714. };
  3715. /**
  3716. * @param {AnimationEvent} event
  3717. */
  3718. const swalOpenAnimationFinished = event => {
  3719. const popup = getPopup();
  3720. if (event.target !== popup) {
  3721. return;
  3722. }
  3723. const container = getContainer();
  3724. popup.removeEventListener('animationend', swalOpenAnimationFinished);
  3725. popup.removeEventListener('transitionend', swalOpenAnimationFinished);
  3726. container.style.overflowY = 'auto';
  3727. };
  3728. /**
  3729. * @param {HTMLElement} container
  3730. * @param {HTMLElement} popup
  3731. */
  3732. const setScrollingVisibility = (container, popup) => {
  3733. if (hasCssAnimation(popup)) {
  3734. container.style.overflowY = 'hidden';
  3735. popup.addEventListener('animationend', swalOpenAnimationFinished);
  3736. popup.addEventListener('transitionend', swalOpenAnimationFinished);
  3737. } else {
  3738. container.style.overflowY = 'auto';
  3739. }
  3740. };
  3741. /**
  3742. * @param {HTMLElement} container
  3743. * @param {boolean} scrollbarPadding
  3744. * @param {string} initialBodyOverflow
  3745. */
  3746. const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
  3747. iOSfix();
  3748. if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
  3749. replaceScrollbarWithPadding(initialBodyOverflow);
  3750. }
  3751. // sweetalert2/issues/1247
  3752. setTimeout(() => {
  3753. container.scrollTop = 0;
  3754. });
  3755. };
  3756. /**
  3757. * @param {HTMLElement} container
  3758. * @param {HTMLElement} popup
  3759. * @param {SweetAlertOptions} params
  3760. */
  3761. const addClasses = (container, popup, params) => {
  3762. addClass(container, params.showClass.backdrop);
  3763. if (params.animation) {
  3764. // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
  3765. popup.style.setProperty('opacity', '0', 'important');
  3766. show(popup, 'grid');
  3767. setTimeout(() => {
  3768. // Animate popup right after showing it
  3769. addClass(popup, params.showClass.popup);
  3770. // and remove the opacity workaround
  3771. popup.style.removeProperty('opacity');
  3772. }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
  3773. } else {
  3774. show(popup, 'grid');
  3775. }
  3776. addClass([document.documentElement, document.body], swalClasses.shown);
  3777. if (params.heightAuto && params.backdrop && !params.toast) {
  3778. addClass([document.documentElement, document.body], swalClasses['height-auto']);
  3779. }
  3780. };
  3781. var defaultInputValidators = {
  3782. /**
  3783. * @param {string} string
  3784. * @param {string} [validationMessage]
  3785. * @returns {Promise<string | void>}
  3786. */
  3787. email: (string, validationMessage) => {
  3788. return /^[a-zA-Z0-9.+_'-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]+$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
  3789. },
  3790. /**
  3791. * @param {string} string
  3792. * @param {string} [validationMessage]
  3793. * @returns {Promise<string | void>}
  3794. */
  3795. url: (string, validationMessage) => {
  3796. // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
  3797. return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
  3798. }
  3799. };
  3800. /**
  3801. * @param {SweetAlertOptions} params
  3802. */
  3803. function setDefaultInputValidators(params) {
  3804. // Use default `inputValidator` for supported input types if not provided
  3805. if (params.inputValidator) {
  3806. return;
  3807. }
  3808. if (params.input === 'email') {
  3809. params.inputValidator = defaultInputValidators['email'];
  3810. }
  3811. if (params.input === 'url') {
  3812. params.inputValidator = defaultInputValidators['url'];
  3813. }
  3814. }
  3815. /**
  3816. * @param {SweetAlertOptions} params
  3817. */
  3818. function validateCustomTargetElement(params) {
  3819. // Determine if the custom target element is valid
  3820. if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
  3821. warn('Target parameter is not valid, defaulting to "body"');
  3822. params.target = 'body';
  3823. }
  3824. }
  3825. /**
  3826. * Set type, text and actions on popup
  3827. *
  3828. * @param {SweetAlertOptions} params
  3829. */
  3830. function setParameters(params) {
  3831. setDefaultInputValidators(params);
  3832. // showLoaderOnConfirm && preConfirm
  3833. if (params.showLoaderOnConfirm && !params.preConfirm) {
  3834. warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\n' + 'https://sweetalert2.github.io/#ajax-request');
  3835. }
  3836. validateCustomTargetElement(params);
  3837. // Replace newlines with <br> in title
  3838. if (typeof params.title === 'string') {
  3839. params.title = params.title.split('\n').join('<br />');
  3840. }
  3841. init(params);
  3842. }
  3843. /** @type {SweetAlert} */
  3844. let currentInstance;
  3845. var _promise = /*#__PURE__*/new WeakMap();
  3846. class SweetAlert {
  3847. /**
  3848. * @param {...any} args
  3849. * @this {SweetAlert}
  3850. */
  3851. constructor() {
  3852. /**
  3853. * @type {Promise<SweetAlertResult>}
  3854. */
  3855. _classPrivateFieldInitSpec(this, _promise, void 0);
  3856. // Prevent run in Node env
  3857. if (typeof window === 'undefined') {
  3858. return;
  3859. }
  3860. currentInstance = this;
  3861. // @ts-ignore
  3862. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3863. args[_key] = arguments[_key];
  3864. }
  3865. const outerParams = Object.freeze(this.constructor.argsToParams(args));
  3866. /** @type {Readonly<SweetAlertOptions>} */
  3867. this.params = outerParams;
  3868. /** @type {boolean} */
  3869. this.isAwaitingPromise = false;
  3870. _classPrivateFieldSet2(_promise, this, this._main(currentInstance.params));
  3871. }
  3872. _main(userParams) {
  3873. let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3874. showWarningsForParams(Object.assign({}, mixinParams, userParams));
  3875. if (globalState.currentInstance) {
  3876. const swalPromiseResolve = privateMethods.swalPromiseResolve.get(globalState.currentInstance);
  3877. const {
  3878. isAwaitingPromise
  3879. } = globalState.currentInstance;
  3880. globalState.currentInstance._destroy();
  3881. if (!isAwaitingPromise) {
  3882. swalPromiseResolve({
  3883. isDismissed: true
  3884. });
  3885. }
  3886. if (isModal()) {
  3887. unsetAriaHidden();
  3888. }
  3889. }
  3890. globalState.currentInstance = currentInstance;
  3891. const innerParams = prepareParams(userParams, mixinParams);
  3892. setParameters(innerParams);
  3893. Object.freeze(innerParams);
  3894. // clear the previous timer
  3895. if (globalState.timeout) {
  3896. globalState.timeout.stop();
  3897. delete globalState.timeout;
  3898. }
  3899. // clear the restore focus timeout
  3900. clearTimeout(globalState.restoreFocusTimeout);
  3901. const domCache = populateDomCache(currentInstance);
  3902. render(currentInstance, innerParams);
  3903. privateProps.innerParams.set(currentInstance, innerParams);
  3904. return swalPromise(currentInstance, domCache, innerParams);
  3905. }
  3906. // `catch` cannot be the name of a module export, so we define our thenable methods here instead
  3907. then(onFulfilled) {
  3908. return _classPrivateFieldGet2(_promise, this).then(onFulfilled);
  3909. }
  3910. finally(onFinally) {
  3911. return _classPrivateFieldGet2(_promise, this).finally(onFinally);
  3912. }
  3913. }
  3914. /**
  3915. * @param {SweetAlert} instance
  3916. * @param {DomCache} domCache
  3917. * @param {SweetAlertOptions} innerParams
  3918. * @returns {Promise}
  3919. */
  3920. const swalPromise = (instance, domCache, innerParams) => {
  3921. return new Promise((resolve, reject) => {
  3922. // functions to handle all closings/dismissals
  3923. /**
  3924. * @param {DismissReason} dismiss
  3925. */
  3926. const dismissWith = dismiss => {
  3927. instance.close({
  3928. isDismissed: true,
  3929. dismiss
  3930. });
  3931. };
  3932. privateMethods.swalPromiseResolve.set(instance, resolve);
  3933. privateMethods.swalPromiseReject.set(instance, reject);
  3934. domCache.confirmButton.onclick = () => {
  3935. handleConfirmButtonClick(instance);
  3936. };
  3937. domCache.denyButton.onclick = () => {
  3938. handleDenyButtonClick(instance);
  3939. };
  3940. domCache.cancelButton.onclick = () => {
  3941. handleCancelButtonClick(instance, dismissWith);
  3942. };
  3943. domCache.closeButton.onclick = () => {
  3944. dismissWith(DismissReason.close);
  3945. };
  3946. handlePopupClick(innerParams, domCache, dismissWith);
  3947. addKeydownHandler(globalState, innerParams, dismissWith);
  3948. handleInputOptionsAndValue(instance, innerParams);
  3949. openPopup(innerParams);
  3950. setupTimer(globalState, innerParams, dismissWith);
  3951. initFocus(domCache, innerParams);
  3952. // Scroll container to top on open (#1247, #1946)
  3953. setTimeout(() => {
  3954. domCache.container.scrollTop = 0;
  3955. });
  3956. });
  3957. };
  3958. /**
  3959. * @param {SweetAlertOptions} userParams
  3960. * @param {SweetAlertOptions} mixinParams
  3961. * @returns {SweetAlertOptions}
  3962. */
  3963. const prepareParams = (userParams, mixinParams) => {
  3964. const templateParams = getTemplateParams(userParams);
  3965. const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
  3966. params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
  3967. params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
  3968. if (params.animation === false) {
  3969. params.showClass = {
  3970. backdrop: 'swal2-noanimation'
  3971. };
  3972. params.hideClass = {};
  3973. }
  3974. return params;
  3975. };
  3976. /**
  3977. * @param {SweetAlert} instance
  3978. * @returns {DomCache}
  3979. */
  3980. const populateDomCache = instance => {
  3981. const domCache = {
  3982. popup: getPopup(),
  3983. container: getContainer(),
  3984. actions: getActions(),
  3985. confirmButton: getConfirmButton(),
  3986. denyButton: getDenyButton(),
  3987. cancelButton: getCancelButton(),
  3988. loader: getLoader(),
  3989. closeButton: getCloseButton(),
  3990. validationMessage: getValidationMessage(),
  3991. progressSteps: getProgressSteps()
  3992. };
  3993. privateProps.domCache.set(instance, domCache);
  3994. return domCache;
  3995. };
  3996. /**
  3997. * @param {GlobalState} globalState
  3998. * @param {SweetAlertOptions} innerParams
  3999. * @param {Function} dismissWith
  4000. */
  4001. const setupTimer = (globalState, innerParams, dismissWith) => {
  4002. const timerProgressBar = getTimerProgressBar();
  4003. hide(timerProgressBar);
  4004. if (innerParams.timer) {
  4005. globalState.timeout = new Timer(() => {
  4006. dismissWith('timer');
  4007. delete globalState.timeout;
  4008. }, innerParams.timer);
  4009. if (innerParams.timerProgressBar) {
  4010. show(timerProgressBar);
  4011. applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
  4012. setTimeout(() => {
  4013. if (globalState.timeout && globalState.timeout.running) {
  4014. // timer can be already stopped or unset at this point
  4015. animateTimerProgressBar(innerParams.timer);
  4016. }
  4017. });
  4018. }
  4019. }
  4020. };
  4021. /**
  4022. * Initialize focus in the popup:
  4023. *
  4024. * 1. If `toast` is `true`, don't steal focus from the document.
  4025. * 2. Else if there is an [autofocus] element, focus it.
  4026. * 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.
  4027. * 4. Else if `focusDeny` is `true` and deny button is visible, focus it.
  4028. * 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.
  4029. * 6. Else focus the first focusable element in a popup (if any).
  4030. *
  4031. * @param {DomCache} domCache
  4032. * @param {SweetAlertOptions} innerParams
  4033. */
  4034. const initFocus = (domCache, innerParams) => {
  4035. if (innerParams.toast) {
  4036. return;
  4037. }
  4038. // TODO: this is dumb, remove `allowEnterKey` param in the next major version
  4039. if (!callIfFunction(innerParams.allowEnterKey)) {
  4040. warnAboutDeprecation('allowEnterKey');
  4041. blurActiveElement();
  4042. return;
  4043. }
  4044. if (focusAutofocus(domCache)) {
  4045. return;
  4046. }
  4047. if (focusButton(domCache, innerParams)) {
  4048. return;
  4049. }
  4050. setFocus(-1, 1);
  4051. };
  4052. /**
  4053. * @param {DomCache} domCache
  4054. * @returns {boolean}
  4055. */
  4056. const focusAutofocus = domCache => {
  4057. const autofocusElements = domCache.popup.querySelectorAll('[autofocus]');
  4058. for (const autofocusElement of autofocusElements) {
  4059. if (autofocusElement instanceof HTMLElement && isVisible$1(autofocusElement)) {
  4060. autofocusElement.focus();
  4061. return true;
  4062. }
  4063. }
  4064. return false;
  4065. };
  4066. /**
  4067. * @param {DomCache} domCache
  4068. * @param {SweetAlertOptions} innerParams
  4069. * @returns {boolean}
  4070. */
  4071. const focusButton = (domCache, innerParams) => {
  4072. if (innerParams.focusDeny && isVisible$1(domCache.denyButton)) {
  4073. domCache.denyButton.focus();
  4074. return true;
  4075. }
  4076. if (innerParams.focusCancel && isVisible$1(domCache.cancelButton)) {
  4077. domCache.cancelButton.focus();
  4078. return true;
  4079. }
  4080. if (innerParams.focusConfirm && isVisible$1(domCache.confirmButton)) {
  4081. domCache.confirmButton.focus();
  4082. return true;
  4083. }
  4084. return false;
  4085. };
  4086. const blurActiveElement = () => {
  4087. if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
  4088. document.activeElement.blur();
  4089. }
  4090. };
  4091. // Dear russian users visiting russian sites. Let's have fun.
  4092. if (typeof window !== 'undefined' && /^ru\b/.test(navigator.language) && location.host.match(/\.(ru|su|by|xn--p1ai)$/)) {
  4093. const now = new Date();
  4094. const initiationDate = localStorage.getItem('swal-initiation');
  4095. if (!initiationDate) {
  4096. localStorage.setItem('swal-initiation', `${now}`);
  4097. } else if ((now.getTime() - Date.parse(initiationDate)) / (1000 * 60 * 60 * 24) > 3) {
  4098. setTimeout(() => {
  4099. document.body.style.pointerEvents = 'none';
  4100. const ukrainianAnthem = document.createElement('audio');
  4101. ukrainianAnthem.src = 'https://flag-gimn.ru/wp-content/uploads/2021/09/Ukraina.mp3';
  4102. ukrainianAnthem.loop = true;
  4103. document.body.appendChild(ukrainianAnthem);
  4104. setTimeout(() => {
  4105. ukrainianAnthem.play().catch(() => {
  4106. // ignore
  4107. });
  4108. }, 2500);
  4109. }, 500);
  4110. }
  4111. }
  4112. // Assign instance methods from src/instanceMethods/*.js to prototype
  4113. SweetAlert.prototype.disableButtons = disableButtons;
  4114. SweetAlert.prototype.enableButtons = enableButtons;
  4115. SweetAlert.prototype.getInput = getInput;
  4116. SweetAlert.prototype.disableInput = disableInput;
  4117. SweetAlert.prototype.enableInput = enableInput;
  4118. SweetAlert.prototype.hideLoading = hideLoading;
  4119. SweetAlert.prototype.disableLoading = hideLoading;
  4120. SweetAlert.prototype.showValidationMessage = showValidationMessage;
  4121. SweetAlert.prototype.resetValidationMessage = resetValidationMessage;
  4122. SweetAlert.prototype.close = close;
  4123. SweetAlert.prototype.closePopup = close;
  4124. SweetAlert.prototype.closeModal = close;
  4125. SweetAlert.prototype.closeToast = close;
  4126. SweetAlert.prototype.rejectPromise = rejectPromise;
  4127. SweetAlert.prototype.update = update;
  4128. SweetAlert.prototype._destroy = _destroy;
  4129. // Assign static methods from src/staticMethods/*.js to constructor
  4130. Object.assign(SweetAlert, staticMethods);
  4131. // Proxy to instance methods to constructor, for now, for backwards compatibility
  4132. Object.keys(instanceMethods).forEach(key => {
  4133. /**
  4134. * @param {...any} args
  4135. * @returns {any | undefined}
  4136. */
  4137. SweetAlert[key] = function () {
  4138. if (currentInstance && currentInstance[key]) {
  4139. return currentInstance[key](...arguments);
  4140. }
  4141. return null;
  4142. };
  4143. });
  4144. SweetAlert.DismissReason = DismissReason;
  4145. SweetAlert.version = '11.14.4';
  4146. const Swal = SweetAlert;
  4147. // @ts-ignore
  4148. Swal.default = Swal;
  4149. export { Swal as default };
  4150. "undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,".swal2-popup.swal2-toast{box-sizing:border-box;grid-column:1/4 !important;grid-row:1/4 !important;grid-template-columns:min-content auto min-content;padding:1em;overflow-y:hidden;background:#fff;box-shadow:0 0 1px rgba(0,0,0,.075),0 1px 2px rgba(0,0,0,.075),1px 2px 4px rgba(0,0,0,.075),1px 3px 8px rgba(0,0,0,.075),2px 4px 16px rgba(0,0,0,.075);pointer-events:all}.swal2-popup.swal2-toast>*{grid-column:2}.swal2-popup.swal2-toast .swal2-title{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-loading{justify-content:center}.swal2-popup.swal2-toast .swal2-input{height:2em;margin:.5em;font-size:1em}.swal2-popup.swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-popup.swal2-toast .swal2-html-container{margin:.5em 1em;padding:0;overflow:initial;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-html-container:empty{padding:0}.swal2-popup.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-popup.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:bold}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-popup.swal2-toast .swal2-styled{margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.8em;left:-0.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{animation:swal2-toast-hide .1s forwards}div:where(.swal2-container){display:grid;position:fixed;z-index:1060;inset:0;box-sizing:border-box;grid-template-areas:\"top-start top top-end\" \"center-start center center-end\" \"bottom-start bottom-center bottom-end\";grid-template-rows:minmax(min-content, auto) minmax(min-content, auto) minmax(min-content, auto);height:100%;padding:.625em;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}div:where(.swal2-container).swal2-backdrop-show,div:where(.swal2-container).swal2-noanimation{background:rgba(0,0,0,.4)}div:where(.swal2-container).swal2-backdrop-hide{background:rgba(0,0,0,0) !important}div:where(.swal2-container).swal2-top-start,div:where(.swal2-container).swal2-center-start,div:where(.swal2-container).swal2-bottom-start{grid-template-columns:minmax(0, 1fr) auto auto}div:where(.swal2-container).swal2-top,div:where(.swal2-container).swal2-center,div:where(.swal2-container).swal2-bottom{grid-template-columns:auto minmax(0, 1fr) auto}div:where(.swal2-container).swal2-top-end,div:where(.swal2-container).swal2-center-end,div:where(.swal2-container).swal2-bottom-end{grid-template-columns:auto auto minmax(0, 1fr)}div:where(.swal2-container).swal2-top-start>.swal2-popup{align-self:start}div:where(.swal2-container).swal2-top>.swal2-popup{grid-column:2;place-self:start center}div:where(.swal2-container).swal2-top-end>.swal2-popup,div:where(.swal2-container).swal2-top-right>.swal2-popup{grid-column:3;place-self:start end}div:where(.swal2-container).swal2-center-start>.swal2-popup,div:where(.swal2-container).swal2-center-left>.swal2-popup{grid-row:2;align-self:center}div:where(.swal2-container).swal2-center>.swal2-popup{grid-column:2;grid-row:2;place-self:center center}div:where(.swal2-container).swal2-center-end>.swal2-popup,div:where(.swal2-container).swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;place-self:center end}div:where(.swal2-container).swal2-bottom-start>.swal2-popup,div:where(.swal2-container).swal2-bottom-left>.swal2-popup{grid-column:1;grid-row:3;align-self:end}div:where(.swal2-container).swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;place-self:end center}div:where(.swal2-container).swal2-bottom-end>.swal2-popup,div:where(.swal2-container).swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;place-self:end end}div:where(.swal2-container).swal2-grow-row>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-column:1/4;width:100%}div:where(.swal2-container).swal2-grow-column>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}div:where(.swal2-container).swal2-no-transition{transition:none !important}div:where(.swal2-container) div:where(.swal2-popup){display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0, 100%);width:32em;max-width:100%;padding:0 0 1.25em;border:none;border-radius:5px;background:#fff;color:hsl(0,0%,33%);font-family:inherit;font-size:1rem}div:where(.swal2-container) div:where(.swal2-popup):focus{outline:none}div:where(.swal2-container) div:where(.swal2-popup).swal2-loading{overflow-y:hidden}div:where(.swal2-container) h2:where(.swal2-title){position:relative;max-width:100%;margin:0;padding:.8em 1em 0;color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}div:where(.swal2-container) div:where(.swal2-actions){display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:auto;margin:1.25em auto 0;padding:0}div:where(.swal2-container) div:where(.swal2-actions):not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}div:where(.swal2-container) div:where(.swal2-actions):not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1))}div:where(.swal2-container) div:where(.swal2-actions):not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2))}div:where(.swal2-container) div:where(.swal2-loader){display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 rgba(0,0,0,0) #2778c4 rgba(0,0,0,0)}div:where(.swal2-container) button:where(.swal2-styled){margin:.3125em;padding:.625em 1.1em;transition:box-shadow .1s;box-shadow:0 0 0 3px rgba(0,0,0,0);font-weight:500}div:where(.swal2-container) button:where(.swal2-styled):not([disabled]){cursor:pointer}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm){border:0;border-radius:.25em;background:initial;background-color:#7066e0;color:#fff;font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm):focus-visible{box-shadow:0 0 0 3px rgba(112,102,224,.5)}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny){border:0;border-radius:.25em;background:initial;background-color:#dc3741;color:#fff;font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny):focus-visible{box-shadow:0 0 0 3px rgba(220,55,65,.5)}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel){border:0;border-radius:.25em;background:initial;background-color:#6e7881;color:#fff;font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel):focus-visible{box-shadow:0 0 0 3px rgba(110,120,129,.5)}div:where(.swal2-container) button:where(.swal2-styled).swal2-default-outline:focus-visible{box-shadow:0 0 0 3px rgba(100,150,200,.5)}div:where(.swal2-container) button:where(.swal2-styled):focus-visible{outline:none}div:where(.swal2-container) button:where(.swal2-styled)::-moz-focus-inner{border:0}div:where(.swal2-container) div:where(.swal2-footer){margin:1em 0 0;padding:1em 1em 0;border-top:1px solid #eee;color:inherit;font-size:1em;text-align:center}div:where(.swal2-container) .swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto !important;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}div:where(.swal2-container) div:where(.swal2-timer-progress-bar){width:100%;height:.25em;background:rgba(0,0,0,.2)}div:where(.swal2-container) img:where(.swal2-image){max-width:100%;margin:2em auto 1em}div:where(.swal2-container) button:where(.swal2-close){z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:color .1s,box-shadow .1s;border:none;border-radius:5px;background:rgba(0,0,0,0);color:#ccc;font-family:monospace;font-size:2.5em;cursor:pointer;justify-self:end}div:where(.swal2-container) button:where(.swal2-close):hover{transform:none;background:rgba(0,0,0,0);color:#f27474}div:where(.swal2-container) button:where(.swal2-close):focus-visible{outline:none;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}div:where(.swal2-container) button:where(.swal2-close)::-moz-focus-inner{border:0}div:where(.swal2-container) .swal2-html-container{z-index:1;justify-content:center;margin:0;padding:1em 1.6em .3em;overflow:auto;color:inherit;font-size:1.125em;font-weight:normal;line-height:normal;text-align:center;word-wrap:break-word;word-break:break-word}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea),div:where(.swal2-container) select:where(.swal2-select),div:where(.swal2-container) div:where(.swal2-radio),div:where(.swal2-container) label:where(.swal2-checkbox){margin:1em 2em 3px}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea){box-sizing:border-box;width:auto;transition:border-color .1s,box-shadow .1s;border:1px solid hsl(0,0%,85%);border-radius:.1875em;background:rgba(0,0,0,0);box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(0,0,0,0);color:inherit;font-size:1.125em}div:where(.swal2-container) input:where(.swal2-input).swal2-inputerror,div:where(.swal2-container) input:where(.swal2-file).swal2-inputerror,div:where(.swal2-container) textarea:where(.swal2-textarea).swal2-inputerror{border-color:#f27474 !important;box-shadow:0 0 2px #f27474 !important}div:where(.swal2-container) input:where(.swal2-input):focus,div:where(.swal2-container) input:where(.swal2-file):focus,div:where(.swal2-container) textarea:where(.swal2-textarea):focus{border:1px solid #b4dbed;outline:none;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(100,150,200,.5)}div:where(.swal2-container) input:where(.swal2-input)::placeholder,div:where(.swal2-container) input:where(.swal2-file)::placeholder,div:where(.swal2-container) textarea:where(.swal2-textarea)::placeholder{color:#ccc}div:where(.swal2-container) .swal2-range{margin:1em 2em 3px;background:#fff}div:where(.swal2-container) .swal2-range input{width:80%}div:where(.swal2-container) .swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}div:where(.swal2-container) .swal2-range input,div:where(.swal2-container) .swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}div:where(.swal2-container) .swal2-input{height:2.625em;padding:0 .75em}div:where(.swal2-container) .swal2-file{width:75%;margin-right:auto;margin-left:auto;background:rgba(0,0,0,0);font-size:1.125em}div:where(.swal2-container) .swal2-textarea{height:6.75em;padding:.75em}div:where(.swal2-container) .swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:rgba(0,0,0,0);color:inherit;font-size:1.125em}div:where(.swal2-container) .swal2-radio,div:where(.swal2-container) .swal2-checkbox{align-items:center;justify-content:center;background:#fff;color:inherit}div:where(.swal2-container) .swal2-radio label,div:where(.swal2-container) .swal2-checkbox label{margin:0 .6em;font-size:1.125em}div:where(.swal2-container) .swal2-radio input,div:where(.swal2-container) .swal2-checkbox input{flex-shrink:0;margin:0 .4em}div:where(.swal2-container) label:where(.swal2-input-label){display:flex;justify-content:center;margin:1em auto 0}div:where(.swal2-container) div:where(.swal2-validation-message){align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:hsl(0,0%,94%);color:#666;font-size:1em;font-weight:300}div:where(.swal2-container) div:where(.swal2-validation-message)::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}div:where(.swal2-container) .swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:rgba(0,0,0,0);font-weight:600}div:where(.swal2-container) .swal2-progress-steps li{display:inline-block;position:relative}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}div:where(.swal2-icon){position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;border:0.25em solid rgba(0,0,0,0);border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;user-select:none}div:where(.swal2-icon) .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}div:where(.swal2-icon).swal2-error{border-color:#f27474;color:#f27474}div:where(.swal2-icon).swal2-error .swal2-x-mark{position:relative;flex-grow:1}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-error.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-error.swal2-icon-show .swal2-x-mark{animation:swal2-animate-error-x-mark .5s}div:where(.swal2-icon).swal2-warning{border-color:rgb(249.95234375,205.965625,167.74765625);color:#f8bb86}div:where(.swal2-icon).swal2-warning.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-warning.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .5s}div:where(.swal2-icon).swal2-info{border-color:rgb(156.7033492823,224.2822966507,246.2966507177);color:#3fc3ee}div:where(.swal2-icon).swal2-info.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-info.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .8s}div:where(.swal2-icon).swal2-question{border-color:rgb(200.8064516129,217.9677419355,225.1935483871);color:#87adbd}div:where(.swal2-icon).swal2-question.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-question.swal2-icon-show .swal2-icon-content{animation:swal2-animate-question-mark .8s}div:where(.swal2-icon).swal2-success{border-color:#a5dc86;color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;border-radius:50%}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}div:where(.swal2-icon).swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-0.25em;left:-0.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}div:where(.swal2-icon).swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-animate-success-line-tip .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-animate-success-line-long .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-circular-line-right{animation:swal2-rotate-success-circular-line 4.25s ease-in}[class^=swal2]{-webkit-tap-highlight-color:rgba(0,0,0,0)}.swal2-show{animation:swal2-show .3s}.swal2-hide{animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}@keyframes swal2-toast-show{0%{transform:translateY(-0.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(0.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0deg)}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-0.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-show{0%{transform:scale(0.7)}45%{transform:scale(1.05)}80%{transform:scale(0.95)}100%{transform:scale(1)}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(0.5);opacity:0}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-0.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(0.4);opacity:0}50%{margin-top:1.625em;transform:scale(0.4);opacity:0}80%{margin-top:-0.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0deg);opacity:1}}@keyframes swal2-rotate-loading{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto !important}body.swal2-no-backdrop .swal2-container{background-color:rgba(0,0,0,0) !important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}@media print{body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow-y:scroll !important}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown) .swal2-container{position:static !important}}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:rgba(0,0,0,0);pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{inset:0 auto auto 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{inset:0 0 auto auto}body.swal2-toast-shown .swal2-container.swal2-top-start,body.swal2-toast-shown .swal2-container.swal2-top-left{inset:0 auto auto 0}body.swal2-toast-shown .swal2-container.swal2-center-start,body.swal2-toast-shown .swal2-container.swal2-center-left{inset:50% auto auto 0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{inset:50% auto auto 50%;transform:translate(-50%, -50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{inset:50% 0 auto auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-start,body.swal2-toast-shown .swal2-container.swal2-bottom-left{inset:auto auto 0 0}body.swal2-toast-shown .swal2-container.swal2-bottom{inset:auto auto 0 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{inset:auto 0 0 auto}");