Debian Codegraph @

templates/lib/620_sweetalert2_11.26.21.js

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