Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

4499 lignes
159 KiB

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