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.

3392 lignes
106KB

  1. /*!
  2. * sweetalert2 v11.4.0
  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 = global || self, global.Sweetalert2 = factory());
  9. }(this, function () { 'use strict';
  10. const consolePrefix = 'SweetAlert2:';
  11. /**
  12. * Filter the unique values into a new array
  13. * @param arr
  14. */
  15. const uniqueArray = arr => {
  16. const result = [];
  17. for (let i = 0; i < arr.length; i++) {
  18. if (result.indexOf(arr[i]) === -1) {
  19. result.push(arr[i]);
  20. }
  21. }
  22. return result;
  23. };
  24. /**
  25. * Capitalize the first letter of a string
  26. * @param {string} str
  27. * @returns {string}
  28. */
  29. const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
  30. /**
  31. * @param {NodeList | HTMLCollection | NamedNodeMap} nodeList
  32. * @returns {array}
  33. */
  34. const toArray = nodeList => Array.prototype.slice.call(nodeList);
  35. /**
  36. * Standardize console warnings
  37. * @param {string | array} message
  38. */
  39. const warn = message => {
  40. console.warn("".concat(consolePrefix, " ").concat(typeof message === 'object' ? message.join(' ') : message));
  41. };
  42. /**
  43. * Standardize console errors
  44. * @param {string} message
  45. */
  46. const error = message => {
  47. console.error("".concat(consolePrefix, " ").concat(message));
  48. };
  49. /**
  50. * Private global state for `warnOnce`
  51. * @type {Array}
  52. * @private
  53. */
  54. const previousWarnOnceMessages = [];
  55. /**
  56. * Show a console warning, but only if it hasn't already been shown
  57. * @param {string} message
  58. */
  59. const warnOnce = message => {
  60. if (!previousWarnOnceMessages.includes(message)) {
  61. previousWarnOnceMessages.push(message);
  62. warn(message);
  63. }
  64. };
  65. /**
  66. * Show a one-time console warning about deprecated params/methods
  67. */
  68. const warnAboutDeprecation = (deprecatedParam, useInstead) => {
  69. warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead."));
  70. };
  71. /**
  72. * If `arg` is a function, call it (with no arguments or context) and return the result.
  73. * Otherwise, just pass the value through
  74. * @param arg
  75. */
  76. const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
  77. const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
  78. const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
  79. const isPromise = arg => arg && Promise.resolve(arg) === arg;
  80. const defaultParams = {
  81. title: '',
  82. titleText: '',
  83. text: '',
  84. html: '',
  85. footer: '',
  86. icon: undefined,
  87. iconColor: undefined,
  88. iconHtml: undefined,
  89. template: undefined,
  90. toast: false,
  91. showClass: {
  92. popup: 'swal2-show',
  93. backdrop: 'swal2-backdrop-show',
  94. icon: 'swal2-icon-show'
  95. },
  96. hideClass: {
  97. popup: 'swal2-hide',
  98. backdrop: 'swal2-backdrop-hide',
  99. icon: 'swal2-icon-hide'
  100. },
  101. customClass: {},
  102. target: 'body',
  103. color: undefined,
  104. backdrop: true,
  105. heightAuto: true,
  106. allowOutsideClick: true,
  107. allowEscapeKey: true,
  108. allowEnterKey: true,
  109. stopKeydownPropagation: true,
  110. keydownListenerCapture: false,
  111. showConfirmButton: true,
  112. showDenyButton: false,
  113. showCancelButton: false,
  114. preConfirm: undefined,
  115. preDeny: undefined,
  116. confirmButtonText: 'OK',
  117. confirmButtonAriaLabel: '',
  118. confirmButtonColor: undefined,
  119. denyButtonText: 'No',
  120. denyButtonAriaLabel: '',
  121. denyButtonColor: undefined,
  122. cancelButtonText: 'Cancel',
  123. cancelButtonAriaLabel: '',
  124. cancelButtonColor: undefined,
  125. buttonsStyling: true,
  126. reverseButtons: false,
  127. focusConfirm: true,
  128. focusDeny: false,
  129. focusCancel: false,
  130. returnFocus: true,
  131. showCloseButton: false,
  132. closeButtonHtml: '&times;',
  133. closeButtonAriaLabel: 'Close this dialog',
  134. loaderHtml: '',
  135. showLoaderOnConfirm: false,
  136. showLoaderOnDeny: false,
  137. imageUrl: undefined,
  138. imageWidth: undefined,
  139. imageHeight: undefined,
  140. imageAlt: '',
  141. timer: undefined,
  142. timerProgressBar: false,
  143. width: undefined,
  144. padding: undefined,
  145. background: undefined,
  146. input: undefined,
  147. inputPlaceholder: '',
  148. inputLabel: '',
  149. inputValue: '',
  150. inputOptions: {},
  151. inputAutoTrim: true,
  152. inputAttributes: {},
  153. inputValidator: undefined,
  154. returnInputValueOnDeny: false,
  155. validationMessage: undefined,
  156. grow: false,
  157. position: 'center',
  158. progressSteps: [],
  159. currentProgressStep: undefined,
  160. progressStepsDistance: undefined,
  161. willOpen: undefined,
  162. didOpen: undefined,
  163. didRender: undefined,
  164. willClose: undefined,
  165. didClose: undefined,
  166. didDestroy: undefined,
  167. scrollbarPadding: true
  168. };
  169. 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'];
  170. const deprecatedParams = {};
  171. const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
  172. /**
  173. * Is valid parameter
  174. * @param {string} paramName
  175. */
  176. const isValidParameter = paramName => {
  177. return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
  178. };
  179. /**
  180. * Is valid parameter for Swal.update() method
  181. * @param {string} paramName
  182. */
  183. const isUpdatableParameter = paramName => {
  184. return updatableParams.indexOf(paramName) !== -1;
  185. };
  186. /**
  187. * Is deprecated parameter
  188. * @param {string} paramName
  189. */
  190. const isDeprecatedParameter = paramName => {
  191. return deprecatedParams[paramName];
  192. };
  193. const checkIfParamIsValid = param => {
  194. if (!isValidParameter(param)) {
  195. warn("Unknown parameter \"".concat(param, "\""));
  196. }
  197. };
  198. const checkIfToastParamIsValid = param => {
  199. if (toastIncompatibleParams.includes(param)) {
  200. warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
  201. }
  202. };
  203. const checkIfParamIsDeprecated = param => {
  204. if (isDeprecatedParameter(param)) {
  205. warnAboutDeprecation(param, isDeprecatedParameter(param));
  206. }
  207. };
  208. /**
  209. * Show relevant warnings for given params
  210. *
  211. * @param params
  212. */
  213. const showWarningsForParams = params => {
  214. if (!params.backdrop && params.allowOutsideClick) {
  215. warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
  216. }
  217. for (const param in params) {
  218. checkIfParamIsValid(param);
  219. if (params.toast) {
  220. checkIfToastParamIsValid(param);
  221. }
  222. checkIfParamIsDeprecated(param);
  223. }
  224. };
  225. const swalPrefix = 'swal2-';
  226. const prefix = items => {
  227. const result = {};
  228. for (const i in items) {
  229. result[items[i]] = swalPrefix + items[i];
  230. }
  231. return result;
  232. };
  233. const swalClasses = prefix(['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']);
  234. const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
  235. /**
  236. * Gets the popup container which contains the backdrop and the popup itself.
  237. *
  238. * @returns {HTMLElement | null}
  239. */
  240. const getContainer = () => document.body.querySelector(".".concat(swalClasses.container));
  241. const elementBySelector = selectorString => {
  242. const container = getContainer();
  243. return container ? container.querySelector(selectorString) : null;
  244. };
  245. const elementByClass = className => {
  246. return elementBySelector(".".concat(className));
  247. };
  248. const getPopup = () => elementByClass(swalClasses.popup);
  249. const getIcon = () => elementByClass(swalClasses.icon);
  250. const getTitle = () => elementByClass(swalClasses.title);
  251. const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
  252. const getImage = () => elementByClass(swalClasses.image);
  253. const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
  254. const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
  255. const getConfirmButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm));
  256. const getDenyButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny));
  257. const getInputLabel = () => elementByClass(swalClasses['input-label']);
  258. const getLoader = () => elementBySelector(".".concat(swalClasses.loader));
  259. const getCancelButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel));
  260. const getActions = () => elementByClass(swalClasses.actions);
  261. const getFooter = () => elementByClass(swalClasses.footer);
  262. const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
  263. const getCloseButton = () => elementByClass(swalClasses.close); // https://github.com/jkup/focusable/blob/master/index.js
  264. const focusable = "\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex=\"0\"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n";
  265. const getFocusableElements = () => {
  266. const focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex
  267. .sort((a, b) => {
  268. const tabindexA = parseInt(a.getAttribute('tabindex'));
  269. const tabindexB = parseInt(b.getAttribute('tabindex'));
  270. if (tabindexA > tabindexB) {
  271. return 1;
  272. } else if (tabindexA < tabindexB) {
  273. return -1;
  274. }
  275. return 0;
  276. });
  277. const otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1');
  278. return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible(el));
  279. };
  280. const isModal = () => {
  281. return !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
  282. };
  283. const isToast = () => {
  284. return getPopup() && hasClass(getPopup(), swalClasses.toast);
  285. };
  286. const isLoading = () => {
  287. return getPopup().hasAttribute('data-loading');
  288. };
  289. const states = {
  290. previousBodyPadding: null
  291. };
  292. /**
  293. * Securely set innerHTML of an element
  294. * https://github.com/sweetalert2/sweetalert2/issues/1926
  295. *
  296. * @param {HTMLElement} elem
  297. * @param {string} html
  298. */
  299. const setInnerHtml = (elem, html) => {
  300. elem.textContent = '';
  301. if (html) {
  302. const parser = new DOMParser();
  303. const parsed = parser.parseFromString(html, "text/html");
  304. toArray(parsed.querySelector('head').childNodes).forEach(child => {
  305. elem.appendChild(child);
  306. });
  307. toArray(parsed.querySelector('body').childNodes).forEach(child => {
  308. elem.appendChild(child);
  309. });
  310. }
  311. };
  312. /**
  313. * @param {HTMLElement} elem
  314. * @param {string} className
  315. * @returns {boolean}
  316. */
  317. const hasClass = (elem, className) => {
  318. if (!className) {
  319. return false;
  320. }
  321. const classList = className.split(/\s+/);
  322. for (let i = 0; i < classList.length; i++) {
  323. if (!elem.classList.contains(classList[i])) {
  324. return false;
  325. }
  326. }
  327. return true;
  328. };
  329. const removeCustomClasses = (elem, params) => {
  330. toArray(elem.classList).forEach(className => {
  331. if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) {
  332. elem.classList.remove(className);
  333. }
  334. });
  335. };
  336. const applyCustomClass = (elem, params, className) => {
  337. removeCustomClasses(elem, params);
  338. if (params.customClass && params.customClass[className]) {
  339. if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
  340. return warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(typeof params.customClass[className], "\""));
  341. }
  342. addClass(elem, params.customClass[className]);
  343. }
  344. };
  345. /**
  346. * @param {HTMLElement} popup
  347. * @param {string} inputType
  348. * @returns {HTMLInputElement | null}
  349. */
  350. const getInput = (popup, inputType) => {
  351. if (!inputType) {
  352. return null;
  353. }
  354. switch (inputType) {
  355. case 'select':
  356. case 'textarea':
  357. case 'file':
  358. return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses[inputType]));
  359. case 'checkbox':
  360. return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.checkbox, " input"));
  361. case 'radio':
  362. return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:checked")) || popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:first-child"));
  363. case 'range':
  364. return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.range, " input"));
  365. default:
  366. return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.input));
  367. }
  368. };
  369. /**
  370. * @param {HTMLInputElement} input
  371. */
  372. const focusInput = input => {
  373. input.focus(); // place cursor at end of text in text input
  374. if (input.type !== 'file') {
  375. // http://stackoverflow.com/a/2345915
  376. const val = input.value;
  377. input.value = '';
  378. input.value = val;
  379. }
  380. };
  381. /**
  382. * @param {HTMLElement | HTMLElement[] | null} target
  383. * @param {string | string[]} classList
  384. * @param {boolean} condition
  385. */
  386. const toggleClass = (target, classList, condition) => {
  387. if (!target || !classList) {
  388. return;
  389. }
  390. if (typeof classList === 'string') {
  391. classList = classList.split(/\s+/).filter(Boolean);
  392. }
  393. classList.forEach(className => {
  394. if (Array.isArray(target)) {
  395. target.forEach(elem => {
  396. condition ? elem.classList.add(className) : elem.classList.remove(className);
  397. });
  398. } else {
  399. condition ? target.classList.add(className) : target.classList.remove(className);
  400. }
  401. });
  402. };
  403. /**
  404. * @param {HTMLElement | HTMLElement[] | null} target
  405. * @param {string | string[]} classList
  406. */
  407. const addClass = (target, classList) => {
  408. toggleClass(target, classList, true);
  409. };
  410. /**
  411. * @param {HTMLElement | HTMLElement[] | null} target
  412. * @param {string | string[]} classList
  413. */
  414. const removeClass = (target, classList) => {
  415. toggleClass(target, classList, false);
  416. };
  417. /**
  418. * Get direct child of an element by class name
  419. *
  420. * @param {HTMLElement} elem
  421. * @param {string} className
  422. * @returns {HTMLElement | null}
  423. */
  424. const getDirectChildByClass = (elem, className) => {
  425. const childNodes = toArray(elem.childNodes);
  426. for (let i = 0; i < childNodes.length; i++) {
  427. if (hasClass(childNodes[i], className)) {
  428. return childNodes[i];
  429. }
  430. }
  431. };
  432. /**
  433. * @param {HTMLElement} elem
  434. * @param {string} property
  435. * @param {*} value
  436. */
  437. const applyNumericalStyle = (elem, property, value) => {
  438. if (value === "".concat(parseInt(value))) {
  439. value = parseInt(value);
  440. }
  441. if (value || parseInt(value) === 0) {
  442. elem.style[property] = typeof value === 'number' ? "".concat(value, "px") : value;
  443. } else {
  444. elem.style.removeProperty(property);
  445. }
  446. };
  447. /**
  448. * @param {HTMLElement} elem
  449. * @param {string} display
  450. */
  451. const show = function (elem) {
  452. let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
  453. elem.style.display = display;
  454. };
  455. /**
  456. * @param {HTMLElement} elem
  457. */
  458. const hide = elem => {
  459. elem.style.display = 'none';
  460. };
  461. const setStyle = (parent, selector, property, value) => {
  462. const el = parent.querySelector(selector);
  463. if (el) {
  464. el.style[property] = value;
  465. }
  466. };
  467. const toggle = (elem, condition, display) => {
  468. condition ? show(elem, display) : hide(elem);
  469. }; // borrowed from jquery $(elem).is(':visible') implementation
  470. const isVisible = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
  471. const allButtonsAreHidden = () => !isVisible(getConfirmButton()) && !isVisible(getDenyButton()) && !isVisible(getCancelButton());
  472. const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight); // borrowed from https://stackoverflow.com/a/46352119
  473. const hasCssAnimation = elem => {
  474. const style = window.getComputedStyle(elem);
  475. const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
  476. const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
  477. return animDuration > 0 || transDuration > 0;
  478. };
  479. const animateTimerProgressBar = function (timer) {
  480. let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  481. const timerProgressBar = getTimerProgressBar();
  482. if (isVisible(timerProgressBar)) {
  483. if (reset) {
  484. timerProgressBar.style.transition = 'none';
  485. timerProgressBar.style.width = '100%';
  486. }
  487. setTimeout(() => {
  488. timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear");
  489. timerProgressBar.style.width = '0%';
  490. }, 10);
  491. }
  492. };
  493. const stopTimerProgressBar = () => {
  494. const timerProgressBar = getTimerProgressBar();
  495. const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  496. timerProgressBar.style.removeProperty('transition');
  497. timerProgressBar.style.width = '100%';
  498. const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  499. const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
  500. timerProgressBar.style.removeProperty('transition');
  501. timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%");
  502. };
  503. /**
  504. * Detect Node env
  505. *
  506. * @returns {boolean}
  507. */
  508. const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
  509. const RESTORE_FOCUS_TIMEOUT = 100;
  510. const globalState = {};
  511. const focusPreviousActiveElement = () => {
  512. if (globalState.previousActiveElement && globalState.previousActiveElement.focus) {
  513. globalState.previousActiveElement.focus();
  514. globalState.previousActiveElement = null;
  515. } else if (document.body) {
  516. document.body.focus();
  517. }
  518. }; // Restore previous active (focused) element
  519. const restoreActiveElement = returnFocus => {
  520. return new Promise(resolve => {
  521. if (!returnFocus) {
  522. return resolve();
  523. }
  524. const x = window.scrollX;
  525. const y = window.scrollY;
  526. globalState.restoreFocusTimeout = setTimeout(() => {
  527. focusPreviousActiveElement();
  528. resolve();
  529. }, RESTORE_FOCUS_TIMEOUT); // issues/900
  530. window.scrollTo(x, y);
  531. });
  532. };
  533. const sweetHTML = "\n <div aria-labelledby=\"".concat(swalClasses.title, "\" aria-describedby=\"").concat(swalClasses['html-container'], "\" class=\"").concat(swalClasses.popup, "\" tabindex=\"-1\">\n <button type=\"button\" class=\"").concat(swalClasses.close, "\"></button>\n <ul class=\"").concat(swalClasses['progress-steps'], "\"></ul>\n <div class=\"").concat(swalClasses.icon, "\"></div>\n <img class=\"").concat(swalClasses.image, "\" />\n <h2 class=\"").concat(swalClasses.title, "\" id=\"").concat(swalClasses.title, "\"></h2>\n <div class=\"").concat(swalClasses['html-container'], "\" id=\"").concat(swalClasses['html-container'], "\"></div>\n <input class=\"").concat(swalClasses.input, "\" />\n <input type=\"file\" class=\"").concat(swalClasses.file, "\" />\n <div class=\"").concat(swalClasses.range, "\">\n <input type=\"range\" />\n <output></output>\n </div>\n <select class=\"").concat(swalClasses.select, "\"></select>\n <div class=\"").concat(swalClasses.radio, "\"></div>\n <label for=\"").concat(swalClasses.checkbox, "\" class=\"").concat(swalClasses.checkbox, "\">\n <input type=\"checkbox\" />\n <span class=\"").concat(swalClasses.label, "\"></span>\n </label>\n <textarea class=\"").concat(swalClasses.textarea, "\"></textarea>\n <div class=\"").concat(swalClasses['validation-message'], "\" id=\"").concat(swalClasses['validation-message'], "\"></div>\n <div class=\"").concat(swalClasses.actions, "\">\n <div class=\"").concat(swalClasses.loader, "\"></div>\n <button type=\"button\" class=\"").concat(swalClasses.confirm, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.deny, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.cancel, "\"></button>\n </div>\n <div class=\"").concat(swalClasses.footer, "\"></div>\n <div class=\"").concat(swalClasses['timer-progress-bar-container'], "\">\n <div class=\"").concat(swalClasses['timer-progress-bar'], "\"></div>\n </div>\n </div>\n").replace(/(^|\n)\s*/g, '');
  534. const resetOldContainer = () => {
  535. const oldContainer = getContainer();
  536. if (!oldContainer) {
  537. return false;
  538. }
  539. oldContainer.remove();
  540. removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
  541. return true;
  542. };
  543. const resetValidationMessage = () => {
  544. globalState.currentInstance.resetValidationMessage();
  545. };
  546. const addInputChangeListeners = () => {
  547. const popup = getPopup();
  548. const input = getDirectChildByClass(popup, swalClasses.input);
  549. const file = getDirectChildByClass(popup, swalClasses.file);
  550. const range = popup.querySelector(".".concat(swalClasses.range, " input"));
  551. const rangeOutput = popup.querySelector(".".concat(swalClasses.range, " output"));
  552. const select = getDirectChildByClass(popup, swalClasses.select);
  553. const checkbox = popup.querySelector(".".concat(swalClasses.checkbox, " input"));
  554. const textarea = getDirectChildByClass(popup, swalClasses.textarea);
  555. input.oninput = resetValidationMessage;
  556. file.onchange = resetValidationMessage;
  557. select.onchange = resetValidationMessage;
  558. checkbox.onchange = resetValidationMessage;
  559. textarea.oninput = resetValidationMessage;
  560. range.oninput = () => {
  561. resetValidationMessage();
  562. rangeOutput.value = range.value;
  563. };
  564. range.onchange = () => {
  565. resetValidationMessage();
  566. range.nextSibling.value = range.value;
  567. };
  568. };
  569. const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;
  570. const setupAccessibility = params => {
  571. const popup = getPopup();
  572. popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
  573. popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
  574. if (!params.toast) {
  575. popup.setAttribute('aria-modal', 'true');
  576. }
  577. };
  578. const setupRTL = targetElement => {
  579. if (window.getComputedStyle(targetElement).direction === 'rtl') {
  580. addClass(getContainer(), swalClasses.rtl);
  581. }
  582. };
  583. /*
  584. * Add modal + backdrop to DOM
  585. */
  586. const init = params => {
  587. // Clean up the old popup container if it exists
  588. const oldContainerExisted = resetOldContainer();
  589. /* istanbul ignore if */
  590. if (isNodeEnv()) {
  591. error('SweetAlert2 requires document to initialize');
  592. return;
  593. }
  594. const container = document.createElement('div');
  595. container.className = swalClasses.container;
  596. if (oldContainerExisted) {
  597. addClass(container, swalClasses['no-transition']);
  598. }
  599. setInnerHtml(container, sweetHTML);
  600. const targetElement = getTarget(params.target);
  601. targetElement.appendChild(container);
  602. setupAccessibility(params);
  603. setupRTL(targetElement);
  604. addInputChangeListeners();
  605. };
  606. /**
  607. * @param {HTMLElement | object | string} param
  608. * @param {HTMLElement} target
  609. */
  610. const parseHtmlToContainer = (param, target) => {
  611. // DOM element
  612. if (param instanceof HTMLElement) {
  613. target.appendChild(param);
  614. } // Object
  615. else if (typeof param === 'object') {
  616. handleObject(param, target);
  617. } // Plain string
  618. else if (param) {
  619. setInnerHtml(target, param);
  620. }
  621. };
  622. /**
  623. * @param {object} param
  624. * @param {HTMLElement} target
  625. */
  626. const handleObject = (param, target) => {
  627. // JQuery element(s)
  628. if (param.jquery) {
  629. handleJqueryElem(target, param);
  630. } // For other objects use their string representation
  631. else {
  632. setInnerHtml(target, param.toString());
  633. }
  634. };
  635. const handleJqueryElem = (target, elem) => {
  636. target.textContent = '';
  637. if (0 in elem) {
  638. for (let i = 0; (i in elem); i++) {
  639. target.appendChild(elem[i].cloneNode(true));
  640. }
  641. } else {
  642. target.appendChild(elem.cloneNode(true));
  643. }
  644. };
  645. const animationEndEvent = (() => {
  646. // Prevent run in Node env
  647. /* istanbul ignore if */
  648. if (isNodeEnv()) {
  649. return false;
  650. }
  651. const testEl = document.createElement('div');
  652. const transEndEventNames = {
  653. WebkitAnimation: 'webkitAnimationEnd',
  654. // Chrome, Safari and Opera
  655. animation: 'animationend' // Standard syntax
  656. };
  657. for (const i in transEndEventNames) {
  658. if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
  659. return transEndEventNames[i];
  660. }
  661. }
  662. return false;
  663. })();
  664. // https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
  665. const measureScrollbar = () => {
  666. const scrollDiv = document.createElement('div');
  667. scrollDiv.className = swalClasses['scrollbar-measure'];
  668. document.body.appendChild(scrollDiv);
  669. const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
  670. document.body.removeChild(scrollDiv);
  671. return scrollbarWidth;
  672. };
  673. const renderActions = (instance, params) => {
  674. const actions = getActions();
  675. const loader = getLoader(); // Actions (buttons) wrapper
  676. if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
  677. hide(actions);
  678. } else {
  679. show(actions);
  680. } // Custom class
  681. applyCustomClass(actions, params, 'actions'); // Render all the buttons
  682. renderButtons(actions, loader, params); // Loader
  683. setInnerHtml(loader, params.loaderHtml);
  684. applyCustomClass(loader, params, 'loader');
  685. };
  686. function renderButtons(actions, loader, params) {
  687. const confirmButton = getConfirmButton();
  688. const denyButton = getDenyButton();
  689. const cancelButton = getCancelButton(); // Render buttons
  690. renderButton(confirmButton, 'confirm', params);
  691. renderButton(denyButton, 'deny', params);
  692. renderButton(cancelButton, 'cancel', params);
  693. handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
  694. if (params.reverseButtons) {
  695. if (params.toast) {
  696. actions.insertBefore(cancelButton, confirmButton);
  697. actions.insertBefore(denyButton, confirmButton);
  698. } else {
  699. actions.insertBefore(cancelButton, loader);
  700. actions.insertBefore(denyButton, loader);
  701. actions.insertBefore(confirmButton, loader);
  702. }
  703. }
  704. }
  705. function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
  706. if (!params.buttonsStyling) {
  707. return removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
  708. }
  709. addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors
  710. if (params.confirmButtonColor) {
  711. confirmButton.style.backgroundColor = params.confirmButtonColor;
  712. addClass(confirmButton, swalClasses['default-outline']);
  713. }
  714. if (params.denyButtonColor) {
  715. denyButton.style.backgroundColor = params.denyButtonColor;
  716. addClass(denyButton, swalClasses['default-outline']);
  717. }
  718. if (params.cancelButtonColor) {
  719. cancelButton.style.backgroundColor = params.cancelButtonColor;
  720. addClass(cancelButton, swalClasses['default-outline']);
  721. }
  722. }
  723. function renderButton(button, buttonType, params) {
  724. toggle(button, params["show".concat(capitalizeFirstLetter(buttonType), "Button")], 'inline-block');
  725. setInnerHtml(button, params["".concat(buttonType, "ButtonText")]); // Set caption text
  726. button.setAttribute('aria-label', params["".concat(buttonType, "ButtonAriaLabel")]); // ARIA label
  727. // Add buttons custom classes
  728. button.className = swalClasses[buttonType];
  729. applyCustomClass(button, params, "".concat(buttonType, "Button"));
  730. addClass(button, params["".concat(buttonType, "ButtonClass")]);
  731. }
  732. function handleBackdropParam(container, backdrop) {
  733. if (typeof backdrop === 'string') {
  734. container.style.background = backdrop;
  735. } else if (!backdrop) {
  736. addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
  737. }
  738. }
  739. function handlePositionParam(container, position) {
  740. if (position in swalClasses) {
  741. addClass(container, swalClasses[position]);
  742. } else {
  743. warn('The "position" parameter is not valid, defaulting to "center"');
  744. addClass(container, swalClasses.center);
  745. }
  746. }
  747. function handleGrowParam(container, grow) {
  748. if (grow && typeof grow === 'string') {
  749. const growClass = "grow-".concat(grow);
  750. if (growClass in swalClasses) {
  751. addClass(container, swalClasses[growClass]);
  752. }
  753. }
  754. }
  755. const renderContainer = (instance, params) => {
  756. const container = getContainer();
  757. if (!container) {
  758. return;
  759. }
  760. handleBackdropParam(container, params.backdrop);
  761. handlePositionParam(container, params.position);
  762. handleGrowParam(container, params.grow); // Custom class
  763. applyCustomClass(container, params, 'container');
  764. };
  765. /**
  766. * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
  767. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  768. * This is the approach that Babel will probably take to implement private methods/fields
  769. * https://github.com/tc39/proposal-private-methods
  770. * https://github.com/babel/babel/pull/7555
  771. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  772. * then we can use that language feature.
  773. */
  774. var privateProps = {
  775. awaitingPromise: new WeakMap(),
  776. promise: new WeakMap(),
  777. innerParams: new WeakMap(),
  778. domCache: new WeakMap()
  779. };
  780. const inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
  781. const renderInput = (instance, params) => {
  782. const popup = getPopup();
  783. const innerParams = privateProps.innerParams.get(instance);
  784. const rerender = !innerParams || params.input !== innerParams.input;
  785. inputTypes.forEach(inputType => {
  786. const inputClass = swalClasses[inputType];
  787. const inputContainer = getDirectChildByClass(popup, inputClass); // set attributes
  788. setAttributes(inputType, params.inputAttributes); // set class
  789. inputContainer.className = inputClass;
  790. if (rerender) {
  791. hide(inputContainer);
  792. }
  793. });
  794. if (params.input) {
  795. if (rerender) {
  796. showInput(params);
  797. } // set custom class
  798. setCustomClass(params);
  799. }
  800. };
  801. const showInput = params => {
  802. if (!renderInputType[params.input]) {
  803. return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\""));
  804. }
  805. const inputContainer = getInputContainer(params.input);
  806. const input = renderInputType[params.input](inputContainer, params);
  807. show(input); // input autofocus
  808. setTimeout(() => {
  809. focusInput(input);
  810. });
  811. };
  812. const removeAttributes = input => {
  813. for (let i = 0; i < input.attributes.length; i++) {
  814. const attrName = input.attributes[i].name;
  815. if (!['type', 'value', 'style'].includes(attrName)) {
  816. input.removeAttribute(attrName);
  817. }
  818. }
  819. };
  820. const setAttributes = (inputType, inputAttributes) => {
  821. const input = getInput(getPopup(), inputType);
  822. if (!input) {
  823. return;
  824. }
  825. removeAttributes(input);
  826. for (const attr in inputAttributes) {
  827. input.setAttribute(attr, inputAttributes[attr]);
  828. }
  829. };
  830. const setCustomClass = params => {
  831. const inputContainer = getInputContainer(params.input);
  832. if (params.customClass) {
  833. addClass(inputContainer, params.customClass.input);
  834. }
  835. };
  836. const setInputPlaceholder = (input, params) => {
  837. if (!input.placeholder || params.inputPlaceholder) {
  838. input.placeholder = params.inputPlaceholder;
  839. }
  840. };
  841. const setInputLabel = (input, prependTo, params) => {
  842. if (params.inputLabel) {
  843. input.id = swalClasses.input;
  844. const label = document.createElement('label');
  845. const labelClass = swalClasses['input-label'];
  846. label.setAttribute('for', input.id);
  847. label.className = labelClass;
  848. addClass(label, params.customClass.inputLabel);
  849. label.innerText = params.inputLabel;
  850. prependTo.insertAdjacentElement('beforebegin', label);
  851. }
  852. };
  853. const getInputContainer = inputType => {
  854. const inputClass = swalClasses[inputType] ? swalClasses[inputType] : swalClasses.input;
  855. return getDirectChildByClass(getPopup(), inputClass);
  856. };
  857. const renderInputType = {};
  858. renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => {
  859. if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') {
  860. input.value = params.inputValue;
  861. } else if (!isPromise(params.inputValue)) {
  862. warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(typeof params.inputValue, "\""));
  863. }
  864. setInputLabel(input, input, params);
  865. setInputPlaceholder(input, params);
  866. input.type = params.input;
  867. return input;
  868. };
  869. renderInputType.file = (input, params) => {
  870. setInputLabel(input, input, params);
  871. setInputPlaceholder(input, params);
  872. return input;
  873. };
  874. renderInputType.range = (range, params) => {
  875. const rangeInput = range.querySelector('input');
  876. const rangeOutput = range.querySelector('output');
  877. rangeInput.value = params.inputValue;
  878. rangeInput.type = params.input;
  879. rangeOutput.value = params.inputValue;
  880. setInputLabel(rangeInput, range, params);
  881. return range;
  882. };
  883. renderInputType.select = (select, params) => {
  884. select.textContent = '';
  885. if (params.inputPlaceholder) {
  886. const placeholder = document.createElement('option');
  887. setInnerHtml(placeholder, params.inputPlaceholder);
  888. placeholder.value = '';
  889. placeholder.disabled = true;
  890. placeholder.selected = true;
  891. select.appendChild(placeholder);
  892. }
  893. setInputLabel(select, select, params);
  894. return select;
  895. };
  896. renderInputType.radio = radio => {
  897. radio.textContent = '';
  898. return radio;
  899. };
  900. renderInputType.checkbox = (checkboxContainer, params) => {
  901. /** @type {HTMLInputElement} */
  902. const checkbox = getInput(getPopup(), 'checkbox');
  903. checkbox.value = '1';
  904. checkbox.id = swalClasses.checkbox;
  905. checkbox.checked = Boolean(params.inputValue);
  906. const label = checkboxContainer.querySelector('span');
  907. setInnerHtml(label, params.inputPlaceholder);
  908. return checkboxContainer;
  909. };
  910. renderInputType.textarea = (textarea, params) => {
  911. textarea.value = params.inputValue;
  912. setInputPlaceholder(textarea, params);
  913. setInputLabel(textarea, textarea, params);
  914. const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight); // https://github.com/sweetalert2/sweetalert2/issues/2291
  915. setTimeout(() => {
  916. // https://github.com/sweetalert2/sweetalert2/issues/1699
  917. if ('MutationObserver' in window) {
  918. const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
  919. const textareaResizeHandler = () => {
  920. const textareaWidth = textarea.offsetWidth + getMargin(textarea);
  921. if (textareaWidth > initialPopupWidth) {
  922. getPopup().style.width = "".concat(textareaWidth, "px");
  923. } else {
  924. getPopup().style.width = null;
  925. }
  926. };
  927. new MutationObserver(textareaResizeHandler).observe(textarea, {
  928. attributes: true,
  929. attributeFilter: ['style']
  930. });
  931. }
  932. });
  933. return textarea;
  934. };
  935. const renderContent = (instance, params) => {
  936. const htmlContainer = getHtmlContainer();
  937. applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML
  938. if (params.html) {
  939. parseHtmlToContainer(params.html, htmlContainer);
  940. show(htmlContainer, 'block');
  941. } // Content as plain text
  942. else if (params.text) {
  943. htmlContainer.textContent = params.text;
  944. show(htmlContainer, 'block');
  945. } // No content
  946. else {
  947. hide(htmlContainer);
  948. }
  949. renderInput(instance, params);
  950. };
  951. const renderFooter = (instance, params) => {
  952. const footer = getFooter();
  953. toggle(footer, params.footer);
  954. if (params.footer) {
  955. parseHtmlToContainer(params.footer, footer);
  956. } // Custom class
  957. applyCustomClass(footer, params, 'footer');
  958. };
  959. const renderCloseButton = (instance, params) => {
  960. const closeButton = getCloseButton();
  961. setInnerHtml(closeButton, params.closeButtonHtml); // Custom class
  962. applyCustomClass(closeButton, params, 'closeButton');
  963. toggle(closeButton, params.showCloseButton);
  964. closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
  965. };
  966. const renderIcon = (instance, params) => {
  967. const innerParams = privateProps.innerParams.get(instance);
  968. const icon = getIcon(); // if the given icon already rendered, apply the styling without re-rendering the icon
  969. if (innerParams && params.icon === innerParams.icon) {
  970. // Custom or default content
  971. setContent(icon, params);
  972. applyStyles(icon, params);
  973. return;
  974. }
  975. if (!params.icon && !params.iconHtml) {
  976. return hide(icon);
  977. }
  978. if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
  979. error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\""));
  980. return hide(icon);
  981. }
  982. show(icon); // Custom or default content
  983. setContent(icon, params);
  984. applyStyles(icon, params); // Animate icon
  985. addClass(icon, params.showClass.icon);
  986. };
  987. const applyStyles = (icon, params) => {
  988. for (const iconType in iconTypes) {
  989. if (params.icon !== iconType) {
  990. removeClass(icon, iconTypes[iconType]);
  991. }
  992. }
  993. addClass(icon, iconTypes[params.icon]); // Icon color
  994. setColor(icon, params); // Success icon background color
  995. adjustSuccessIconBackgroundColor(); // Custom class
  996. applyCustomClass(icon, params, 'icon');
  997. }; // Adjust success icon background color to match the popup background color
  998. const adjustSuccessIconBackgroundColor = () => {
  999. const popup = getPopup();
  1000. const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
  1001. const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
  1002. for (let i = 0; i < successIconParts.length; i++) {
  1003. successIconParts[i].style.backgroundColor = popupBackgroundColor;
  1004. }
  1005. };
  1006. const successIconHtml = "\n <div class=\"swal2-success-circular-line-left\"></div>\n <span class=\"swal2-success-line-tip\"></span> <span class=\"swal2-success-line-long\"></span>\n <div class=\"swal2-success-ring\"></div> <div class=\"swal2-success-fix\"></div>\n <div class=\"swal2-success-circular-line-right\"></div>\n";
  1007. const errorIconHtml = "\n <span class=\"swal2-x-mark\">\n <span class=\"swal2-x-mark-line-left\"></span>\n <span class=\"swal2-x-mark-line-right\"></span>\n </span>\n";
  1008. const setContent = (icon, params) => {
  1009. icon.textContent = '';
  1010. if (params.iconHtml) {
  1011. setInnerHtml(icon, iconContent(params.iconHtml));
  1012. } else if (params.icon === 'success') {
  1013. setInnerHtml(icon, successIconHtml);
  1014. } else if (params.icon === 'error') {
  1015. setInnerHtml(icon, errorIconHtml);
  1016. } else {
  1017. const defaultIconHtml = {
  1018. question: '?',
  1019. warning: '!',
  1020. info: 'i'
  1021. };
  1022. setInnerHtml(icon, iconContent(defaultIconHtml[params.icon]));
  1023. }
  1024. };
  1025. const setColor = (icon, params) => {
  1026. if (!params.iconColor) {
  1027. return;
  1028. }
  1029. icon.style.color = params.iconColor;
  1030. icon.style.borderColor = params.iconColor;
  1031. for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
  1032. setStyle(icon, sel, 'backgroundColor', params.iconColor);
  1033. }
  1034. setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);
  1035. };
  1036. const iconContent = content => "<div class=\"".concat(swalClasses['icon-content'], "\">").concat(content, "</div>");
  1037. const renderImage = (instance, params) => {
  1038. const image = getImage();
  1039. if (!params.imageUrl) {
  1040. return hide(image);
  1041. }
  1042. show(image, ''); // Src, alt
  1043. image.setAttribute('src', params.imageUrl);
  1044. image.setAttribute('alt', params.imageAlt); // Width, height
  1045. applyNumericalStyle(image, 'width', params.imageWidth);
  1046. applyNumericalStyle(image, 'height', params.imageHeight); // Class
  1047. image.className = swalClasses.image;
  1048. applyCustomClass(image, params, 'image');
  1049. };
  1050. const createStepElement = step => {
  1051. const stepEl = document.createElement('li');
  1052. addClass(stepEl, swalClasses['progress-step']);
  1053. setInnerHtml(stepEl, step);
  1054. return stepEl;
  1055. };
  1056. const createLineElement = params => {
  1057. const lineEl = document.createElement('li');
  1058. addClass(lineEl, swalClasses['progress-step-line']);
  1059. if (params.progressStepsDistance) {
  1060. lineEl.style.width = params.progressStepsDistance;
  1061. }
  1062. return lineEl;
  1063. };
  1064. const renderProgressSteps = (instance, params) => {
  1065. const progressStepsContainer = getProgressSteps();
  1066. if (!params.progressSteps || params.progressSteps.length === 0) {
  1067. return hide(progressStepsContainer);
  1068. }
  1069. show(progressStepsContainer);
  1070. progressStepsContainer.textContent = '';
  1071. if (params.currentProgressStep >= params.progressSteps.length) {
  1072. warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
  1073. }
  1074. params.progressSteps.forEach((step, index) => {
  1075. const stepEl = createStepElement(step);
  1076. progressStepsContainer.appendChild(stepEl);
  1077. if (index === params.currentProgressStep) {
  1078. addClass(stepEl, swalClasses['active-progress-step']);
  1079. }
  1080. if (index !== params.progressSteps.length - 1) {
  1081. const lineEl = createLineElement(params);
  1082. progressStepsContainer.appendChild(lineEl);
  1083. }
  1084. });
  1085. };
  1086. const renderTitle = (instance, params) => {
  1087. const title = getTitle();
  1088. toggle(title, params.title || params.titleText, 'block');
  1089. if (params.title) {
  1090. parseHtmlToContainer(params.title, title);
  1091. }
  1092. if (params.titleText) {
  1093. title.innerText = params.titleText;
  1094. } // Custom class
  1095. applyCustomClass(title, params, 'title');
  1096. };
  1097. const renderPopup = (instance, params) => {
  1098. const container = getContainer();
  1099. const popup = getPopup(); // Width
  1100. // https://github.com/sweetalert2/sweetalert2/issues/2170
  1101. if (params.toast) {
  1102. applyNumericalStyle(container, 'width', params.width);
  1103. popup.style.width = '100%';
  1104. popup.insertBefore(getLoader(), getIcon());
  1105. } else {
  1106. applyNumericalStyle(popup, 'width', params.width);
  1107. } // Padding
  1108. applyNumericalStyle(popup, 'padding', params.padding); // Color
  1109. if (params.color) {
  1110. popup.style.color = params.color;
  1111. } // Background
  1112. if (params.background) {
  1113. popup.style.background = params.background;
  1114. }
  1115. hide(getValidationMessage()); // Classes
  1116. addClasses(popup, params);
  1117. };
  1118. const addClasses = (popup, params) => {
  1119. // Default Class + showClass when updating Swal.update({})
  1120. popup.className = "".concat(swalClasses.popup, " ").concat(isVisible(popup) ? params.showClass.popup : '');
  1121. if (params.toast) {
  1122. addClass([document.documentElement, document.body], swalClasses['toast-shown']);
  1123. addClass(popup, swalClasses.toast);
  1124. } else {
  1125. addClass(popup, swalClasses.modal);
  1126. } // Custom class
  1127. applyCustomClass(popup, params, 'popup');
  1128. if (typeof params.customClass === 'string') {
  1129. addClass(popup, params.customClass);
  1130. } // Icon class (#1842)
  1131. if (params.icon) {
  1132. addClass(popup, swalClasses["icon-".concat(params.icon)]);
  1133. }
  1134. };
  1135. const render = (instance, params) => {
  1136. renderPopup(instance, params);
  1137. renderContainer(instance, params);
  1138. renderProgressSteps(instance, params);
  1139. renderIcon(instance, params);
  1140. renderImage(instance, params);
  1141. renderTitle(instance, params);
  1142. renderCloseButton(instance, params);
  1143. renderContent(instance, params);
  1144. renderActions(instance, params);
  1145. renderFooter(instance, params);
  1146. if (typeof params.didRender === 'function') {
  1147. params.didRender(getPopup());
  1148. }
  1149. };
  1150. const DismissReason = Object.freeze({
  1151. cancel: 'cancel',
  1152. backdrop: 'backdrop',
  1153. close: 'close',
  1154. esc: 'esc',
  1155. timer: 'timer'
  1156. });
  1157. // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
  1158. // elements not within the active modal dialog will not be surfaced if a user opens a screen
  1159. // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
  1160. const setAriaHidden = () => {
  1161. const bodyChildren = toArray(document.body.children);
  1162. bodyChildren.forEach(el => {
  1163. if (el === getContainer() || el.contains(getContainer())) {
  1164. return;
  1165. }
  1166. if (el.hasAttribute('aria-hidden')) {
  1167. el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
  1168. }
  1169. el.setAttribute('aria-hidden', 'true');
  1170. });
  1171. };
  1172. const unsetAriaHidden = () => {
  1173. const bodyChildren = toArray(document.body.children);
  1174. bodyChildren.forEach(el => {
  1175. if (el.hasAttribute('data-previous-aria-hidden')) {
  1176. el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
  1177. el.removeAttribute('data-previous-aria-hidden');
  1178. } else {
  1179. el.removeAttribute('aria-hidden');
  1180. }
  1181. });
  1182. };
  1183. const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
  1184. const getTemplateParams = params => {
  1185. const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;
  1186. if (!template) {
  1187. return {};
  1188. }
  1189. /** @type {DocumentFragment} */
  1190. const templateContent = template.content;
  1191. showWarningsForElements(templateContent);
  1192. const result = Object.assign(getSwalParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
  1193. return result;
  1194. };
  1195. /**
  1196. * @param {DocumentFragment} templateContent
  1197. */
  1198. const getSwalParams = templateContent => {
  1199. const result = {};
  1200. toArray(templateContent.querySelectorAll('swal-param')).forEach(param => {
  1201. showWarningsForAttributes(param, ['name', 'value']);
  1202. const paramName = param.getAttribute('name');
  1203. const value = param.getAttribute('value');
  1204. if (typeof defaultParams[paramName] === 'boolean' && value === 'false') {
  1205. result[paramName] = false;
  1206. }
  1207. if (typeof defaultParams[paramName] === 'object') {
  1208. result[paramName] = JSON.parse(value);
  1209. }
  1210. });
  1211. return result;
  1212. };
  1213. /**
  1214. * @param {DocumentFragment} templateContent
  1215. */
  1216. const getSwalButtons = templateContent => {
  1217. const result = {};
  1218. toArray(templateContent.querySelectorAll('swal-button')).forEach(button => {
  1219. showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
  1220. const type = button.getAttribute('type');
  1221. result["".concat(type, "ButtonText")] = button.innerHTML;
  1222. result["show".concat(capitalizeFirstLetter(type), "Button")] = true;
  1223. if (button.hasAttribute('color')) {
  1224. result["".concat(type, "ButtonColor")] = button.getAttribute('color');
  1225. }
  1226. if (button.hasAttribute('aria-label')) {
  1227. result["".concat(type, "ButtonAriaLabel")] = button.getAttribute('aria-label');
  1228. }
  1229. });
  1230. return result;
  1231. };
  1232. /**
  1233. * @param {DocumentFragment} templateContent
  1234. */
  1235. const getSwalImage = templateContent => {
  1236. const result = {};
  1237. /** @type {HTMLElement} */
  1238. const image = templateContent.querySelector('swal-image');
  1239. if (image) {
  1240. showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
  1241. if (image.hasAttribute('src')) {
  1242. result.imageUrl = image.getAttribute('src');
  1243. }
  1244. if (image.hasAttribute('width')) {
  1245. result.imageWidth = image.getAttribute('width');
  1246. }
  1247. if (image.hasAttribute('height')) {
  1248. result.imageHeight = image.getAttribute('height');
  1249. }
  1250. if (image.hasAttribute('alt')) {
  1251. result.imageAlt = image.getAttribute('alt');
  1252. }
  1253. }
  1254. return result;
  1255. };
  1256. /**
  1257. * @param {DocumentFragment} templateContent
  1258. */
  1259. const getSwalIcon = templateContent => {
  1260. const result = {};
  1261. /** @type {HTMLElement} */
  1262. const icon = templateContent.querySelector('swal-icon');
  1263. if (icon) {
  1264. showWarningsForAttributes(icon, ['type', 'color']);
  1265. if (icon.hasAttribute('type')) {
  1266. result.icon = icon.getAttribute('type');
  1267. }
  1268. if (icon.hasAttribute('color')) {
  1269. result.iconColor = icon.getAttribute('color');
  1270. }
  1271. result.iconHtml = icon.innerHTML;
  1272. }
  1273. return result;
  1274. };
  1275. /**
  1276. * @param {DocumentFragment} templateContent
  1277. */
  1278. const getSwalInput = templateContent => {
  1279. const result = {};
  1280. /** @type {HTMLElement} */
  1281. const input = templateContent.querySelector('swal-input');
  1282. if (input) {
  1283. showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
  1284. result.input = input.getAttribute('type') || 'text';
  1285. if (input.hasAttribute('label')) {
  1286. result.inputLabel = input.getAttribute('label');
  1287. }
  1288. if (input.hasAttribute('placeholder')) {
  1289. result.inputPlaceholder = input.getAttribute('placeholder');
  1290. }
  1291. if (input.hasAttribute('value')) {
  1292. result.inputValue = input.getAttribute('value');
  1293. }
  1294. }
  1295. const inputOptions = templateContent.querySelectorAll('swal-input-option');
  1296. if (inputOptions.length) {
  1297. result.inputOptions = {};
  1298. toArray(inputOptions).forEach(option => {
  1299. showWarningsForAttributes(option, ['value']);
  1300. const optionValue = option.getAttribute('value');
  1301. const optionName = option.innerHTML;
  1302. result.inputOptions[optionValue] = optionName;
  1303. });
  1304. }
  1305. return result;
  1306. };
  1307. /**
  1308. * @param {DocumentFragment} templateContent
  1309. * @param {string[]} paramNames
  1310. */
  1311. const getSwalStringParams = (templateContent, paramNames) => {
  1312. const result = {};
  1313. for (const i in paramNames) {
  1314. const paramName = paramNames[i];
  1315. /** @type {HTMLElement} */
  1316. const tag = templateContent.querySelector(paramName);
  1317. if (tag) {
  1318. showWarningsForAttributes(tag, []);
  1319. result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
  1320. }
  1321. }
  1322. return result;
  1323. };
  1324. /**
  1325. * @param {DocumentFragment} templateContent
  1326. */
  1327. const showWarningsForElements = templateContent => {
  1328. const allowedElements = swalStringParams.concat(['swal-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
  1329. toArray(templateContent.children).forEach(el => {
  1330. const tagName = el.tagName.toLowerCase();
  1331. if (allowedElements.indexOf(tagName) === -1) {
  1332. warn("Unrecognized element <".concat(tagName, ">"));
  1333. }
  1334. });
  1335. };
  1336. /**
  1337. * @param {HTMLElement} el
  1338. * @param {string[]} allowedAttributes
  1339. */
  1340. const showWarningsForAttributes = (el, allowedAttributes) => {
  1341. toArray(el.attributes).forEach(attribute => {
  1342. if (allowedAttributes.indexOf(attribute.name) === -1) {
  1343. warn(["Unrecognized attribute \"".concat(attribute.name, "\" on <").concat(el.tagName.toLowerCase(), ">."), "".concat(allowedAttributes.length ? "Allowed attributes are: ".concat(allowedAttributes.join(', ')) : 'To set the value, use HTML within the element.')]);
  1344. }
  1345. });
  1346. };
  1347. var defaultInputValidators = {
  1348. email: (string, validationMessage) => {
  1349. return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
  1350. },
  1351. url: (string, validationMessage) => {
  1352. // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
  1353. 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');
  1354. }
  1355. };
  1356. function setDefaultInputValidators(params) {
  1357. // Use default `inputValidator` for supported input types if not provided
  1358. if (!params.inputValidator) {
  1359. Object.keys(defaultInputValidators).forEach(key => {
  1360. if (params.input === key) {
  1361. params.inputValidator = defaultInputValidators[key];
  1362. }
  1363. });
  1364. }
  1365. }
  1366. function validateCustomTargetElement(params) {
  1367. // Determine if the custom target element is valid
  1368. if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
  1369. warn('Target parameter is not valid, defaulting to "body"');
  1370. params.target = 'body';
  1371. }
  1372. }
  1373. /**
  1374. * Set type, text and actions on popup
  1375. *
  1376. * @param params
  1377. */
  1378. function setParameters(params) {
  1379. setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm
  1380. if (params.showLoaderOnConfirm && !params.preConfirm) {
  1381. 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');
  1382. }
  1383. validateCustomTargetElement(params); // Replace newlines with <br> in title
  1384. if (typeof params.title === 'string') {
  1385. params.title = params.title.split('\n').join('<br />');
  1386. }
  1387. init(params);
  1388. }
  1389. class Timer {
  1390. constructor(callback, delay) {
  1391. this.callback = callback;
  1392. this.remaining = delay;
  1393. this.running = false;
  1394. this.start();
  1395. }
  1396. start() {
  1397. if (!this.running) {
  1398. this.running = true;
  1399. this.started = new Date();
  1400. this.id = setTimeout(this.callback, this.remaining);
  1401. }
  1402. return this.remaining;
  1403. }
  1404. stop() {
  1405. if (this.running) {
  1406. this.running = false;
  1407. clearTimeout(this.id);
  1408. this.remaining -= new Date().getTime() - this.started.getTime();
  1409. }
  1410. return this.remaining;
  1411. }
  1412. increase(n) {
  1413. const running = this.running;
  1414. if (running) {
  1415. this.stop();
  1416. }
  1417. this.remaining += n;
  1418. if (running) {
  1419. this.start();
  1420. }
  1421. return this.remaining;
  1422. }
  1423. getTimerLeft() {
  1424. if (this.running) {
  1425. this.stop();
  1426. this.start();
  1427. }
  1428. return this.remaining;
  1429. }
  1430. isRunning() {
  1431. return this.running;
  1432. }
  1433. }
  1434. const fixScrollbar = () => {
  1435. // for queues, do not do this more than once
  1436. if (states.previousBodyPadding !== null) {
  1437. return;
  1438. } // if the body has overflow
  1439. if (document.body.scrollHeight > window.innerHeight) {
  1440. // add padding so the content doesn't shift after removal of scrollbar
  1441. states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
  1442. document.body.style.paddingRight = "".concat(states.previousBodyPadding + measureScrollbar(), "px");
  1443. }
  1444. };
  1445. const undoScrollbar = () => {
  1446. if (states.previousBodyPadding !== null) {
  1447. document.body.style.paddingRight = "".concat(states.previousBodyPadding, "px");
  1448. states.previousBodyPadding = null;
  1449. }
  1450. };
  1451. /* istanbul ignore file */
  1452. const iOSfix = () => {
  1453. const iOS = // @ts-ignore
  1454. /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
  1455. if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
  1456. const offset = document.body.scrollTop;
  1457. document.body.style.top = "".concat(offset * -1, "px");
  1458. addClass(document.body, swalClasses.iosfix);
  1459. lockBodyScroll();
  1460. addBottomPaddingForTallPopups();
  1461. }
  1462. };
  1463. /**
  1464. * https://github.com/sweetalert2/sweetalert2/issues/1948
  1465. */
  1466. const addBottomPaddingForTallPopups = () => {
  1467. const ua = navigator.userAgent;
  1468. const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
  1469. const webkit = !!ua.match(/WebKit/i);
  1470. const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  1471. if (iOSSafari) {
  1472. const bottomPanelHeight = 44;
  1473. if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {
  1474. getContainer().style.paddingBottom = "".concat(bottomPanelHeight, "px");
  1475. }
  1476. }
  1477. };
  1478. /**
  1479. * https://github.com/sweetalert2/sweetalert2/issues/1246
  1480. */
  1481. const lockBodyScroll = () => {
  1482. const container = getContainer();
  1483. let preventTouchMove;
  1484. container.ontouchstart = e => {
  1485. preventTouchMove = shouldPreventTouchMove(e);
  1486. };
  1487. container.ontouchmove = e => {
  1488. if (preventTouchMove) {
  1489. e.preventDefault();
  1490. e.stopPropagation();
  1491. }
  1492. };
  1493. };
  1494. const shouldPreventTouchMove = event => {
  1495. const target = event.target;
  1496. const container = getContainer();
  1497. if (isStylus(event) || isZoom(event)) {
  1498. return false;
  1499. }
  1500. if (target === container) {
  1501. return true;
  1502. }
  1503. if (!isScrollable(container) && target.tagName !== 'INPUT' && // #1603
  1504. target.tagName !== 'TEXTAREA' && // #2266
  1505. !(isScrollable(getHtmlContainer()) && // #1944
  1506. getHtmlContainer().contains(target))) {
  1507. return true;
  1508. }
  1509. return false;
  1510. };
  1511. /**
  1512. * https://github.com/sweetalert2/sweetalert2/issues/1786
  1513. *
  1514. * @param {*} event
  1515. * @returns {boolean}
  1516. */
  1517. const isStylus = event => {
  1518. return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
  1519. };
  1520. /**
  1521. * https://github.com/sweetalert2/sweetalert2/issues/1891
  1522. *
  1523. * @param {TouchEvent} event
  1524. * @returns {boolean}
  1525. */
  1526. const isZoom = event => {
  1527. return event.touches && event.touches.length > 1;
  1528. };
  1529. const undoIOSfix = () => {
  1530. if (hasClass(document.body, swalClasses.iosfix)) {
  1531. const offset = parseInt(document.body.style.top, 10);
  1532. removeClass(document.body, swalClasses.iosfix);
  1533. document.body.style.top = '';
  1534. document.body.scrollTop = offset * -1;
  1535. }
  1536. };
  1537. const SHOW_CLASS_TIMEOUT = 10;
  1538. /**
  1539. * Open popup, add necessary classes and styles, fix scrollbar
  1540. *
  1541. * @param params
  1542. */
  1543. const openPopup = params => {
  1544. const container = getContainer();
  1545. const popup = getPopup();
  1546. if (typeof params.willOpen === 'function') {
  1547. params.willOpen(popup);
  1548. }
  1549. const bodyStyles = window.getComputedStyle(document.body);
  1550. const initialBodyOverflow = bodyStyles.overflowY;
  1551. addClasses$1(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'
  1552. setTimeout(() => {
  1553. setScrollingVisibility(container, popup);
  1554. }, SHOW_CLASS_TIMEOUT);
  1555. if (isModal()) {
  1556. fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
  1557. setAriaHidden();
  1558. }
  1559. if (!isToast() && !globalState.previousActiveElement) {
  1560. globalState.previousActiveElement = document.activeElement;
  1561. }
  1562. if (typeof params.didOpen === 'function') {
  1563. setTimeout(() => params.didOpen(popup));
  1564. }
  1565. removeClass(container, swalClasses['no-transition']);
  1566. };
  1567. const swalOpenAnimationFinished = event => {
  1568. const popup = getPopup();
  1569. if (event.target !== popup) {
  1570. return;
  1571. }
  1572. const container = getContainer();
  1573. popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
  1574. container.style.overflowY = 'auto';
  1575. };
  1576. const setScrollingVisibility = (container, popup) => {
  1577. if (animationEndEvent && hasCssAnimation(popup)) {
  1578. container.style.overflowY = 'hidden';
  1579. popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
  1580. } else {
  1581. container.style.overflowY = 'auto';
  1582. }
  1583. };
  1584. const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
  1585. iOSfix();
  1586. if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
  1587. fixScrollbar();
  1588. } // sweetalert2/issues/1247
  1589. setTimeout(() => {
  1590. container.scrollTop = 0;
  1591. });
  1592. };
  1593. const addClasses$1 = (container, popup, params) => {
  1594. addClass(container, params.showClass.backdrop); // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
  1595. popup.style.setProperty('opacity', '0', 'important');
  1596. show(popup, 'grid');
  1597. setTimeout(() => {
  1598. // Animate popup right after showing it
  1599. addClass(popup, params.showClass.popup); // and remove the opacity workaround
  1600. popup.style.removeProperty('opacity');
  1601. }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
  1602. addClass([document.documentElement, document.body], swalClasses.shown);
  1603. if (params.heightAuto && params.backdrop && !params.toast) {
  1604. addClass([document.documentElement, document.body], swalClasses['height-auto']);
  1605. }
  1606. };
  1607. /**
  1608. * Shows loader (spinner), this is useful with AJAX requests.
  1609. * By default the loader be shown instead of the "Confirm" button.
  1610. */
  1611. const showLoading = buttonToReplace => {
  1612. let popup = getPopup();
  1613. if (!popup) {
  1614. new Swal(); // eslint-disable-line no-new
  1615. }
  1616. popup = getPopup();
  1617. const loader = getLoader();
  1618. if (isToast()) {
  1619. hide(getIcon());
  1620. } else {
  1621. replaceButton(popup, buttonToReplace);
  1622. }
  1623. show(loader);
  1624. popup.setAttribute('data-loading', true);
  1625. popup.setAttribute('aria-busy', true);
  1626. popup.focus();
  1627. };
  1628. const replaceButton = (popup, buttonToReplace) => {
  1629. const actions = getActions();
  1630. const loader = getLoader();
  1631. if (!buttonToReplace && isVisible(getConfirmButton())) {
  1632. buttonToReplace = getConfirmButton();
  1633. }
  1634. show(actions);
  1635. if (buttonToReplace) {
  1636. hide(buttonToReplace);
  1637. loader.setAttribute('data-button-to-replace', buttonToReplace.className);
  1638. }
  1639. loader.parentNode.insertBefore(loader, buttonToReplace);
  1640. addClass([popup, actions], swalClasses.loading);
  1641. };
  1642. const handleInputOptionsAndValue = (instance, params) => {
  1643. if (params.input === 'select' || params.input === 'radio') {
  1644. handleInputOptions(instance, params);
  1645. } else if (['text', 'email', 'number', 'tel', 'textarea'].includes(params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
  1646. showLoading(getConfirmButton());
  1647. handleInputValue(instance, params);
  1648. }
  1649. };
  1650. const getInputValue = (instance, innerParams) => {
  1651. const input = instance.getInput();
  1652. if (!input) {
  1653. return null;
  1654. }
  1655. switch (innerParams.input) {
  1656. case 'checkbox':
  1657. return getCheckboxValue(input);
  1658. case 'radio':
  1659. return getRadioValue(input);
  1660. case 'file':
  1661. return getFileValue(input);
  1662. default:
  1663. return innerParams.inputAutoTrim ? input.value.trim() : input.value;
  1664. }
  1665. };
  1666. const getCheckboxValue = input => input.checked ? 1 : 0;
  1667. const getRadioValue = input => input.checked ? input.value : null;
  1668. const getFileValue = input => input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
  1669. const handleInputOptions = (instance, params) => {
  1670. const popup = getPopup();
  1671. const processInputOptions = inputOptions => populateInputOptions[params.input](popup, formatInputOptions(inputOptions), params);
  1672. if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
  1673. showLoading(getConfirmButton());
  1674. asPromise(params.inputOptions).then(inputOptions => {
  1675. instance.hideLoading();
  1676. processInputOptions(inputOptions);
  1677. });
  1678. } else if (typeof params.inputOptions === 'object') {
  1679. processInputOptions(params.inputOptions);
  1680. } else {
  1681. error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(typeof params.inputOptions));
  1682. }
  1683. };
  1684. const handleInputValue = (instance, params) => {
  1685. const input = instance.getInput();
  1686. hide(input);
  1687. asPromise(params.inputValue).then(inputValue => {
  1688. input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : "".concat(inputValue);
  1689. show(input);
  1690. input.focus();
  1691. instance.hideLoading();
  1692. }).catch(err => {
  1693. error("Error in inputValue promise: ".concat(err));
  1694. input.value = '';
  1695. show(input);
  1696. input.focus();
  1697. instance.hideLoading();
  1698. });
  1699. };
  1700. const populateInputOptions = {
  1701. select: (popup, inputOptions, params) => {
  1702. const select = getDirectChildByClass(popup, swalClasses.select);
  1703. const renderOption = (parent, optionLabel, optionValue) => {
  1704. const option = document.createElement('option');
  1705. option.value = optionValue;
  1706. setInnerHtml(option, optionLabel);
  1707. option.selected = isSelected(optionValue, params.inputValue);
  1708. parent.appendChild(option);
  1709. };
  1710. inputOptions.forEach(inputOption => {
  1711. const optionValue = inputOption[0];
  1712. const optionLabel = inputOption[1]; // <optgroup> spec:
  1713. // https://www.w3.org/TR/html401/interact/forms.html#h-17.6
  1714. // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
  1715. // check whether this is a <optgroup>
  1716. if (Array.isArray(optionLabel)) {
  1717. // if it is an array, then it is an <optgroup>
  1718. const optgroup = document.createElement('optgroup');
  1719. optgroup.label = optionValue;
  1720. optgroup.disabled = false; // not configurable for now
  1721. select.appendChild(optgroup);
  1722. optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
  1723. } else {
  1724. // case of <option>
  1725. renderOption(select, optionLabel, optionValue);
  1726. }
  1727. });
  1728. select.focus();
  1729. },
  1730. radio: (popup, inputOptions, params) => {
  1731. const radio = getDirectChildByClass(popup, swalClasses.radio);
  1732. inputOptions.forEach(inputOption => {
  1733. const radioValue = inputOption[0];
  1734. const radioLabel = inputOption[1];
  1735. const radioInput = document.createElement('input');
  1736. const radioLabelElement = document.createElement('label');
  1737. radioInput.type = 'radio';
  1738. radioInput.name = swalClasses.radio;
  1739. radioInput.value = radioValue;
  1740. if (isSelected(radioValue, params.inputValue)) {
  1741. radioInput.checked = true;
  1742. }
  1743. const label = document.createElement('span');
  1744. setInnerHtml(label, radioLabel);
  1745. label.className = swalClasses.label;
  1746. radioLabelElement.appendChild(radioInput);
  1747. radioLabelElement.appendChild(label);
  1748. radio.appendChild(radioLabelElement);
  1749. });
  1750. const radios = radio.querySelectorAll('input');
  1751. if (radios.length) {
  1752. radios[0].focus();
  1753. }
  1754. }
  1755. };
  1756. /**
  1757. * Converts `inputOptions` into an array of `[value, label]`s
  1758. * @param inputOptions
  1759. */
  1760. const formatInputOptions = inputOptions => {
  1761. const result = [];
  1762. if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
  1763. inputOptions.forEach((value, key) => {
  1764. let valueFormatted = value;
  1765. if (typeof valueFormatted === 'object') {
  1766. // case of <optgroup>
  1767. valueFormatted = formatInputOptions(valueFormatted);
  1768. }
  1769. result.push([key, valueFormatted]);
  1770. });
  1771. } else {
  1772. Object.keys(inputOptions).forEach(key => {
  1773. let valueFormatted = inputOptions[key];
  1774. if (typeof valueFormatted === 'object') {
  1775. // case of <optgroup>
  1776. valueFormatted = formatInputOptions(valueFormatted);
  1777. }
  1778. result.push([key, valueFormatted]);
  1779. });
  1780. }
  1781. return result;
  1782. };
  1783. const isSelected = (optionValue, inputValue) => {
  1784. return inputValue && inputValue.toString() === optionValue.toString();
  1785. };
  1786. const handleConfirmButtonClick = instance => {
  1787. const innerParams = privateProps.innerParams.get(instance);
  1788. instance.disableButtons();
  1789. if (innerParams.input) {
  1790. handleConfirmOrDenyWithInput(instance, 'confirm');
  1791. } else {
  1792. confirm(instance, true);
  1793. }
  1794. };
  1795. const handleDenyButtonClick = instance => {
  1796. const innerParams = privateProps.innerParams.get(instance);
  1797. instance.disableButtons();
  1798. if (innerParams.returnInputValueOnDeny) {
  1799. handleConfirmOrDenyWithInput(instance, 'deny');
  1800. } else {
  1801. deny(instance, false);
  1802. }
  1803. };
  1804. const handleCancelButtonClick = (instance, dismissWith) => {
  1805. instance.disableButtons();
  1806. dismissWith(DismissReason.cancel);
  1807. };
  1808. const handleConfirmOrDenyWithInput = (instance, type
  1809. /* 'confirm' | 'deny' */
  1810. ) => {
  1811. const innerParams = privateProps.innerParams.get(instance);
  1812. if (!innerParams.input) {
  1813. return error("The \"input\" parameter is needed to be set when using returnInputValueOn".concat(capitalizeFirstLetter(type)));
  1814. }
  1815. const inputValue = getInputValue(instance, innerParams);
  1816. if (innerParams.inputValidator) {
  1817. handleInputValidator(instance, inputValue, type);
  1818. } else if (!instance.getInput().checkValidity()) {
  1819. instance.enableButtons();
  1820. instance.showValidationMessage(innerParams.validationMessage);
  1821. } else if (type === 'deny') {
  1822. deny(instance, inputValue);
  1823. } else {
  1824. confirm(instance, inputValue);
  1825. }
  1826. };
  1827. const handleInputValidator = (instance, inputValue, type
  1828. /* 'confirm' | 'deny' */
  1829. ) => {
  1830. const innerParams = privateProps.innerParams.get(instance);
  1831. instance.disableInput();
  1832. const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
  1833. validationPromise.then(validationMessage => {
  1834. instance.enableButtons();
  1835. instance.enableInput();
  1836. if (validationMessage) {
  1837. instance.showValidationMessage(validationMessage);
  1838. } else if (type === 'deny') {
  1839. deny(instance, inputValue);
  1840. } else {
  1841. confirm(instance, inputValue);
  1842. }
  1843. });
  1844. };
  1845. const deny = (instance, value) => {
  1846. const innerParams = privateProps.innerParams.get(instance || undefined);
  1847. if (innerParams.showLoaderOnDeny) {
  1848. showLoading(getDenyButton());
  1849. }
  1850. if (innerParams.preDeny) {
  1851. privateProps.awaitingPromise.set(instance || undefined, 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
  1852. const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
  1853. preDenyPromise.then(preDenyValue => {
  1854. if (preDenyValue === false) {
  1855. instance.hideLoading();
  1856. } else {
  1857. instance.closePopup({
  1858. isDenied: true,
  1859. value: typeof preDenyValue === 'undefined' ? value : preDenyValue
  1860. });
  1861. }
  1862. }).catch(error$$1 => rejectWith(instance || undefined, error$$1));
  1863. } else {
  1864. instance.closePopup({
  1865. isDenied: true,
  1866. value
  1867. });
  1868. }
  1869. };
  1870. const succeedWith = (instance, value) => {
  1871. instance.closePopup({
  1872. isConfirmed: true,
  1873. value
  1874. });
  1875. };
  1876. const rejectWith = (instance, error$$1) => {
  1877. instance.rejectPromise(error$$1);
  1878. };
  1879. const confirm = (instance, value) => {
  1880. const innerParams = privateProps.innerParams.get(instance || undefined);
  1881. if (innerParams.showLoaderOnConfirm) {
  1882. showLoading();
  1883. }
  1884. if (innerParams.preConfirm) {
  1885. instance.resetValidationMessage();
  1886. privateProps.awaitingPromise.set(instance || undefined, 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
  1887. const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
  1888. preConfirmPromise.then(preConfirmValue => {
  1889. if (isVisible(getValidationMessage()) || preConfirmValue === false) {
  1890. instance.hideLoading();
  1891. } else {
  1892. succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
  1893. }
  1894. }).catch(error$$1 => rejectWith(instance || undefined, error$$1));
  1895. } else {
  1896. succeedWith(instance, value);
  1897. }
  1898. };
  1899. const handlePopupClick = (instance, domCache, dismissWith) => {
  1900. const innerParams = privateProps.innerParams.get(instance);
  1901. if (innerParams.toast) {
  1902. handleToastClick(instance, domCache, dismissWith);
  1903. } else {
  1904. // Ignore click events that had mousedown on the popup but mouseup on the container
  1905. // This can happen when the user drags a slider
  1906. handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup
  1907. handleContainerMousedown(domCache);
  1908. handleModalClick(instance, domCache, dismissWith);
  1909. }
  1910. };
  1911. const handleToastClick = (instance, domCache, dismissWith) => {
  1912. // Closing toast by internal click
  1913. domCache.popup.onclick = () => {
  1914. const innerParams = privateProps.innerParams.get(instance);
  1915. if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
  1916. return;
  1917. }
  1918. dismissWith(DismissReason.close);
  1919. };
  1920. };
  1921. /**
  1922. * @param {*} innerParams
  1923. * @returns {boolean}
  1924. */
  1925. const isAnyButtonShown = innerParams => {
  1926. return innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton;
  1927. };
  1928. let ignoreOutsideClick = false;
  1929. const handleModalMousedown = domCache => {
  1930. domCache.popup.onmousedown = () => {
  1931. domCache.container.onmouseup = function (e) {
  1932. domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't
  1933. // have any other direct children aside of the popup
  1934. if (e.target === domCache.container) {
  1935. ignoreOutsideClick = true;
  1936. }
  1937. };
  1938. };
  1939. };
  1940. const handleContainerMousedown = domCache => {
  1941. domCache.container.onmousedown = () => {
  1942. domCache.popup.onmouseup = function (e) {
  1943. domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup
  1944. if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
  1945. ignoreOutsideClick = true;
  1946. }
  1947. };
  1948. };
  1949. };
  1950. const handleModalClick = (instance, domCache, dismissWith) => {
  1951. domCache.container.onclick = e => {
  1952. const innerParams = privateProps.innerParams.get(instance);
  1953. if (ignoreOutsideClick) {
  1954. ignoreOutsideClick = false;
  1955. return;
  1956. }
  1957. if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
  1958. dismissWith(DismissReason.backdrop);
  1959. }
  1960. };
  1961. };
  1962. /*
  1963. * Global function to determine if SweetAlert2 popup is shown
  1964. */
  1965. const isVisible$1 = () => {
  1966. return isVisible(getPopup());
  1967. };
  1968. /*
  1969. * Global function to click 'Confirm' button
  1970. */
  1971. const clickConfirm = () => getConfirmButton() && getConfirmButton().click();
  1972. /*
  1973. * Global function to click 'Deny' button
  1974. */
  1975. const clickDeny = () => getDenyButton() && getDenyButton().click();
  1976. /*
  1977. * Global function to click 'Cancel' button
  1978. */
  1979. const clickCancel = () => getCancelButton() && getCancelButton().click();
  1980. const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => {
  1981. if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
  1982. globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
  1983. capture: globalState.keydownListenerCapture
  1984. });
  1985. globalState.keydownHandlerAdded = false;
  1986. }
  1987. if (!innerParams.toast) {
  1988. globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith);
  1989. globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
  1990. globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
  1991. globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
  1992. capture: globalState.keydownListenerCapture
  1993. });
  1994. globalState.keydownHandlerAdded = true;
  1995. }
  1996. }; // Focus handling
  1997. const setFocus = (innerParams, index, increment) => {
  1998. const focusableElements = getFocusableElements(); // search for visible elements and select the next possible match
  1999. if (focusableElements.length) {
  2000. index = index + increment; // rollover to first item
  2001. if (index === focusableElements.length) {
  2002. index = 0; // go to last item
  2003. } else if (index === -1) {
  2004. index = focusableElements.length - 1;
  2005. }
  2006. return focusableElements[index].focus();
  2007. } // no visible focusable elements, focus the popup
  2008. getPopup().focus();
  2009. };
  2010. const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
  2011. const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
  2012. const keydownHandler = (instance, e, dismissWith) => {
  2013. const innerParams = privateProps.innerParams.get(instance);
  2014. if (!innerParams) {
  2015. return; // This instance has already been destroyed
  2016. }
  2017. if (innerParams.stopKeydownPropagation) {
  2018. e.stopPropagation();
  2019. } // ENTER
  2020. if (e.key === 'Enter') {
  2021. handleEnter(instance, e, innerParams);
  2022. } // TAB
  2023. else if (e.key === 'Tab') {
  2024. handleTab(e, innerParams);
  2025. } // ARROWS - switch focus between buttons
  2026. else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(e.key)) {
  2027. handleArrows(e.key);
  2028. } // ESC
  2029. else if (e.key === 'Escape') {
  2030. handleEsc(e, innerParams, dismissWith);
  2031. }
  2032. };
  2033. const handleEnter = (instance, e, innerParams) => {
  2034. // #2386 #720 #721
  2035. if (!callIfFunction(innerParams.allowEnterKey) || e.isComposing) {
  2036. return;
  2037. }
  2038. if (e.target && instance.getInput() && e.target.outerHTML === instance.getInput().outerHTML) {
  2039. if (['textarea', 'file'].includes(innerParams.input)) {
  2040. return; // do not submit
  2041. }
  2042. clickConfirm();
  2043. e.preventDefault();
  2044. }
  2045. };
  2046. const handleTab = (e, innerParams) => {
  2047. const targetElement = e.target;
  2048. const focusableElements = getFocusableElements();
  2049. let btnIndex = -1;
  2050. for (let i = 0; i < focusableElements.length; i++) {
  2051. if (targetElement === focusableElements[i]) {
  2052. btnIndex = i;
  2053. break;
  2054. }
  2055. } // Cycle to the next button
  2056. if (!e.shiftKey) {
  2057. setFocus(innerParams, btnIndex, 1);
  2058. } // Cycle to the prev button
  2059. else {
  2060. setFocus(innerParams, btnIndex, -1);
  2061. }
  2062. e.stopPropagation();
  2063. e.preventDefault();
  2064. };
  2065. const handleArrows = key => {
  2066. const confirmButton = getConfirmButton();
  2067. const denyButton = getDenyButton();
  2068. const cancelButton = getCancelButton();
  2069. if (![confirmButton, denyButton, cancelButton].includes(document.activeElement)) {
  2070. return;
  2071. }
  2072. const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
  2073. const buttonToFocus = document.activeElement[sibling];
  2074. if (buttonToFocus instanceof HTMLElement) {
  2075. buttonToFocus.focus();
  2076. }
  2077. };
  2078. const handleEsc = (e, innerParams, dismissWith) => {
  2079. if (callIfFunction(innerParams.allowEscapeKey)) {
  2080. e.preventDefault();
  2081. dismissWith(DismissReason.esc);
  2082. }
  2083. };
  2084. const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
  2085. const isElement = elem => elem instanceof Element || isJqueryElement(elem);
  2086. const argsToParams = args => {
  2087. const params = {};
  2088. if (typeof args[0] === 'object' && !isElement(args[0])) {
  2089. Object.assign(params, args[0]);
  2090. } else {
  2091. ['title', 'html', 'icon'].forEach((name, index) => {
  2092. const arg = args[index];
  2093. if (typeof arg === 'string' || isElement(arg)) {
  2094. params[name] = arg;
  2095. } else if (arg !== undefined) {
  2096. error("Unexpected type of ".concat(name, "! Expected \"string\" or \"Element\", got ").concat(typeof arg));
  2097. }
  2098. });
  2099. }
  2100. return params;
  2101. };
  2102. function fire() {
  2103. const Swal = this; // eslint-disable-line @typescript-eslint/no-this-alias
  2104. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2105. args[_key] = arguments[_key];
  2106. }
  2107. return new Swal(...args);
  2108. }
  2109. /**
  2110. * Returns an extended version of `Swal` containing `params` as defaults.
  2111. * Useful for reusing Swal configuration.
  2112. *
  2113. * For example:
  2114. *
  2115. * Before:
  2116. * const textPromptOptions = { input: 'text', showCancelButton: true }
  2117. * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
  2118. * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
  2119. *
  2120. * After:
  2121. * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
  2122. * const {value: firstName} = await TextPrompt('What is your first name?')
  2123. * const {value: lastName} = await TextPrompt('What is your last name?')
  2124. *
  2125. * @param mixinParams
  2126. */
  2127. function mixin(mixinParams) {
  2128. class MixinSwal extends this {
  2129. _main(params, priorityMixinParams) {
  2130. return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
  2131. }
  2132. }
  2133. return MixinSwal;
  2134. }
  2135. /**
  2136. * If `timer` parameter is set, returns number of milliseconds of timer remained.
  2137. * Otherwise, returns undefined.
  2138. */
  2139. const getTimerLeft = () => {
  2140. return globalState.timeout && globalState.timeout.getTimerLeft();
  2141. };
  2142. /**
  2143. * Stop timer. Returns number of milliseconds of timer remained.
  2144. * If `timer` parameter isn't set, returns undefined.
  2145. */
  2146. const stopTimer = () => {
  2147. if (globalState.timeout) {
  2148. stopTimerProgressBar();
  2149. return globalState.timeout.stop();
  2150. }
  2151. };
  2152. /**
  2153. * Resume timer. Returns number of milliseconds of timer remained.
  2154. * If `timer` parameter isn't set, returns undefined.
  2155. */
  2156. const resumeTimer = () => {
  2157. if (globalState.timeout) {
  2158. const remaining = globalState.timeout.start();
  2159. animateTimerProgressBar(remaining);
  2160. return remaining;
  2161. }
  2162. };
  2163. /**
  2164. * Resume timer. Returns number of milliseconds of timer remained.
  2165. * If `timer` parameter isn't set, returns undefined.
  2166. */
  2167. const toggleTimer = () => {
  2168. const timer = globalState.timeout;
  2169. return timer && (timer.running ? stopTimer() : resumeTimer());
  2170. };
  2171. /**
  2172. * Increase timer. Returns number of milliseconds of an updated timer.
  2173. * If `timer` parameter isn't set, returns undefined.
  2174. */
  2175. const increaseTimer = n => {
  2176. if (globalState.timeout) {
  2177. const remaining = globalState.timeout.increase(n);
  2178. animateTimerProgressBar(remaining, true);
  2179. return remaining;
  2180. }
  2181. };
  2182. /**
  2183. * Check if timer is running. Returns true if timer is running
  2184. * or false if timer is paused or stopped.
  2185. * If `timer` parameter isn't set, returns undefined
  2186. */
  2187. const isTimerRunning = () => {
  2188. return globalState.timeout && globalState.timeout.isRunning();
  2189. };
  2190. let bodyClickListenerAdded = false;
  2191. const clickHandlers = {};
  2192. function bindClickHandler() {
  2193. let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
  2194. clickHandlers[attr] = this;
  2195. if (!bodyClickListenerAdded) {
  2196. document.body.addEventListener('click', bodyClickListener);
  2197. bodyClickListenerAdded = true;
  2198. }
  2199. }
  2200. const bodyClickListener = event => {
  2201. for (let el = event.target; el && el !== document; el = el.parentNode) {
  2202. for (const attr in clickHandlers) {
  2203. const template = el.getAttribute(attr);
  2204. if (template) {
  2205. clickHandlers[attr].fire({
  2206. template
  2207. });
  2208. return;
  2209. }
  2210. }
  2211. }
  2212. };
  2213. var staticMethods = /*#__PURE__*/Object.freeze({
  2214. isValidParameter: isValidParameter,
  2215. isUpdatableParameter: isUpdatableParameter,
  2216. isDeprecatedParameter: isDeprecatedParameter,
  2217. argsToParams: argsToParams,
  2218. isVisible: isVisible$1,
  2219. clickConfirm: clickConfirm,
  2220. clickDeny: clickDeny,
  2221. clickCancel: clickCancel,
  2222. getContainer: getContainer,
  2223. getPopup: getPopup,
  2224. getTitle: getTitle,
  2225. getHtmlContainer: getHtmlContainer,
  2226. getImage: getImage,
  2227. getIcon: getIcon,
  2228. getInputLabel: getInputLabel,
  2229. getCloseButton: getCloseButton,
  2230. getActions: getActions,
  2231. getConfirmButton: getConfirmButton,
  2232. getDenyButton: getDenyButton,
  2233. getCancelButton: getCancelButton,
  2234. getLoader: getLoader,
  2235. getFooter: getFooter,
  2236. getTimerProgressBar: getTimerProgressBar,
  2237. getFocusableElements: getFocusableElements,
  2238. getValidationMessage: getValidationMessage,
  2239. isLoading: isLoading,
  2240. fire: fire,
  2241. mixin: mixin,
  2242. showLoading: showLoading,
  2243. enableLoading: showLoading,
  2244. getTimerLeft: getTimerLeft,
  2245. stopTimer: stopTimer,
  2246. resumeTimer: resumeTimer,
  2247. toggleTimer: toggleTimer,
  2248. increaseTimer: increaseTimer,
  2249. isTimerRunning: isTimerRunning,
  2250. bindClickHandler: bindClickHandler
  2251. });
  2252. /**
  2253. * Hides loader and shows back the button which was hidden by .showLoading()
  2254. */
  2255. function hideLoading() {
  2256. // do nothing if popup is closed
  2257. const innerParams = privateProps.innerParams.get(this);
  2258. if (!innerParams) {
  2259. return;
  2260. }
  2261. const domCache = privateProps.domCache.get(this);
  2262. hide(domCache.loader);
  2263. if (isToast()) {
  2264. if (innerParams.icon) {
  2265. show(getIcon());
  2266. }
  2267. } else {
  2268. showRelatedButton(domCache);
  2269. }
  2270. removeClass([domCache.popup, domCache.actions], swalClasses.loading);
  2271. domCache.popup.removeAttribute('aria-busy');
  2272. domCache.popup.removeAttribute('data-loading');
  2273. domCache.confirmButton.disabled = false;
  2274. domCache.denyButton.disabled = false;
  2275. domCache.cancelButton.disabled = false;
  2276. }
  2277. const showRelatedButton = domCache => {
  2278. const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
  2279. if (buttonToReplace.length) {
  2280. show(buttonToReplace[0], 'inline-block');
  2281. } else if (allButtonsAreHidden()) {
  2282. hide(domCache.actions);
  2283. }
  2284. };
  2285. /**
  2286. * Gets the input DOM node, this method works with input parameter.
  2287. * @returns {HTMLElement | null}
  2288. */
  2289. function getInput$1(instance) {
  2290. const innerParams = privateProps.innerParams.get(instance || this);
  2291. const domCache = privateProps.domCache.get(instance || this);
  2292. if (!domCache) {
  2293. return null;
  2294. }
  2295. return getInput(domCache.popup, innerParams.input);
  2296. }
  2297. /**
  2298. * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
  2299. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  2300. * This is the approach that Babel will probably take to implement private methods/fields
  2301. * https://github.com/tc39/proposal-private-methods
  2302. * https://github.com/babel/babel/pull/7555
  2303. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  2304. * then we can use that language feature.
  2305. */
  2306. var privateMethods = {
  2307. swalPromiseResolve: new WeakMap(),
  2308. swalPromiseReject: new WeakMap()
  2309. };
  2310. /*
  2311. * Instance method to close sweetAlert
  2312. */
  2313. function removePopupAndResetState(instance, container, returnFocus, didClose) {
  2314. if (isToast()) {
  2315. triggerDidCloseAndDispose(instance, didClose);
  2316. } else {
  2317. restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
  2318. globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
  2319. capture: globalState.keydownListenerCapture
  2320. });
  2321. globalState.keydownHandlerAdded = false;
  2322. }
  2323. const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); // workaround for #2088
  2324. // for some reason removing the container in Safari will scroll the document to bottom
  2325. if (isSafari) {
  2326. container.setAttribute('style', 'display:none !important');
  2327. container.removeAttribute('class');
  2328. container.innerHTML = '';
  2329. } else {
  2330. container.remove();
  2331. }
  2332. if (isModal()) {
  2333. undoScrollbar();
  2334. undoIOSfix();
  2335. unsetAriaHidden();
  2336. }
  2337. removeBodyClasses();
  2338. }
  2339. function removeBodyClasses() {
  2340. removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
  2341. }
  2342. function close(resolveValue) {
  2343. resolveValue = prepareResolveValue(resolveValue);
  2344. const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
  2345. const didClose = triggerClosePopup(this);
  2346. if (this.isAwaitingPromise()) {
  2347. // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
  2348. if (!resolveValue.isDismissed) {
  2349. handleAwaitingPromise(this);
  2350. swalPromiseResolve(resolveValue);
  2351. }
  2352. } else if (didClose) {
  2353. // Resolve Swal promise
  2354. swalPromiseResolve(resolveValue);
  2355. }
  2356. }
  2357. function isAwaitingPromise() {
  2358. return !!privateProps.awaitingPromise.get(this);
  2359. }
  2360. const triggerClosePopup = instance => {
  2361. const popup = getPopup();
  2362. if (!popup) {
  2363. return false;
  2364. }
  2365. const innerParams = privateProps.innerParams.get(instance);
  2366. if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
  2367. return false;
  2368. }
  2369. removeClass(popup, innerParams.showClass.popup);
  2370. addClass(popup, innerParams.hideClass.popup);
  2371. const backdrop = getContainer();
  2372. removeClass(backdrop, innerParams.showClass.backdrop);
  2373. addClass(backdrop, innerParams.hideClass.backdrop);
  2374. handlePopupAnimation(instance, popup, innerParams);
  2375. return true;
  2376. };
  2377. function rejectPromise(error) {
  2378. const rejectPromise = privateMethods.swalPromiseReject.get(this);
  2379. handleAwaitingPromise(this);
  2380. if (rejectPromise) {
  2381. // Reject Swal promise
  2382. rejectPromise(error);
  2383. }
  2384. }
  2385. const handleAwaitingPromise = instance => {
  2386. if (instance.isAwaitingPromise()) {
  2387. privateProps.awaitingPromise.delete(instance); // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
  2388. if (!privateProps.innerParams.get(instance)) {
  2389. instance._destroy();
  2390. }
  2391. }
  2392. };
  2393. const prepareResolveValue = resolveValue => {
  2394. // When user calls Swal.close()
  2395. if (typeof resolveValue === 'undefined') {
  2396. return {
  2397. isConfirmed: false,
  2398. isDenied: false,
  2399. isDismissed: true
  2400. };
  2401. }
  2402. return Object.assign({
  2403. isConfirmed: false,
  2404. isDenied: false,
  2405. isDismissed: false
  2406. }, resolveValue);
  2407. };
  2408. const handlePopupAnimation = (instance, popup, innerParams) => {
  2409. const container = getContainer(); // If animation is supported, animate
  2410. const animationIsSupported = animationEndEvent && hasCssAnimation(popup);
  2411. if (typeof innerParams.willClose === 'function') {
  2412. innerParams.willClose(popup);
  2413. }
  2414. if (animationIsSupported) {
  2415. animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
  2416. } else {
  2417. // Otherwise, remove immediately
  2418. removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
  2419. }
  2420. };
  2421. const animatePopup = (instance, popup, container, returnFocus, didClose) => {
  2422. globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
  2423. popup.addEventListener(animationEndEvent, function (e) {
  2424. if (e.target === popup) {
  2425. globalState.swalCloseEventFinishedCallback();
  2426. delete globalState.swalCloseEventFinishedCallback;
  2427. }
  2428. });
  2429. };
  2430. const triggerDidCloseAndDispose = (instance, didClose) => {
  2431. setTimeout(() => {
  2432. if (typeof didClose === 'function') {
  2433. didClose.bind(instance.params)();
  2434. }
  2435. instance._destroy();
  2436. });
  2437. };
  2438. function setButtonsDisabled(instance, buttons, disabled) {
  2439. const domCache = privateProps.domCache.get(instance);
  2440. buttons.forEach(button => {
  2441. domCache[button].disabled = disabled;
  2442. });
  2443. }
  2444. function setInputDisabled(input, disabled) {
  2445. if (!input) {
  2446. return false;
  2447. }
  2448. if (input.type === 'radio') {
  2449. const radiosContainer = input.parentNode.parentNode;
  2450. const radios = radiosContainer.querySelectorAll('input');
  2451. for (let i = 0; i < radios.length; i++) {
  2452. radios[i].disabled = disabled;
  2453. }
  2454. } else {
  2455. input.disabled = disabled;
  2456. }
  2457. }
  2458. function enableButtons() {
  2459. setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
  2460. }
  2461. function disableButtons() {
  2462. setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
  2463. }
  2464. function enableInput() {
  2465. return setInputDisabled(this.getInput(), false);
  2466. }
  2467. function disableInput() {
  2468. return setInputDisabled(this.getInput(), true);
  2469. }
  2470. function showValidationMessage(error) {
  2471. const domCache = privateProps.domCache.get(this);
  2472. const params = privateProps.innerParams.get(this);
  2473. setInnerHtml(domCache.validationMessage, error);
  2474. domCache.validationMessage.className = swalClasses['validation-message'];
  2475. if (params.customClass && params.customClass.validationMessage) {
  2476. addClass(domCache.validationMessage, params.customClass.validationMessage);
  2477. }
  2478. show(domCache.validationMessage);
  2479. const input = this.getInput();
  2480. if (input) {
  2481. input.setAttribute('aria-invalid', true);
  2482. input.setAttribute('aria-describedby', swalClasses['validation-message']);
  2483. focusInput(input);
  2484. addClass(input, swalClasses.inputerror);
  2485. }
  2486. } // Hide block with validation message
  2487. function resetValidationMessage$1() {
  2488. const domCache = privateProps.domCache.get(this);
  2489. if (domCache.validationMessage) {
  2490. hide(domCache.validationMessage);
  2491. }
  2492. const input = this.getInput();
  2493. if (input) {
  2494. input.removeAttribute('aria-invalid');
  2495. input.removeAttribute('aria-describedby');
  2496. removeClass(input, swalClasses.inputerror);
  2497. }
  2498. }
  2499. function getProgressSteps$1() {
  2500. const domCache = privateProps.domCache.get(this);
  2501. return domCache.progressSteps;
  2502. }
  2503. /**
  2504. * Updates popup parameters.
  2505. */
  2506. function update(params) {
  2507. const popup = getPopup();
  2508. const innerParams = privateProps.innerParams.get(this);
  2509. if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
  2510. return 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.");
  2511. }
  2512. const validUpdatableParams = filterValidParams(params);
  2513. const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
  2514. render(this, updatedParams);
  2515. privateProps.innerParams.set(this, updatedParams);
  2516. Object.defineProperties(this, {
  2517. params: {
  2518. value: Object.assign({}, this.params, params),
  2519. writable: false,
  2520. enumerable: true
  2521. }
  2522. });
  2523. }
  2524. const filterValidParams = params => {
  2525. const validUpdatableParams = {};
  2526. Object.keys(params).forEach(param => {
  2527. if (isUpdatableParameter(param)) {
  2528. validUpdatableParams[param] = params[param];
  2529. } else {
  2530. warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md"));
  2531. }
  2532. });
  2533. return validUpdatableParams;
  2534. };
  2535. function _destroy() {
  2536. const domCache = privateProps.domCache.get(this);
  2537. const innerParams = privateProps.innerParams.get(this);
  2538. if (!innerParams) {
  2539. disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
  2540. return; // This instance has already been destroyed
  2541. } // Check if there is another Swal closing
  2542. if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
  2543. globalState.swalCloseEventFinishedCallback();
  2544. delete globalState.swalCloseEventFinishedCallback;
  2545. } // Check if there is a swal disposal defer timer
  2546. if (globalState.deferDisposalTimer) {
  2547. clearTimeout(globalState.deferDisposalTimer);
  2548. delete globalState.deferDisposalTimer;
  2549. }
  2550. if (typeof innerParams.didDestroy === 'function') {
  2551. innerParams.didDestroy();
  2552. }
  2553. disposeSwal(this);
  2554. }
  2555. const disposeSwal = instance => {
  2556. disposeWeakMaps(instance); // Unset this.params so GC will dispose it (#1569)
  2557. delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)
  2558. delete globalState.keydownHandler;
  2559. delete globalState.keydownTarget; // Unset currentInstance
  2560. delete globalState.currentInstance;
  2561. };
  2562. const disposeWeakMaps = instance => {
  2563. // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
  2564. if (instance.isAwaitingPromise()) {
  2565. unsetWeakMaps(privateProps, instance);
  2566. privateProps.awaitingPromise.set(instance, true);
  2567. } else {
  2568. unsetWeakMaps(privateMethods, instance);
  2569. unsetWeakMaps(privateProps, instance);
  2570. }
  2571. };
  2572. const unsetWeakMaps = (obj, instance) => {
  2573. for (const i in obj) {
  2574. obj[i].delete(instance);
  2575. }
  2576. };
  2577. var instanceMethods = /*#__PURE__*/Object.freeze({
  2578. hideLoading: hideLoading,
  2579. disableLoading: hideLoading,
  2580. getInput: getInput$1,
  2581. close: close,
  2582. isAwaitingPromise: isAwaitingPromise,
  2583. rejectPromise: rejectPromise,
  2584. closePopup: close,
  2585. closeModal: close,
  2586. closeToast: close,
  2587. enableButtons: enableButtons,
  2588. disableButtons: disableButtons,
  2589. enableInput: enableInput,
  2590. disableInput: disableInput,
  2591. showValidationMessage: showValidationMessage,
  2592. resetValidationMessage: resetValidationMessage$1,
  2593. getProgressSteps: getProgressSteps$1,
  2594. update: update,
  2595. _destroy: _destroy
  2596. });
  2597. let currentInstance;
  2598. class SweetAlert {
  2599. constructor() {
  2600. // Prevent run in Node env
  2601. if (typeof window === 'undefined') {
  2602. return;
  2603. }
  2604. currentInstance = this; // @ts-ignore
  2605. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2606. args[_key] = arguments[_key];
  2607. }
  2608. const outerParams = Object.freeze(this.constructor.argsToParams(args));
  2609. Object.defineProperties(this, {
  2610. params: {
  2611. value: outerParams,
  2612. writable: false,
  2613. enumerable: true,
  2614. configurable: true
  2615. }
  2616. }); // @ts-ignore
  2617. const promise = this._main(this.params);
  2618. privateProps.promise.set(this, promise);
  2619. }
  2620. _main(userParams) {
  2621. let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2622. showWarningsForParams(Object.assign({}, mixinParams, userParams));
  2623. if (globalState.currentInstance) {
  2624. globalState.currentInstance._destroy();
  2625. if (isModal()) {
  2626. unsetAriaHidden();
  2627. }
  2628. }
  2629. globalState.currentInstance = this;
  2630. const innerParams = prepareParams(userParams, mixinParams);
  2631. setParameters(innerParams);
  2632. Object.freeze(innerParams); // clear the previous timer
  2633. if (globalState.timeout) {
  2634. globalState.timeout.stop();
  2635. delete globalState.timeout;
  2636. } // clear the restore focus timeout
  2637. clearTimeout(globalState.restoreFocusTimeout);
  2638. const domCache = populateDomCache(this);
  2639. render(this, innerParams);
  2640. privateProps.innerParams.set(this, innerParams);
  2641. return swalPromise(this, domCache, innerParams);
  2642. } // `catch` cannot be the name of a module export, so we define our thenable methods here instead
  2643. then(onFulfilled) {
  2644. const promise = privateProps.promise.get(this);
  2645. return promise.then(onFulfilled);
  2646. }
  2647. finally(onFinally) {
  2648. const promise = privateProps.promise.get(this);
  2649. return promise.finally(onFinally);
  2650. }
  2651. }
  2652. const swalPromise = (instance, domCache, innerParams) => {
  2653. return new Promise((resolve, reject) => {
  2654. // functions to handle all closings/dismissals
  2655. const dismissWith = dismiss => {
  2656. instance.closePopup({
  2657. isDismissed: true,
  2658. dismiss
  2659. });
  2660. };
  2661. privateMethods.swalPromiseResolve.set(instance, resolve);
  2662. privateMethods.swalPromiseReject.set(instance, reject);
  2663. domCache.confirmButton.onclick = () => handleConfirmButtonClick(instance);
  2664. domCache.denyButton.onclick = () => handleDenyButtonClick(instance);
  2665. domCache.cancelButton.onclick = () => handleCancelButtonClick(instance, dismissWith);
  2666. domCache.closeButton.onclick = () => dismissWith(DismissReason.close);
  2667. handlePopupClick(instance, domCache, dismissWith);
  2668. addKeydownHandler(instance, globalState, innerParams, dismissWith);
  2669. handleInputOptionsAndValue(instance, innerParams);
  2670. openPopup(innerParams);
  2671. setupTimer(globalState, innerParams, dismissWith);
  2672. initFocus(domCache, innerParams); // Scroll container to top on open (#1247, #1946)
  2673. setTimeout(() => {
  2674. domCache.container.scrollTop = 0;
  2675. });
  2676. });
  2677. };
  2678. const prepareParams = (userParams, mixinParams) => {
  2679. const templateParams = getTemplateParams(userParams);
  2680. const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
  2681. params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
  2682. params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
  2683. return params;
  2684. };
  2685. const populateDomCache = instance => {
  2686. const domCache = {
  2687. popup: getPopup(),
  2688. container: getContainer(),
  2689. actions: getActions(),
  2690. confirmButton: getConfirmButton(),
  2691. denyButton: getDenyButton(),
  2692. cancelButton: getCancelButton(),
  2693. loader: getLoader(),
  2694. closeButton: getCloseButton(),
  2695. validationMessage: getValidationMessage(),
  2696. progressSteps: getProgressSteps()
  2697. };
  2698. privateProps.domCache.set(instance, domCache);
  2699. return domCache;
  2700. };
  2701. const setupTimer = (globalState$$1, innerParams, dismissWith) => {
  2702. const timerProgressBar = getTimerProgressBar();
  2703. hide(timerProgressBar);
  2704. if (innerParams.timer) {
  2705. globalState$$1.timeout = new Timer(() => {
  2706. dismissWith('timer');
  2707. delete globalState$$1.timeout;
  2708. }, innerParams.timer);
  2709. if (innerParams.timerProgressBar) {
  2710. show(timerProgressBar);
  2711. applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
  2712. setTimeout(() => {
  2713. if (globalState$$1.timeout && globalState$$1.timeout.running) {
  2714. // timer can be already stopped or unset at this point
  2715. animateTimerProgressBar(innerParams.timer);
  2716. }
  2717. });
  2718. }
  2719. }
  2720. };
  2721. const initFocus = (domCache, innerParams) => {
  2722. if (innerParams.toast) {
  2723. return;
  2724. }
  2725. if (!callIfFunction(innerParams.allowEnterKey)) {
  2726. return blurActiveElement();
  2727. }
  2728. if (!focusButton(domCache, innerParams)) {
  2729. setFocus(innerParams, -1, 1);
  2730. }
  2731. };
  2732. const focusButton = (domCache, innerParams) => {
  2733. if (innerParams.focusDeny && isVisible(domCache.denyButton)) {
  2734. domCache.denyButton.focus();
  2735. return true;
  2736. }
  2737. if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {
  2738. domCache.cancelButton.focus();
  2739. return true;
  2740. }
  2741. if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {
  2742. domCache.confirmButton.focus();
  2743. return true;
  2744. }
  2745. return false;
  2746. };
  2747. const blurActiveElement = () => {
  2748. if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
  2749. document.activeElement.blur();
  2750. }
  2751. }; // Assign instance methods from src/instanceMethods/*.js to prototype
  2752. Object.assign(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor
  2753. Object.assign(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility
  2754. Object.keys(instanceMethods).forEach(key => {
  2755. SweetAlert[key] = function () {
  2756. if (currentInstance) {
  2757. return currentInstance[key](...arguments);
  2758. }
  2759. };
  2760. });
  2761. SweetAlert.DismissReason = DismissReason;
  2762. SweetAlert.version = '11.4.0';
  2763. const Swal = SweetAlert; // @ts-ignore
  2764. Swal.default = Swal;
  2765. return Swal;
  2766. }));
  2767. if (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}