AdminLTE/plugins/sweetalert2/sweetalert2.js

3640 lines
115 KiB
JavaScript
Raw Normal View History

/*!
2021-02-23 11:22:20 +00:00
* sweetalert2 v10.15.5
* Released under the MIT License.
*/
(function (global, factory) {
2020-04-01 22:52:43 +00:00
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Sweetalert2 = factory());
}(this, function () { 'use strict';
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
2020-04-01 22:52:43 +00:00
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
2020-04-01 22:52:43 +00:00
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
2020-04-01 22:52:43 +00:00
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
2020-04-01 22:52:43 +00:00
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
2020-04-01 22:52:43 +00:00
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
2020-04-01 22:52:43 +00:00
return _construct.apply(null, arguments);
}
2020-04-01 22:52:43 +00:00
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
2020-04-01 22:52:43 +00:00
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
2020-04-01 22:52:43 +00:00
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
2020-04-01 22:52:43 +00:00
return desc.value;
};
}
return _get(target, property, receiver || target);
}
var consolePrefix = 'SweetAlert2:';
/**
* Filter the unique values into a new array
* @param arr
*/
var uniqueArray = function uniqueArray(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
2020-04-01 22:52:43 +00:00
return result;
};
2020-04-01 22:52:43 +00:00
/**
* Capitalize the first letter of a string
* @param str
*/
2020-04-01 22:52:43 +00:00
var capitalizeFirstLetter = function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
/**
* Returns the array of object values (Object.values isn't supported in IE11)
2020-04-01 22:52:43 +00:00
* @param obj
*/
var objectValues = function objectValues(obj) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
};
/**
* Convert NodeList to Array
* @param nodeList
*/
2020-04-01 22:52:43 +00:00
var toArray = function toArray(nodeList) {
return Array.prototype.slice.call(nodeList);
};
/**
* Standardise console warnings
* @param message
*/
var warn = function warn(message) {
2020-12-23 07:17:49 +00:00
console.warn("".concat(consolePrefix, " ").concat(_typeof(message) === 'object' ? message.join(' ') : message));
2020-04-01 22:52:43 +00:00
};
/**
* Standardise console errors
* @param message
*/
2020-04-01 22:52:43 +00:00
var error = function error(message) {
console.error("".concat(consolePrefix, " ").concat(message));
};
/**
* Private global state for `warnOnce`
* @type {Array}
* @private
*/
var previousWarnOnceMessages = [];
/**
* Show a console warning, but only if it hasn't already been shown
* @param message
*/
var warnOnce = function warnOnce(message) {
if (!(previousWarnOnceMessages.indexOf(message) !== -1)) {
previousWarnOnceMessages.push(message);
warn(message);
}
2020-04-01 22:52:43 +00:00
};
/**
* Show a one-time console warning about deprecated params/methods
*/
2020-11-24 07:16:03 +00:00
var warnAboutDeprecation = function warnAboutDeprecation(deprecatedParam, useInstead) {
2020-04-01 22:52:43 +00:00
warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead."));
};
/**
* If `arg` is a function, call it (with no arguments or context) and return the result.
* Otherwise, just pass the value through
* @param arg
*/
var callIfFunction = function callIfFunction(arg) {
return typeof arg === 'function' ? arg() : arg;
};
var hasToPromiseFn = function hasToPromiseFn(arg) {
return arg && typeof arg.toPromise === 'function';
};
var asPromise = function asPromise(arg) {
return hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
};
2020-04-01 22:52:43 +00:00
var isPromise = function isPromise(arg) {
return arg && Promise.resolve(arg) === arg;
};
var DismissReason = Object.freeze({
cancel: 'cancel',
backdrop: 'backdrop',
close: 'close',
esc: 'esc',
timer: 'timer'
});
2020-04-01 22:52:43 +00:00
var isJqueryElement = function isJqueryElement(elem) {
return _typeof(elem) === 'object' && elem.jquery;
};
2020-04-01 22:52:43 +00:00
var isElement = function isElement(elem) {
return elem instanceof Element || isJqueryElement(elem);
};
2020-04-01 22:52:43 +00:00
var argsToParams = function argsToParams(args) {
var params = {};
2020-04-01 22:52:43 +00:00
if (_typeof(args[0]) === 'object' && !isElement(args[0])) {
_extends(params, args[0]);
} else {
['title', 'html', 'icon'].forEach(function (name, index) {
var arg = args[index];
if (typeof arg === 'string' || isElement(arg)) {
params[name] = arg;
} else if (arg !== undefined) {
error("Unexpected type of ".concat(name, "! Expected \"string\" or \"Element\", got ").concat(_typeof(arg)));
}
});
}
return params;
};
var swalPrefix = 'swal2-';
var prefix = function prefix(items) {
var result = {};
for (var i in items) {
result[items[i]] = swalPrefix + items[i];
}
return result;
};
2020-11-25 09:31:52 +00:00
var swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'toast-column', 'show', 'hide', 'close', 'title', 'header', 'content', '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']);
2020-04-01 22:52:43 +00:00
var iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
var getContainer = function getContainer() {
return document.body.querySelector(".".concat(swalClasses.container));
};
var elementBySelector = function elementBySelector(selectorString) {
var container = getContainer();
return container ? container.querySelector(selectorString) : null;
};
var elementByClass = function elementByClass(className) {
return elementBySelector(".".concat(className));
};
var getPopup = function getPopup() {
return elementByClass(swalClasses.popup);
};
var getIcon = function getIcon() {
2021-02-23 11:22:20 +00:00
return elementByClass(swalClasses.icon);
2020-04-01 22:52:43 +00:00
};
var getTitle = function getTitle() {
return elementByClass(swalClasses.title);
};
var getContent = function getContent() {
return elementByClass(swalClasses.content);
};
var getHtmlContainer = function getHtmlContainer() {
return elementByClass(swalClasses['html-container']);
};
var getImage = function getImage() {
return elementByClass(swalClasses.image);
};
var getProgressSteps = function getProgressSteps() {
return elementByClass(swalClasses['progress-steps']);
};
var getValidationMessage = function getValidationMessage() {
return elementByClass(swalClasses['validation-message']);
};
var getConfirmButton = function getConfirmButton() {
return elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm));
};
2020-11-24 07:16:03 +00:00
var getDenyButton = function getDenyButton() {
return elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny));
};
2020-11-25 09:31:52 +00:00
var getInputLabel = function getInputLabel() {
return elementByClass(swalClasses['input-label']);
};
2020-11-24 07:16:03 +00:00
var getLoader = function getLoader() {
return elementBySelector(".".concat(swalClasses.loader));
};
2020-04-01 22:52:43 +00:00
var getCancelButton = function getCancelButton() {
return elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel));
};
var getActions = function getActions() {
return elementByClass(swalClasses.actions);
};
var getHeader = function getHeader() {
return elementByClass(swalClasses.header);
};
var getFooter = function getFooter() {
return elementByClass(swalClasses.footer);
};
var getTimerProgressBar = function getTimerProgressBar() {
return elementByClass(swalClasses['timer-progress-bar']);
};
var getCloseButton = function getCloseButton() {
return elementByClass(swalClasses.close);
}; // https://github.com/jkup/focusable/blob/master/index.js
var focusable = "\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex=\"0\"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n";
var getFocusableElements = function getFocusableElements() {
var focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex
.sort(function (a, b) {
a = parseInt(a.getAttribute('tabindex'));
b = parseInt(b.getAttribute('tabindex'));
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
});
var otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(function (el) {
return el.getAttribute('tabindex') !== '-1';
});
return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(function (el) {
return isVisible(el);
});
};
var isModal = function isModal() {
return !isToast() && !document.body.classList.contains(swalClasses['no-backdrop']);
};
var isToast = function isToast() {
return document.body.classList.contains(swalClasses['toast-shown']);
};
var isLoading = function isLoading() {
return getPopup().hasAttribute('data-loading');
};
var states = {
previousBodyPadding: null
};
var setInnerHtml = function setInnerHtml(elem, html) {
// #1926
elem.textContent = '';
if (html) {
var parser = new DOMParser();
var parsed = parser.parseFromString(html, "text/html");
toArray(parsed.querySelector('head').childNodes).forEach(function (child) {
elem.appendChild(child);
});
toArray(parsed.querySelector('body').childNodes).forEach(function (child) {
elem.appendChild(child);
});
}
};
var hasClass = function hasClass(elem, className) {
if (!className) {
return false;
}
var classList = className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (!elem.classList.contains(classList[i])) {
return false;
}
}
return true;
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
var removeCustomClasses = function removeCustomClasses(elem, params) {
toArray(elem.classList).forEach(function (className) {
if (!(objectValues(swalClasses).indexOf(className) !== -1) && !(objectValues(iconTypes).indexOf(className) !== -1) && !(objectValues(params.showClass).indexOf(className) !== -1)) {
elem.classList.remove(className);
}
});
};
2020-04-01 22:52:43 +00:00
var applyCustomClass = function applyCustomClass(elem, params, className) {
removeCustomClasses(elem, params);
2020-04-01 22:52:43 +00:00
if (params.customClass && params.customClass[className]) {
if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
return warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(_typeof(params.customClass[className]), "\""));
}
2020-04-01 22:52:43 +00:00
addClass(elem, params.customClass[className]);
}
};
function getInput(content, inputType) {
if (!inputType) {
return null;
}
switch (inputType) {
case 'select':
case 'textarea':
case 'file':
return getChildByClass(content, swalClasses[inputType]);
case 'checkbox':
return content.querySelector(".".concat(swalClasses.checkbox, " input"));
2020-04-01 22:52:43 +00:00
case 'radio':
return content.querySelector(".".concat(swalClasses.radio, " input:checked")) || content.querySelector(".".concat(swalClasses.radio, " input:first-child"));
2020-04-01 22:52:43 +00:00
case 'range':
return content.querySelector(".".concat(swalClasses.range, " input"));
default:
return getChildByClass(content, swalClasses.input);
}
}
2020-04-01 22:52:43 +00:00
var focusInput = function focusInput(input) {
input.focus(); // place cursor at end of text in text input
2020-04-01 22:52:43 +00:00
if (input.type !== 'file') {
// http://stackoverflow.com/a/2345915
var val = input.value;
input.value = '';
input.value = val;
}
};
var toggleClass = function toggleClass(target, classList, condition) {
if (!target || !classList) {
return;
}
2020-04-01 22:52:43 +00:00
if (typeof classList === 'string') {
classList = classList.split(/\s+/).filter(Boolean);
}
2020-04-01 22:52:43 +00:00
classList.forEach(function (className) {
if (target.forEach) {
target.forEach(function (elem) {
condition ? elem.classList.add(className) : elem.classList.remove(className);
});
} else {
condition ? target.classList.add(className) : target.classList.remove(className);
}
});
};
var addClass = function addClass(target, classList) {
toggleClass(target, classList, true);
};
var removeClass = function removeClass(target, classList) {
toggleClass(target, classList, false);
};
var getChildByClass = function getChildByClass(elem, className) {
for (var i = 0; i < elem.childNodes.length; i++) {
if (hasClass(elem.childNodes[i], className)) {
return elem.childNodes[i];
}
}
};
var applyNumericalStyle = function applyNumericalStyle(elem, property, value) {
2020-11-25 09:31:52 +00:00
if (value === "".concat(parseInt(value))) {
value = parseInt(value);
}
2020-04-01 22:52:43 +00:00
if (value || parseInt(value) === 0) {
elem.style[property] = typeof value === 'number' ? "".concat(value, "px") : value;
} else {
elem.style.removeProperty(property);
}
};
var show = function show(elem) {
var display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
elem.style.display = display;
};
var hide = function hide(elem) {
elem.style.display = 'none';
};
2020-11-24 07:16:03 +00:00
var setStyle = function setStyle(parent, selector, property, value) {
var el = parent.querySelector(selector);
if (el) {
el.style[property] = value;
}
};
2020-04-01 22:52:43 +00:00
var toggle = function toggle(elem, condition, display) {
condition ? show(elem, display) : hide(elem);
}; // borrowed from jquery $(elem).is(':visible') implementation
var isVisible = function isVisible(elem) {
return !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
};
2020-11-25 09:31:52 +00:00
var allButtonsAreHidden = function allButtonsAreHidden() {
return !isVisible(getConfirmButton()) && !isVisible(getDenyButton()) && !isVisible(getCancelButton());
};
2020-04-01 22:52:43 +00:00
var isScrollable = function isScrollable(elem) {
return !!(elem.scrollHeight > elem.clientHeight);
}; // borrowed from https://stackoverflow.com/a/46352119
var hasCssAnimation = function hasCssAnimation(elem) {
var style = window.getComputedStyle(elem);
var animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
var transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
return animDuration > 0 || transDuration > 0;
};
var contains = function contains(haystack, needle) {
if (typeof haystack.contains === 'function') {
return haystack.contains(needle);
}
};
var animateTimerProgressBar = function animateTimerProgressBar(timer) {
var reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var timerProgressBar = getTimerProgressBar();
if (isVisible(timerProgressBar)) {
if (reset) {
timerProgressBar.style.transition = 'none';
timerProgressBar.style.width = '100%';
}
2020-04-01 22:52:43 +00:00
setTimeout(function () {
timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear");
timerProgressBar.style.width = '0%';
}, 10);
}
};
var stopTimerProgressBar = function stopTimerProgressBar() {
var timerProgressBar = getTimerProgressBar();
var timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
timerProgressBar.style.removeProperty('transition');
timerProgressBar.style.width = '100%';
var timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
var timerProgressBarPercent = parseInt(timerProgressBarWidth / timerProgressBarFullWidth * 100);
timerProgressBar.style.removeProperty('transition');
timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%");
};
// Detect Node env
var isNodeEnv = function isNodeEnv() {
return typeof window === 'undefined' || typeof document === 'undefined';
};
2021-02-23 11:22:20 +00:00
var sweetHTML = "\n <div aria-labelledby=\"".concat(swalClasses.title, "\" aria-describedby=\"").concat(swalClasses.content, "\" class=\"").concat(swalClasses.popup, "\" tabindex=\"-1\">\n <div class=\"").concat(swalClasses.header, "\">\n <ul class=\"").concat(swalClasses['progress-steps'], "\"></ul>\n <div class=\"").concat(swalClasses.icon, "\"></div>\n <img class=\"").concat(swalClasses.image, "\" />\n <h2 class=\"").concat(swalClasses.title, "\" id=\"").concat(swalClasses.title, "\"></h2>\n <button type=\"button\" class=\"").concat(swalClasses.close, "\"></button>\n </div>\n <div class=\"").concat(swalClasses.content, "\">\n <div id=\"").concat(swalClasses.content, "\" class=\"").concat(swalClasses['html-container'], "\"></div>\n <input class=\"").concat(swalClasses.input, "\" />\n <input type=\"file\" class=\"").concat(swalClasses.file, "\" />\n <div class=\"").concat(swalClasses.range, "\">\n <input type=\"range\" />\n <output></output>\n </div>\n <select class=\"").concat(swalClasses.select, "\"></select>\n <div class=\"").concat(swalClasses.radio, "\"></div>\n <label for=\"").concat(swalClasses.checkbox, "\" class=\"").concat(swalClasses.checkbox, "\">\n <input type=\"checkbox\" />\n <span class=\"").concat(swalClasses.label, "\"></span>\n </label>\n <textarea class=\"").concat(swalClasses.textarea, "\"></textarea>\n <div class=\"").concat(swalClasses['validation-message'], "\" id=\"").concat(swalClasses['validation-message'], "\"></div>\n </div>\n <div class=\"").concat(swalClasses.actions, "\">\n <div class=\"").concat(swalClasses.loader, "\"></div>\n <button type=\"button\" class=\"").concat(swalClasses.confirm, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.deny, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.cancel, "\"></button>\n </div>\n <div class=\"").concat(swalClasses.footer, "\"></div>\n <div class=\"").concat(swalClasses['timer-progress-bar-container'], "\">\n <div class=\"").concat(swalClasses['timer-progress-bar'], "\"></div>\n </div>\n </div>\n").replace(/(^|\n)\s*/g, '');
2020-04-01 22:52:43 +00:00
var resetOldContainer = function resetOldContainer() {
var oldContainer = getContainer();
if (!oldContainer) {
return false;
}
oldContainer.parentNode.removeChild(oldContainer);
removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
return true;
};
var oldInputVal; // IE11 workaround, see #1109 for details
var resetValidationMessage = function resetValidationMessage(e) {
if (Swal.isVisible() && oldInputVal !== e.target.value) {
Swal.resetValidationMessage();
}
oldInputVal = e.target.value;
};
var addInputChangeListeners = function addInputChangeListeners() {
var content = getContent();
var input = getChildByClass(content, swalClasses.input);
var file = getChildByClass(content, swalClasses.file);
var range = content.querySelector(".".concat(swalClasses.range, " input"));
var rangeOutput = content.querySelector(".".concat(swalClasses.range, " output"));
var select = getChildByClass(content, swalClasses.select);
var checkbox = content.querySelector(".".concat(swalClasses.checkbox, " input"));
var textarea = getChildByClass(content, swalClasses.textarea);
input.oninput = resetValidationMessage;
file.onchange = resetValidationMessage;
select.onchange = resetValidationMessage;
checkbox.onchange = resetValidationMessage;
textarea.oninput = resetValidationMessage;
range.oninput = function (e) {
resetValidationMessage(e);
rangeOutput.value = range.value;
};
2020-04-01 22:52:43 +00:00
range.onchange = function (e) {
resetValidationMessage(e);
range.nextSibling.value = range.value;
};
};
2020-04-01 22:52:43 +00:00
var getTarget = function getTarget(target) {
return typeof target === 'string' ? document.querySelector(target) : target;
};
2020-04-01 22:52:43 +00:00
var setupAccessibility = function setupAccessibility(params) {
var popup = getPopup();
popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
2020-04-01 22:52:43 +00:00
if (!params.toast) {
popup.setAttribute('aria-modal', 'true');
}
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
var setupRTL = function setupRTL(targetElement) {
if (window.getComputedStyle(targetElement).direction === 'rtl') {
addClass(getContainer(), swalClasses.rtl);
}
};
/*
* Add modal + backdrop to DOM
*/
2020-04-01 22:52:43 +00:00
var init = function init(params) {
// Clean up the old popup container if it exists
var oldContainerExisted = resetOldContainer();
/* istanbul ignore if */
2020-04-01 22:52:43 +00:00
if (isNodeEnv()) {
error('SweetAlert2 requires document to initialize');
return;
}
2020-04-01 22:52:43 +00:00
var container = document.createElement('div');
container.className = swalClasses.container;
2020-04-01 22:52:43 +00:00
if (oldContainerExisted) {
addClass(container, swalClasses['no-transition']);
}
2020-04-01 22:52:43 +00:00
setInnerHtml(container, sweetHTML);
var targetElement = getTarget(params.target);
targetElement.appendChild(container);
setupAccessibility(params);
setupRTL(targetElement);
addInputChangeListeners();
};
2020-04-01 22:52:43 +00:00
var parseHtmlToContainer = function parseHtmlToContainer(param, target) {
// DOM element
if (param instanceof HTMLElement) {
target.appendChild(param); // Object
} else if (_typeof(param) === 'object') {
handleObject(param, target); // Plain string
} else if (param) {
setInnerHtml(target, param);
}
};
2020-04-01 22:52:43 +00:00
var handleObject = function handleObject(param, target) {
// JQuery element(s)
if (param.jquery) {
handleJqueryElem(target, param); // For other objects use their string representation
} else {
setInnerHtml(target, param.toString());
}
};
2020-04-01 22:52:43 +00:00
var handleJqueryElem = function handleJqueryElem(target, elem) {
target.textContent = '';
2020-04-01 22:52:43 +00:00
if (0 in elem) {
for (var i = 0; (i in elem); i++) {
2020-04-01 22:52:43 +00:00
target.appendChild(elem[i].cloneNode(true));
}
} else {
target.appendChild(elem.cloneNode(true));
}
};
var animationEndEvent = function () {
// Prevent run in Node env
2020-04-01 22:52:43 +00:00
/* istanbul ignore if */
if (isNodeEnv()) {
return false;
}
2020-04-01 22:52:43 +00:00
var testEl = document.createElement('div');
var transEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
OAnimation: 'oAnimationEnd oanimationend',
animation: 'animationend'
};
2020-04-01 22:52:43 +00:00
for (var i in transEndEventNames) {
if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
return transEndEventNames[i];
}
}
2020-04-01 22:52:43 +00:00
return false;
}();
2020-04-01 22:52:43 +00:00
// https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
2020-04-01 22:52:43 +00:00
var measureScrollbar = function measureScrollbar() {
var scrollDiv = document.createElement('div');
scrollDiv.className = swalClasses['scrollbar-measure'];
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
};
2020-04-01 22:52:43 +00:00
var renderActions = function renderActions(instance, params) {
var actions = getActions();
2020-11-24 07:16:03 +00:00
var loader = getLoader();
2020-04-01 22:52:43 +00:00
var confirmButton = getConfirmButton();
2020-11-24 07:16:03 +00:00
var denyButton = getDenyButton();
2020-04-01 22:52:43 +00:00
var cancelButton = getCancelButton(); // Actions (buttons) wrapper
2020-11-24 07:16:03 +00:00
if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
2020-04-01 22:52:43 +00:00
hide(actions);
} // Custom class
2020-11-24 07:16:03 +00:00
applyCustomClass(actions, params, 'actions'); // Render buttons
2020-11-24 07:16:03 +00:00
renderButton(confirmButton, 'confirm', params);
renderButton(denyButton, 'deny', params);
2020-11-25 09:31:52 +00:00
renderButton(cancelButton, 'cancel', params);
handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
2020-04-01 22:52:43 +00:00
if (params.reverseButtons) {
2020-11-24 07:16:03 +00:00
actions.insertBefore(cancelButton, loader);
actions.insertBefore(denyButton, loader);
actions.insertBefore(confirmButton, loader);
2020-11-25 09:31:52 +00:00
} // Loader
2020-12-23 07:17:49 +00:00
setInnerHtml(loader, params.loaderHtml);
2020-11-25 09:31:52 +00:00
applyCustomClass(loader, params, 'loader');
2020-04-01 22:52:43 +00:00
};
2020-11-24 07:16:03 +00:00
function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
2020-11-25 09:31:52 +00:00
if (!params.buttonsStyling) {
return removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
}
2020-11-24 07:16:03 +00:00
addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors
2020-04-01 22:52:43 +00:00
if (params.confirmButtonColor) {
confirmButton.style.backgroundColor = params.confirmButtonColor;
}
2020-11-24 07:16:03 +00:00
if (params.denyButtonColor) {
denyButton.style.backgroundColor = params.denyButtonColor;
}
2020-04-01 22:52:43 +00:00
if (params.cancelButtonColor) {
cancelButton.style.backgroundColor = params.cancelButtonColor;
}
}
2020-04-01 22:52:43 +00:00
function renderButton(button, buttonType, params) {
toggle(button, params["show".concat(capitalizeFirstLetter(buttonType), "Button")], 'inline-block');
setInnerHtml(button, params["".concat(buttonType, "ButtonText")]); // Set caption text
button.setAttribute('aria-label', params["".concat(buttonType, "ButtonAriaLabel")]); // ARIA label
// Add buttons custom classes
button.className = swalClasses[buttonType];
applyCustomClass(button, params, "".concat(buttonType, "Button"));
addClass(button, params["".concat(buttonType, "ButtonClass")]);
}
2020-04-01 22:52:43 +00:00
function handleBackdropParam(container, backdrop) {
if (typeof backdrop === 'string') {
container.style.background = backdrop;
} else if (!backdrop) {
addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
}
}
2020-04-01 22:52:43 +00:00
function handlePositionParam(container, position) {
if (position in swalClasses) {
addClass(container, swalClasses[position]);
} else {
warn('The "position" parameter is not valid, defaulting to "center"');
addClass(container, swalClasses.center);
}
}
2020-04-01 22:52:43 +00:00
function handleGrowParam(container, grow) {
if (grow && typeof grow === 'string') {
var growClass = "grow-".concat(grow);
2020-04-01 22:52:43 +00:00
if (growClass in swalClasses) {
addClass(container, swalClasses[growClass]);
}
}
}
2020-04-01 22:52:43 +00:00
var renderContainer = function renderContainer(instance, params) {
var container = getContainer();
if (!container) {
return;
}
handleBackdropParam(container, params.backdrop);
if (!params.backdrop && params.allowOutsideClick) {
warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
}
handlePositionParam(container, params.position);
handleGrowParam(container, params.grow); // Custom class
applyCustomClass(container, params, 'container'); // Set queue step attribute for getQueueStep() method
var queueStep = document.body.getAttribute('data-swal2-queue-step');
if (queueStep) {
container.setAttribute('data-queue-step', queueStep);
document.body.removeAttribute('data-swal2-queue-step');
}
};
/**
* This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* https://github.com/tc39/proposal-private-methods
* https://github.com/babel/babel/pull/7555
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateProps = {
promise: new WeakMap(),
innerParams: new WeakMap(),
domCache: new WeakMap()
};
var inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
var renderInput = function renderInput(instance, params) {
var content = getContent();
var innerParams = privateProps.innerParams.get(instance);
var rerender = !innerParams || params.input !== innerParams.input;
inputTypes.forEach(function (inputType) {
var inputClass = swalClasses[inputType];
var inputContainer = getChildByClass(content, inputClass); // set attributes
setAttributes(inputType, params.inputAttributes); // set class
inputContainer.className = inputClass;
if (rerender) {
hide(inputContainer);
}
});
if (params.input) {
if (rerender) {
showInput(params);
} // set custom class
setCustomClass(params);
}
};
var showInput = function showInput(params) {
if (!renderInputType[params.input]) {
return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\""));
}
var inputContainer = getInputContainer(params.input);
var input = renderInputType[params.input](inputContainer, params);
show(input); // input autofocus
setTimeout(function () {
focusInput(input);
});
};
var removeAttributes = function removeAttributes(input) {
for (var i = 0; i < input.attributes.length; i++) {
var attrName = input.attributes[i].name;
if (!(['type', 'value', 'style'].indexOf(attrName) !== -1)) {
input.removeAttribute(attrName);
}
}
};
var setAttributes = function setAttributes(inputType, inputAttributes) {
var input = getInput(getContent(), inputType);
if (!input) {
return;
}
removeAttributes(input);
for (var attr in inputAttributes) {
// Do not set a placeholder for <input type="range">
// it'll crash Edge, #1298
if (inputType === 'range' && attr === 'placeholder') {
continue;
}
input.setAttribute(attr, inputAttributes[attr]);
}
};
var setCustomClass = function setCustomClass(params) {
var inputContainer = getInputContainer(params.input);
if (params.customClass) {
addClass(inputContainer, params.customClass.input);
}
};
var setInputPlaceholder = function setInputPlaceholder(input, params) {
if (!input.placeholder || params.inputPlaceholder) {
input.placeholder = params.inputPlaceholder;
}
};
2020-11-25 09:31:52 +00:00
var setInputLabel = function setInputLabel(input, prependTo, params) {
if (params.inputLabel) {
input.id = swalClasses.input;
var label = document.createElement('label');
var labelClass = swalClasses['input-label'];
label.setAttribute('for', input.id);
label.className = labelClass;
2021-01-11 13:35:52 +00:00
addClass(label, params.customClass.inputLabel);
2020-11-25 09:31:52 +00:00
label.innerText = params.inputLabel;
prependTo.insertAdjacentElement('beforebegin', label);
}
};
2020-04-01 22:52:43 +00:00
var getInputContainer = function getInputContainer(inputType) {
var inputClass = swalClasses[inputType] ? swalClasses[inputType] : swalClasses.input;
return getChildByClass(getContent(), inputClass);
};
var renderInputType = {};
renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = function (input, params) {
if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') {
input.value = params.inputValue;
} else if (!isPromise(params.inputValue)) {
warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(_typeof(params.inputValue), "\""));
}
2020-11-25 09:31:52 +00:00
setInputLabel(input, input, params);
2020-04-01 22:52:43 +00:00
setInputPlaceholder(input, params);
input.type = params.input;
return input;
};
renderInputType.file = function (input, params) {
2020-11-25 09:31:52 +00:00
setInputLabel(input, input, params);
2020-04-01 22:52:43 +00:00
setInputPlaceholder(input, params);
return input;
};
renderInputType.range = function (range, params) {
var rangeInput = range.querySelector('input');
var rangeOutput = range.querySelector('output');
rangeInput.value = params.inputValue;
rangeInput.type = params.input;
rangeOutput.value = params.inputValue;
2020-11-25 09:31:52 +00:00
setInputLabel(rangeInput, range, params);
2020-04-01 22:52:43 +00:00
return range;
};
renderInputType.select = function (select, params) {
select.textContent = '';
if (params.inputPlaceholder) {
var placeholder = document.createElement('option');
setInnerHtml(placeholder, params.inputPlaceholder);
placeholder.value = '';
placeholder.disabled = true;
placeholder.selected = true;
select.appendChild(placeholder);
}
2020-11-25 09:31:52 +00:00
setInputLabel(select, select, params);
2020-04-01 22:52:43 +00:00
return select;
};
renderInputType.radio = function (radio) {
radio.textContent = '';
return radio;
};
renderInputType.checkbox = function (checkboxContainer, params) {
var checkbox = getInput(getContent(), 'checkbox');
checkbox.value = 1;
checkbox.id = swalClasses.checkbox;
checkbox.checked = Boolean(params.inputValue);
var label = checkboxContainer.querySelector('span');
setInnerHtml(label, params.inputPlaceholder);
return checkboxContainer;
};
renderInputType.textarea = function (textarea, params) {
textarea.value = params.inputValue;
setInputPlaceholder(textarea, params);
2020-11-25 09:31:52 +00:00
setInputLabel(textarea, textarea, params);
2020-04-01 22:52:43 +00:00
2020-12-23 07:17:49 +00:00
var getPadding = function getPadding(el) {
return parseInt(window.getComputedStyle(el).paddingLeft) + parseInt(window.getComputedStyle(el).paddingRight);
};
2020-04-01 22:52:43 +00:00
if ('MutationObserver' in window) {
// #1699
var initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
var outputsize = function outputsize() {
2020-12-23 07:17:49 +00:00
var contentWidth = textarea.offsetWidth + getPadding(getPopup()) + getPadding(getContent());
2020-04-01 22:52:43 +00:00
if (contentWidth > initialPopupWidth) {
getPopup().style.width = "".concat(contentWidth, "px");
} else {
getPopup().style.width = null;
}
};
new MutationObserver(outputsize).observe(textarea, {
attributes: true,
attributeFilter: ['style']
});
}
return textarea;
};
var renderContent = function renderContent(instance, params) {
2021-02-23 11:22:20 +00:00
var htmlContainer = getHtmlContainer();
applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML
2020-04-01 22:52:43 +00:00
if (params.html) {
2021-02-23 11:22:20 +00:00
parseHtmlToContainer(params.html, htmlContainer);
show(htmlContainer, 'block'); // Content as plain text
2020-04-01 22:52:43 +00:00
} else if (params.text) {
2021-02-23 11:22:20 +00:00
htmlContainer.textContent = params.text;
show(htmlContainer, 'block'); // No content
2020-04-01 22:52:43 +00:00
} else {
2021-02-23 11:22:20 +00:00
hide(htmlContainer);
2020-04-01 22:52:43 +00:00
}
renderInput(instance, params); // Custom class
2020-04-01 22:52:43 +00:00
applyCustomClass(getContent(), params, 'content');
};
2020-04-01 22:52:43 +00:00
var renderFooter = function renderFooter(instance, params) {
var footer = getFooter();
toggle(footer, params.footer);
2020-04-01 22:52:43 +00:00
if (params.footer) {
parseHtmlToContainer(params.footer, footer);
} // Custom class
2020-04-01 22:52:43 +00:00
applyCustomClass(footer, params, 'footer');
};
2020-04-01 22:52:43 +00:00
var renderCloseButton = function renderCloseButton(instance, params) {
var closeButton = getCloseButton();
setInnerHtml(closeButton, params.closeButtonHtml); // Custom class
2020-04-01 22:52:43 +00:00
applyCustomClass(closeButton, params, 'closeButton');
toggle(closeButton, params.showCloseButton);
closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
};
2020-04-01 22:52:43 +00:00
var renderIcon = function renderIcon(instance, params) {
2021-02-23 11:22:20 +00:00
var innerParams = privateProps.innerParams.get(instance);
var icon = getIcon(); // if the given icon already rendered, apply the styling without re-rendering the icon
2021-02-23 11:22:20 +00:00
if (innerParams && params.icon === innerParams.icon) {
// Custom or default content
setContent(icon, params);
applyStyles(icon, params);
2020-04-01 22:52:43 +00:00
return;
}
2021-02-23 11:22:20 +00:00
if (!params.icon && !params.iconHtml) {
return hide(icon);
2020-04-01 22:52:43 +00:00
}
2021-02-23 11:22:20 +00:00
if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
2020-04-01 22:52:43 +00:00
error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\""));
2021-02-23 11:22:20 +00:00
return hide(icon);
2020-04-01 22:52:43 +00:00
}
2021-02-23 11:22:20 +00:00
show(icon); // Custom or default content
2021-02-23 11:22:20 +00:00
setContent(icon, params);
applyStyles(icon, params); // Animate icon
addClass(icon, params.showClass.icon);
2020-11-24 07:16:03 +00:00
};
var applyStyles = function applyStyles(icon, params) {
2021-02-23 11:22:20 +00:00
for (var iconType in iconTypes) {
if (params.icon !== iconType) {
removeClass(icon, iconTypes[iconType]);
}
}
addClass(icon, iconTypes[params.icon]); // Icon color
2020-11-24 07:16:03 +00:00
setColor(icon, params); // Success icon background color
adjustSuccessIconBackgoundColor(); // Custom class
applyCustomClass(icon, params, 'icon');
2020-04-01 22:52:43 +00:00
}; // Adjust success icon background color to match the popup background color
2020-04-01 22:52:43 +00:00
var adjustSuccessIconBackgoundColor = function adjustSuccessIconBackgoundColor() {
var popup = getPopup();
var popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
var successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
2020-04-01 22:52:43 +00:00
for (var i = 0; i < successIconParts.length; i++) {
successIconParts[i].style.backgroundColor = popupBackgroundColor;
}
};
2020-04-01 22:52:43 +00:00
var setContent = function setContent(icon, params) {
icon.textContent = '';
2020-04-01 22:52:43 +00:00
if (params.iconHtml) {
setInnerHtml(icon, iconContent(params.iconHtml));
} else if (params.icon === 'success') {
setInnerHtml(icon, "\n <div class=\"swal2-success-circular-line-left\"></div>\n <span class=\"swal2-success-line-tip\"></span> <span class=\"swal2-success-line-long\"></span>\n <div class=\"swal2-success-ring\"></div> <div class=\"swal2-success-fix\"></div>\n <div class=\"swal2-success-circular-line-right\"></div>\n ");
} else if (params.icon === 'error') {
setInnerHtml(icon, "\n <span class=\"swal2-x-mark\">\n <span class=\"swal2-x-mark-line-left\"></span>\n <span class=\"swal2-x-mark-line-right\"></span>\n </span>\n ");
} else {
var defaultIconHtml = {
question: '?',
warning: '!',
info: 'i'
};
setInnerHtml(icon, iconContent(defaultIconHtml[params.icon]));
}
};
2020-11-24 07:16:03 +00:00
var setColor = function setColor(icon, params) {
if (!params.iconColor) {
return;
}
icon.style.color = params.iconColor;
icon.style.borderColor = params.iconColor;
for (var _i = 0, _arr = ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']; _i < _arr.length; _i++) {
var sel = _arr[_i];
setStyle(icon, sel, 'backgroundColor', params.iconColor);
}
setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);
};
2020-04-01 22:52:43 +00:00
var iconContent = function iconContent(content) {
return "<div class=\"".concat(swalClasses['icon-content'], "\">").concat(content, "</div>");
};
2020-04-01 22:52:43 +00:00
var renderImage = function renderImage(instance, params) {
var image = getImage();
2020-04-01 22:52:43 +00:00
if (!params.imageUrl) {
return hide(image);
}
show(image, ''); // Src, alt
2020-04-01 22:52:43 +00:00
image.setAttribute('src', params.imageUrl);
image.setAttribute('alt', params.imageAlt); // Width, height
2020-04-01 22:52:43 +00:00
applyNumericalStyle(image, 'width', params.imageWidth);
applyNumericalStyle(image, 'height', params.imageHeight); // Class
2020-04-01 22:52:43 +00:00
image.className = swalClasses.image;
applyCustomClass(image, params, 'image');
};
2020-04-01 22:52:43 +00:00
var currentSteps = [];
/*
* Global function for chaining sweetAlert popups
*/
2020-04-01 22:52:43 +00:00
var queue = function queue(steps) {
var Swal = this;
currentSteps = steps;
2020-04-01 22:52:43 +00:00
var resetAndResolve = function resetAndResolve(resolve, value) {
currentSteps = [];
resolve(value);
};
2020-04-01 22:52:43 +00:00
var queueResult = [];
return new Promise(function (resolve) {
(function step(i, callback) {
if (i < currentSteps.length) {
document.body.setAttribute('data-swal2-queue-step', i);
Swal.fire(currentSteps[i]).then(function (result) {
if (typeof result.value !== 'undefined') {
queueResult.push(result.value);
step(i + 1, callback);
} else {
resetAndResolve(resolve, {
dismiss: result.dismiss
});
}
});
} else {
resetAndResolve(resolve, {
value: queueResult
});
}
})(0);
});
};
/*
* Global function for getting the index of current popup in queue
*/
var getQueueStep = function getQueueStep() {
return getContainer() && getContainer().getAttribute('data-queue-step');
2020-04-01 22:52:43 +00:00
};
/*
* Global function for inserting a popup to the queue
*/
2020-04-01 22:52:43 +00:00
var insertQueueStep = function insertQueueStep(step, index) {
if (index && index < currentSteps.length) {
return currentSteps.splice(index, 0, step);
}
2020-04-01 22:52:43 +00:00
return currentSteps.push(step);
};
/*
* Global function for deleting a popup from the queue
*/
2020-04-01 22:52:43 +00:00
var deleteQueueStep = function deleteQueueStep(index) {
if (typeof currentSteps[index] !== 'undefined') {
currentSteps.splice(index, 1);
}
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
var createStepElement = function createStepElement(step) {
var stepEl = document.createElement('li');
addClass(stepEl, swalClasses['progress-step']);
setInnerHtml(stepEl, step);
return stepEl;
};
2020-04-01 22:52:43 +00:00
var createLineElement = function createLineElement(params) {
var lineEl = document.createElement('li');
addClass(lineEl, swalClasses['progress-step-line']);
2020-04-01 22:52:43 +00:00
if (params.progressStepsDistance) {
lineEl.style.width = params.progressStepsDistance;
}
2020-04-01 22:52:43 +00:00
return lineEl;
};
2020-04-01 22:52:43 +00:00
var renderProgressSteps = function renderProgressSteps(instance, params) {
var progressStepsContainer = getProgressSteps();
2020-04-01 22:52:43 +00:00
if (!params.progressSteps || params.progressSteps.length === 0) {
return hide(progressStepsContainer);
}
2020-04-01 22:52:43 +00:00
show(progressStepsContainer);
progressStepsContainer.textContent = '';
var currentProgressStep = parseInt(params.currentProgressStep === undefined ? getQueueStep() : params.currentProgressStep);
2020-04-01 22:52:43 +00:00
if (currentProgressStep >= params.progressSteps.length) {
warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
}
2020-04-01 22:52:43 +00:00
params.progressSteps.forEach(function (step, index) {
var stepEl = createStepElement(step);
progressStepsContainer.appendChild(stepEl);
2020-04-01 22:52:43 +00:00
if (index === currentProgressStep) {
addClass(stepEl, swalClasses['active-progress-step']);
}
if (index !== params.progressSteps.length - 1) {
var lineEl = createLineElement(params);
2020-04-01 22:52:43 +00:00
progressStepsContainer.appendChild(lineEl);
}
});
};
2020-04-01 22:52:43 +00:00
var renderTitle = function renderTitle(instance, params) {
var title = getTitle();
toggle(title, params.title || params.titleText);
2020-04-01 22:52:43 +00:00
if (params.title) {
parseHtmlToContainer(params.title, title);
}
2020-04-01 22:52:43 +00:00
if (params.titleText) {
title.innerText = params.titleText;
} // Custom class
2020-04-01 22:52:43 +00:00
applyCustomClass(title, params, 'title');
};
2020-04-01 22:52:43 +00:00
var renderHeader = function renderHeader(instance, params) {
var header = getHeader(); // Custom class
2020-04-01 22:52:43 +00:00
applyCustomClass(header, params, 'header'); // Progress steps
2020-04-01 22:52:43 +00:00
renderProgressSteps(instance, params); // Icon
2020-04-01 22:52:43 +00:00
renderIcon(instance, params); // Image
2020-04-01 22:52:43 +00:00
renderImage(instance, params); // Title
2020-04-01 22:52:43 +00:00
renderTitle(instance, params); // Close button
2020-04-01 22:52:43 +00:00
renderCloseButton(instance, params);
};
2020-04-01 22:52:43 +00:00
var renderPopup = function renderPopup(instance, params) {
2021-02-23 11:22:20 +00:00
var container = getContainer();
2020-04-01 22:52:43 +00:00
var popup = getPopup(); // Width
2021-02-23 11:22:20 +00:00
if (params.toast) {
// #2170
applyNumericalStyle(container, 'width', params.width);
popup.style.width = '100%';
} else {
applyNumericalStyle(popup, 'width', params.width);
} // Padding
2020-04-01 22:52:43 +00:00
applyNumericalStyle(popup, 'padding', params.padding); // Background
2020-04-01 22:52:43 +00:00
if (params.background) {
popup.style.background = params.background;
} // Classes
2020-04-01 22:52:43 +00:00
addClasses(popup, params);
};
2020-04-01 22:52:43 +00:00
var addClasses = function addClasses(popup, params) {
// Default Class + showClass when updating Swal.update({})
popup.className = "".concat(swalClasses.popup, " ").concat(isVisible(popup) ? params.showClass.popup : '');
2020-04-01 22:52:43 +00:00
if (params.toast) {
addClass([document.documentElement, document.body], swalClasses['toast-shown']);
addClass(popup, swalClasses.toast);
} else {
addClass(popup, swalClasses.modal);
} // Custom class
2020-04-01 22:52:43 +00:00
applyCustomClass(popup, params, 'popup');
2020-04-01 22:52:43 +00:00
if (typeof params.customClass === 'string') {
addClass(popup, params.customClass);
} // Icon class (#1842)
2020-04-01 22:52:43 +00:00
if (params.icon) {
addClass(popup, swalClasses["icon-".concat(params.icon)]);
}
};
2020-04-01 22:52:43 +00:00
var render = function render(instance, params) {
renderPopup(instance, params);
renderContainer(instance, params);
renderHeader(instance, params);
renderContent(instance, params);
renderActions(instance, params);
renderFooter(instance, params);
2020-11-24 07:16:03 +00:00
if (typeof params.didRender === 'function') {
params.didRender(getPopup());
} else if (typeof params.onRender === 'function') {
params.onRender(getPopup()); // @deprecated
2020-04-01 22:52:43 +00:00
}
};
2020-04-01 22:52:43 +00:00
/*
* Global function to determine if SweetAlert2 popup is shown
*/
2020-04-01 22:52:43 +00:00
var isVisible$1 = function isVisible$$1() {
return isVisible(getPopup());
};
/*
* Global function to click 'Confirm' button
*/
2020-04-01 22:52:43 +00:00
var clickConfirm = function clickConfirm() {
return getConfirmButton() && getConfirmButton().click();
};
2020-11-24 07:16:03 +00:00
/*
* Global function to click 'Deny' button
*/
var clickDeny = function clickDeny() {
return getDenyButton() && getDenyButton().click();
};
2020-04-01 22:52:43 +00:00
/*
* Global function to click 'Cancel' button
*/
2020-04-01 22:52:43 +00:00
var clickCancel = function clickCancel() {
return getCancelButton() && getCancelButton().click();
};
2020-04-01 22:52:43 +00:00
function fire() {
var Swal = this;
2020-04-01 22:52:43 +00:00
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
2020-04-01 22:52:43 +00:00
return _construct(Swal, args);
}
/**
* Returns an extended version of `Swal` containing `params` as defaults.
* Useful for reusing Swal configuration.
*
* For example:
*
* Before:
* const textPromptOptions = { input: 'text', showCancelButton: true }
* const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
* const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
*
* After:
* const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
* const {value: firstName} = await TextPrompt('What is your first name?')
* const {value: lastName} = await TextPrompt('What is your last name?')
*
* @param mixinParams
*/
function mixin(mixinParams) {
var MixinSwal = /*#__PURE__*/function (_this) {
_inherits(MixinSwal, _this);
var _super = _createSuper(MixinSwal);
2020-04-01 22:52:43 +00:00
function MixinSwal() {
_classCallCheck(this, MixinSwal);
return _super.apply(this, arguments);
2020-04-01 22:52:43 +00:00
}
2020-04-01 22:52:43 +00:00
_createClass(MixinSwal, [{
key: "_main",
2021-02-23 11:22:20 +00:00
value: function _main(params, priorityMixinParams) {
return _get(_getPrototypeOf(MixinSwal.prototype), "_main", this).call(this, params, _extends({}, mixinParams, priorityMixinParams));
2020-04-01 22:52:43 +00:00
}
}]);
2020-04-01 22:52:43 +00:00
return MixinSwal;
}(this);
2020-04-01 22:52:43 +00:00
return MixinSwal;
}
2020-04-01 22:52:43 +00:00
/**
2020-11-25 09:31:52 +00:00
* Shows loader (spinner), this is useful with AJAX requests.
* By default the loader be shown instead of the "Confirm" button.
2020-04-01 22:52:43 +00:00
*/
2020-11-25 09:31:52 +00:00
var showLoading = function showLoading(buttonToReplace) {
2020-04-01 22:52:43 +00:00
var popup = getPopup();
2020-04-01 22:52:43 +00:00
if (!popup) {
Swal.fire();
}
2020-04-01 22:52:43 +00:00
popup = getPopup();
var actions = getActions();
2020-11-24 07:16:03 +00:00
var loader = getLoader();
2020-11-25 09:31:52 +00:00
if (!buttonToReplace && isVisible(getConfirmButton())) {
buttonToReplace = getConfirmButton();
}
2020-04-01 22:52:43 +00:00
show(actions);
2020-11-25 09:31:52 +00:00
if (buttonToReplace) {
hide(buttonToReplace);
loader.setAttribute('data-button-to-replace', buttonToReplace.className);
}
loader.parentNode.insertBefore(loader, buttonToReplace);
2020-04-01 22:52:43 +00:00
addClass([popup, actions], swalClasses.loading);
2020-11-24 07:16:03 +00:00
show(loader);
2020-04-01 22:52:43 +00:00
popup.setAttribute('data-loading', true);
popup.setAttribute('aria-busy', true);
popup.focus();
};
2020-04-01 22:52:43 +00:00
var RESTORE_FOCUS_TIMEOUT = 100;
2020-04-01 22:52:43 +00:00
var globalState = {};
2020-04-01 22:52:43 +00:00
var focusPreviousActiveElement = function focusPreviousActiveElement() {
if (globalState.previousActiveElement && globalState.previousActiveElement.focus) {
globalState.previousActiveElement.focus();
globalState.previousActiveElement = null;
} else if (document.body) {
document.body.focus();
}
}; // Restore previous active (focused) element
2020-04-01 22:52:43 +00:00
var restoreActiveElement = function restoreActiveElement() {
return new Promise(function (resolve) {
var x = window.scrollX;
var y = window.scrollY;
globalState.restoreFocusTimeout = setTimeout(function () {
focusPreviousActiveElement();
resolve();
}, RESTORE_FOCUS_TIMEOUT); // issues/900
2020-04-01 22:52:43 +00:00
/* istanbul ignore if */
2020-04-01 22:52:43 +00:00
if (typeof x !== 'undefined' && typeof y !== 'undefined') {
// IE doesn't have scrollX/scrollY support
window.scrollTo(x, y);
}
});
};
2020-04-01 22:52:43 +00:00
/**
* If `timer` parameter is set, returns number of milliseconds of timer remained.
* Otherwise, returns undefined.
*/
2020-04-01 22:52:43 +00:00
var getTimerLeft = function getTimerLeft() {
return globalState.timeout && globalState.timeout.getTimerLeft();
};
/**
* Stop timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
var stopTimer = function stopTimer() {
if (globalState.timeout) {
stopTimerProgressBar();
return globalState.timeout.stop();
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
var resumeTimer = function resumeTimer() {
if (globalState.timeout) {
var remaining = globalState.timeout.start();
animateTimerProgressBar(remaining);
return remaining;
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
var toggleTimer = function toggleTimer() {
var timer = globalState.timeout;
return timer && (timer.running ? stopTimer() : resumeTimer());
};
/**
* Increase timer. Returns number of milliseconds of an updated timer.
* If `timer` parameter isn't set, returns undefined.
*/
var increaseTimer = function increaseTimer(n) {
if (globalState.timeout) {
var remaining = globalState.timeout.increase(n);
animateTimerProgressBar(remaining, true);
return remaining;
}
};
/**
* Check if timer is running. Returns true if timer is running
* or false if timer is paused or stopped.
* If `timer` parameter isn't set, returns undefined
*/
var isTimerRunning = function isTimerRunning() {
return globalState.timeout && globalState.timeout.isRunning();
};
2020-12-23 07:17:49 +00:00
var bodyClickListenerAdded = false;
var clickHandlers = {};
function bindClickHandler() {
var attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
clickHandlers[attr] = this;
if (!bodyClickListenerAdded) {
document.body.addEventListener('click', bodyClickListener);
bodyClickListenerAdded = true;
}
}
var bodyClickListener = function bodyClickListener(event) {
// 1. using .parentNode instead of event.path because of better support by old browsers https://stackoverflow.com/a/39245638
// 2. using .parentNode instead of .parentElement because of IE11 + SVG https://stackoverflow.com/a/36270354
for (var el = event.target; el && el !== document; el = el.parentNode) {
for (var attr in clickHandlers) {
var template = el.getAttribute(attr);
if (template) {
clickHandlers[attr].fire({
template: template
});
return;
}
}
}
};
2020-04-01 22:52:43 +00:00
var defaultParams = {
title: '',
titleText: '',
text: '',
html: '',
footer: '',
icon: undefined,
2020-11-24 07:16:03 +00:00
iconColor: undefined,
2020-04-01 22:52:43 +00:00
iconHtml: undefined,
2020-12-23 07:17:49 +00:00
template: undefined,
2020-04-01 22:52:43 +00:00
toast: false,
animation: true,
showClass: {
popup: 'swal2-show',
backdrop: 'swal2-backdrop-show',
icon: 'swal2-icon-show'
},
hideClass: {
popup: 'swal2-hide',
backdrop: 'swal2-backdrop-hide',
icon: 'swal2-icon-hide'
},
2020-12-23 07:17:49 +00:00
customClass: {},
2020-04-01 22:52:43 +00:00
target: 'body',
backdrop: true,
heightAuto: true,
allowOutsideClick: true,
allowEscapeKey: true,
allowEnterKey: true,
stopKeydownPropagation: true,
keydownListenerCapture: false,
showConfirmButton: true,
2020-11-24 07:16:03 +00:00
showDenyButton: false,
2020-04-01 22:52:43 +00:00
showCancelButton: false,
preConfirm: undefined,
2020-11-25 09:31:52 +00:00
preDeny: undefined,
2020-04-01 22:52:43 +00:00
confirmButtonText: 'OK',
confirmButtonAriaLabel: '',
confirmButtonColor: undefined,
2020-11-24 07:16:03 +00:00
denyButtonText: 'No',
denyButtonAriaLabel: '',
denyButtonColor: undefined,
2020-04-01 22:52:43 +00:00
cancelButtonText: 'Cancel',
cancelButtonAriaLabel: '',
cancelButtonColor: undefined,
buttonsStyling: true,
reverseButtons: false,
focusConfirm: true,
2020-11-24 07:16:03 +00:00
focusDeny: false,
2020-04-01 22:52:43 +00:00
focusCancel: false,
showCloseButton: false,
closeButtonHtml: '&times;',
closeButtonAriaLabel: 'Close this dialog',
2020-11-24 07:16:03 +00:00
loaderHtml: '',
2020-04-01 22:52:43 +00:00
showLoaderOnConfirm: false,
2021-02-02 06:47:35 +00:00
showLoaderOnDeny: false,
2020-04-01 22:52:43 +00:00
imageUrl: undefined,
imageWidth: undefined,
imageHeight: undefined,
imageAlt: '',
timer: undefined,
timerProgressBar: false,
width: undefined,
padding: undefined,
background: undefined,
input: undefined,
inputPlaceholder: '',
2020-11-25 09:31:52 +00:00
inputLabel: '',
2020-04-01 22:52:43 +00:00
inputValue: '',
inputOptions: {},
inputAutoTrim: true,
inputAttributes: {},
inputValidator: undefined,
2020-11-25 09:31:52 +00:00
returnInputValueOnDeny: false,
2020-04-01 22:52:43 +00:00
validationMessage: undefined,
grow: false,
position: 'center',
progressSteps: [],
currentProgressStep: undefined,
progressStepsDistance: undefined,
onBeforeOpen: undefined,
onOpen: undefined,
2020-11-24 07:16:03 +00:00
willOpen: undefined,
didOpen: undefined,
2020-04-01 22:52:43 +00:00
onRender: undefined,
2020-11-24 07:16:03 +00:00
didRender: undefined,
2020-04-01 22:52:43 +00:00
onClose: undefined,
onAfterClose: undefined,
2020-11-24 07:16:03 +00:00
willClose: undefined,
didClose: undefined,
2020-04-01 22:52:43 +00:00
onDestroy: undefined,
2020-11-24 07:16:03 +00:00
didDestroy: undefined,
2020-04-01 22:52:43 +00:00
scrollbarPadding: true
};
2021-02-23 11:22:20 +00:00
var updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'onAfterClose', 'onClose', 'onDestroy', 'progressSteps', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];
2020-04-01 22:52:43 +00:00
var deprecatedParams = {
2020-11-24 07:16:03 +00:00
animation: 'showClass" and "hideClass',
onBeforeOpen: 'willOpen',
onOpen: 'didOpen',
onRender: 'didRender',
onClose: 'willClose',
onAfterClose: 'didClose',
onDestroy: 'didDestroy'
};
var toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'heightAuto', 'keydownListenerCapture'];
2020-04-01 22:52:43 +00:00
/**
* Is valid parameter
* @param {String} paramName
*/
var isValidParameter = function isValidParameter(paramName) {
return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
};
/**
* Is valid parameter for Swal.update() method
* @param {String} paramName
*/
2020-04-01 22:52:43 +00:00
var isUpdatableParameter = function isUpdatableParameter(paramName) {
return updatableParams.indexOf(paramName) !== -1;
};
/**
* Is deprecated parameter
* @param {String} paramName
*/
2020-04-01 22:52:43 +00:00
var isDeprecatedParameter = function isDeprecatedParameter(paramName) {
return deprecatedParams[paramName];
};
2020-04-01 22:52:43 +00:00
var checkIfParamIsValid = function checkIfParamIsValid(param) {
if (!isValidParameter(param)) {
warn("Unknown parameter \"".concat(param, "\""));
}
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
var checkIfToastParamIsValid = function checkIfToastParamIsValid(param) {
if (toastIncompatibleParams.indexOf(param) !== -1) {
warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
}
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
var checkIfParamIsDeprecated = function checkIfParamIsDeprecated(param) {
if (isDeprecatedParameter(param)) {
2020-11-24 07:16:03 +00:00
warnAboutDeprecation(param, isDeprecatedParameter(param));
2020-04-01 22:52:43 +00:00
}
};
/**
* Show relevant warnings for given params
*
* @param params
*/
2020-04-01 22:52:43 +00:00
var showWarningsForParams = function showWarningsForParams(params) {
for (var param in params) {
checkIfParamIsValid(param);
2020-04-01 22:52:43 +00:00
if (params.toast) {
checkIfToastParamIsValid(param);
}
2020-04-01 22:52:43 +00:00
checkIfParamIsDeprecated(param);
}
};
2020-04-01 22:52:43 +00:00
var staticMethods = /*#__PURE__*/Object.freeze({
isValidParameter: isValidParameter,
isUpdatableParameter: isUpdatableParameter,
isDeprecatedParameter: isDeprecatedParameter,
argsToParams: argsToParams,
isVisible: isVisible$1,
clickConfirm: clickConfirm,
2020-11-24 07:16:03 +00:00
clickDeny: clickDeny,
2020-04-01 22:52:43 +00:00
clickCancel: clickCancel,
getContainer: getContainer,
getPopup: getPopup,
getTitle: getTitle,
getContent: getContent,
getHtmlContainer: getHtmlContainer,
getImage: getImage,
getIcon: getIcon,
2020-11-25 09:31:52 +00:00
getInputLabel: getInputLabel,
2020-04-01 22:52:43 +00:00
getCloseButton: getCloseButton,
getActions: getActions,
getConfirmButton: getConfirmButton,
2020-11-24 07:16:03 +00:00
getDenyButton: getDenyButton,
2020-04-01 22:52:43 +00:00
getCancelButton: getCancelButton,
2020-11-25 09:31:52 +00:00
getLoader: getLoader,
2020-04-01 22:52:43 +00:00
getHeader: getHeader,
getFooter: getFooter,
getTimerProgressBar: getTimerProgressBar,
getFocusableElements: getFocusableElements,
getValidationMessage: getValidationMessage,
isLoading: isLoading,
fire: fire,
mixin: mixin,
queue: queue,
getQueueStep: getQueueStep,
insertQueueStep: insertQueueStep,
deleteQueueStep: deleteQueueStep,
showLoading: showLoading,
enableLoading: showLoading,
getTimerLeft: getTimerLeft,
stopTimer: stopTimer,
resumeTimer: resumeTimer,
toggleTimer: toggleTimer,
increaseTimer: increaseTimer,
2020-12-23 07:17:49 +00:00
isTimerRunning: isTimerRunning,
bindClickHandler: bindClickHandler
2020-04-01 22:52:43 +00:00
});
2020-04-01 22:52:43 +00:00
/**
2020-11-25 09:31:52 +00:00
* Hides loader and shows back the button which was hidden by .showLoading()
2020-04-01 22:52:43 +00:00
*/
2020-04-01 22:52:43 +00:00
function hideLoading() {
// do nothing if popup is closed
var innerParams = privateProps.innerParams.get(this);
2020-04-01 22:52:43 +00:00
if (!innerParams) {
return;
}
2020-04-01 22:52:43 +00:00
var domCache = privateProps.domCache.get(this);
2020-11-24 07:16:03 +00:00
hide(domCache.loader);
2020-11-25 09:31:52 +00:00
var buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
2020-11-25 09:31:52 +00:00
if (buttonToReplace.length) {
show(buttonToReplace[0], 'inline-block');
} else if (allButtonsAreHidden()) {
2020-11-24 07:16:03 +00:00
hide(domCache.actions);
2020-04-01 22:52:43 +00:00
}
2020-04-01 22:52:43 +00:00
removeClass([domCache.popup, domCache.actions], swalClasses.loading);
domCache.popup.removeAttribute('aria-busy');
domCache.popup.removeAttribute('data-loading');
domCache.confirmButton.disabled = false;
2020-11-24 07:16:03 +00:00
domCache.denyButton.disabled = false;
2020-04-01 22:52:43 +00:00
domCache.cancelButton.disabled = false;
}
2020-04-01 22:52:43 +00:00
function getInput$1(instance) {
var innerParams = privateProps.innerParams.get(instance || this);
var domCache = privateProps.domCache.get(instance || this);
2020-04-01 22:52:43 +00:00
if (!domCache) {
return null;
}
2020-04-01 22:52:43 +00:00
return getInput(domCache.content, innerParams.input);
}
2020-04-01 22:52:43 +00:00
var fixScrollbar = function fixScrollbar() {
// for queues, do not do this more than once
if (states.previousBodyPadding !== null) {
return;
} // if the body has overflow
2020-04-01 22:52:43 +00:00
if (document.body.scrollHeight > window.innerHeight) {
// add padding so the content doesn't shift after removal of scrollbar
states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
document.body.style.paddingRight = "".concat(states.previousBodyPadding + measureScrollbar(), "px");
}
};
var undoScrollbar = function undoScrollbar() {
if (states.previousBodyPadding !== null) {
document.body.style.paddingRight = "".concat(states.previousBodyPadding, "px");
states.previousBodyPadding = null;
}
};
2020-04-01 22:52:43 +00:00
/* istanbul ignore file */
2020-04-01 22:52:43 +00:00
var iOSfix = function iOSfix() {
var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
2020-04-01 22:52:43 +00:00
if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
var offset = document.body.scrollTop;
document.body.style.top = "".concat(offset * -1, "px");
addClass(document.body, swalClasses.iosfix);
lockBodyScroll();
addBottomPaddingForTallPopups(); // #1948
}
};
var addBottomPaddingForTallPopups = function addBottomPaddingForTallPopups() {
var safari = !navigator.userAgent.match(/(CriOS|FxiOS|EdgiOS|YaBrowser|UCBrowser)/i);
if (safari) {
var bottomPanelHeight = 44;
if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {
getContainer().style.paddingBottom = "".concat(bottomPanelHeight, "px");
}
2020-04-01 22:52:43 +00:00
}
};
2020-04-01 22:52:43 +00:00
var lockBodyScroll = function lockBodyScroll() {
// #1246
var container = getContainer();
var preventTouchMove;
2020-04-01 22:52:43 +00:00
container.ontouchstart = function (e) {
2020-11-25 09:31:52 +00:00
preventTouchMove = shouldPreventTouchMove(e);
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
container.ontouchmove = function (e) {
if (preventTouchMove) {
e.preventDefault();
e.stopPropagation();
}
2020-04-01 22:52:43 +00:00
};
};
2020-11-25 09:31:52 +00:00
var shouldPreventTouchMove = function shouldPreventTouchMove(event) {
var target = event.target;
var container = getContainer();
2020-11-25 09:31:52 +00:00
if (isStylys(event) || isZoom(event)) {
return false;
}
if (target === container) {
return true;
}
if (!isScrollable(container) && target.tagName !== 'INPUT' && // #1603
!(isScrollable(getContent()) && // #1944
getContent().contains(target))) {
return true;
}
return false;
};
2020-11-25 09:31:52 +00:00
var isStylys = function isStylys(event) {
// #1786
return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
};
var isZoom = function isZoom(event) {
// #1891
return event.touches && event.touches.length > 1;
};
2020-04-01 22:52:43 +00:00
var undoIOSfix = function undoIOSfix() {
if (hasClass(document.body, swalClasses.iosfix)) {
var offset = parseInt(document.body.style.top, 10);
removeClass(document.body, swalClasses.iosfix);
document.body.style.top = '';
document.body.scrollTop = offset * -1;
}
};
2020-04-01 22:52:43 +00:00
/* istanbul ignore file */
2020-04-01 22:52:43 +00:00
var isIE11 = function isIE11() {
return !!window.MSInputMethodContext && !!document.documentMode;
}; // Fix IE11 centering sweetalert2/issues/933
2020-04-01 22:52:43 +00:00
var fixVerticalPositionIE = function fixVerticalPositionIE() {
var container = getContainer();
var popup = getPopup();
container.style.removeProperty('align-items');
2020-04-01 22:52:43 +00:00
if (popup.offsetTop < 0) {
container.style.alignItems = 'flex-start';
}
};
2020-04-01 22:52:43 +00:00
var IEfix = function IEfix() {
if (typeof window !== 'undefined' && isIE11()) {
fixVerticalPositionIE();
window.addEventListener('resize', fixVerticalPositionIE);
}
};
var undoIEfix = function undoIEfix() {
if (typeof window !== 'undefined' && isIE11()) {
window.removeEventListener('resize', fixVerticalPositionIE);
}
};
2020-04-01 22:52:43 +00:00
// Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
// elements not within the active modal dialog will not be surfaced if a user opens a screen
// readers list of elements (headings, form controls, landmarks, etc.) in the document.
2020-04-01 22:52:43 +00:00
var setAriaHidden = function setAriaHidden() {
var bodyChildren = toArray(document.body.children);
bodyChildren.forEach(function (el) {
if (el === getContainer() || contains(el, getContainer())) {
return;
}
2020-04-01 22:52:43 +00:00
if (el.hasAttribute('aria-hidden')) {
el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
}
2020-04-01 22:52:43 +00:00
el.setAttribute('aria-hidden', 'true');
});
};
var unsetAriaHidden = function unsetAriaHidden() {
var bodyChildren = toArray(document.body.children);
bodyChildren.forEach(function (el) {
if (el.hasAttribute('data-previous-aria-hidden')) {
el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
el.removeAttribute('data-previous-aria-hidden');
} else {
el.removeAttribute('aria-hidden');
}
});
};
2020-04-01 22:52:43 +00:00
/**
* This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* https://github.com/tc39/proposal-private-methods
* https://github.com/babel/babel/pull/7555
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateMethods = {
swalPromiseResolve: new WeakMap()
};
2020-04-01 22:52:43 +00:00
/*
* Instance method to close sweetAlert
*/
2020-11-24 07:16:03 +00:00
function removePopupAndResetState(instance, container, isToast$$1, didClose) {
2020-04-01 22:52:43 +00:00
if (isToast$$1) {
2020-11-24 07:16:03 +00:00
triggerDidCloseAndDispose(instance, didClose);
2020-04-01 22:52:43 +00:00
} else {
restoreActiveElement().then(function () {
2020-11-24 07:16:03 +00:00
return triggerDidCloseAndDispose(instance, didClose);
2020-04-01 22:52:43 +00:00
});
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = false;
}
2020-04-01 22:52:43 +00:00
if (container.parentNode && !document.body.getAttribute('data-swal2-queue-step')) {
container.parentNode.removeChild(container);
}
2020-04-01 22:52:43 +00:00
if (isModal()) {
undoScrollbar();
undoIOSfix();
undoIEfix();
unsetAriaHidden();
}
2020-04-01 22:52:43 +00:00
removeBodyClasses();
}
2020-04-01 22:52:43 +00:00
function removeBodyClasses() {
removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['toast-column']]);
}
2020-04-01 22:52:43 +00:00
function close(resolveValue) {
var popup = getPopup();
2020-04-01 22:52:43 +00:00
if (!popup) {
return;
}
2020-11-24 07:16:03 +00:00
resolveValue = prepareResolveValue(resolveValue);
2020-04-01 22:52:43 +00:00
var innerParams = privateProps.innerParams.get(this);
2020-04-01 22:52:43 +00:00
if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
return;
}
2020-04-01 22:52:43 +00:00
var swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
removeClass(popup, innerParams.showClass.popup);
addClass(popup, innerParams.hideClass.popup);
var backdrop = getContainer();
removeClass(backdrop, innerParams.showClass.backdrop);
addClass(backdrop, innerParams.hideClass.backdrop);
2020-11-24 07:16:03 +00:00
handlePopupAnimation(this, popup, innerParams); // Resolve Swal promise
2020-11-24 07:16:03 +00:00
swalPromiseResolve(resolveValue);
}
2020-11-24 07:16:03 +00:00
var prepareResolveValue = function prepareResolveValue(resolveValue) {
// When user calls Swal.close()
if (typeof resolveValue === 'undefined') {
return {
isConfirmed: false,
isDenied: false,
isDismissed: true
};
}
2020-11-24 07:16:03 +00:00
return _extends({
isConfirmed: false,
isDenied: false,
isDismissed: false
}, resolveValue);
};
2020-04-01 22:52:43 +00:00
var handlePopupAnimation = function handlePopupAnimation(instance, popup, innerParams) {
var container = getContainer(); // If animation is supported, animate
2020-04-01 22:52:43 +00:00
var animationIsSupported = animationEndEvent && hasCssAnimation(popup);
var onClose = innerParams.onClose,
2020-11-24 07:16:03 +00:00
onAfterClose = innerParams.onAfterClose,
willClose = innerParams.willClose,
didClose = innerParams.didClose;
runDidClose(popup, willClose, onClose);
2020-04-01 22:52:43 +00:00
if (animationIsSupported) {
2020-11-24 07:16:03 +00:00
animatePopup(instance, popup, container, didClose || onAfterClose);
2020-04-01 22:52:43 +00:00
} else {
// Otherwise, remove immediately
2020-11-24 07:16:03 +00:00
removePopupAndResetState(instance, container, isToast(), didClose || onAfterClose);
}
};
2020-11-24 07:16:03 +00:00
var runDidClose = function runDidClose(popup, willClose, onClose) {
if (willClose !== null && typeof willClose === 'function') {
willClose(popup);
} else if (onClose !== null && typeof onClose === 'function') {
onClose(popup); // @deprecated
}
};
var animatePopup = function animatePopup(instance, popup, container, didClose) {
globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, isToast(), didClose);
2020-04-01 22:52:43 +00:00
popup.addEventListener(animationEndEvent, function (e) {
if (e.target === popup) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
}
});
};
2020-11-24 07:16:03 +00:00
var triggerDidCloseAndDispose = function triggerDidCloseAndDispose(instance, didClose) {
2020-04-01 22:52:43 +00:00
setTimeout(function () {
2020-11-24 07:16:03 +00:00
if (typeof didClose === 'function') {
didClose();
2020-04-01 22:52:43 +00:00
}
2020-04-01 22:52:43 +00:00
instance._destroy();
});
};
2020-04-01 22:52:43 +00:00
function setButtonsDisabled(instance, buttons, disabled) {
var domCache = privateProps.domCache.get(instance);
buttons.forEach(function (button) {
domCache[button].disabled = disabled;
});
}
2020-04-01 22:52:43 +00:00
function setInputDisabled(input, disabled) {
if (!input) {
return false;
}
2020-04-01 22:52:43 +00:00
if (input.type === 'radio') {
var radiosContainer = input.parentNode.parentNode;
var radios = radiosContainer.querySelectorAll('input');
2020-04-01 22:52:43 +00:00
for (var i = 0; i < radios.length; i++) {
radios[i].disabled = disabled;
}
} else {
input.disabled = disabled;
}
}
2020-04-01 22:52:43 +00:00
function enableButtons() {
2020-11-24 07:16:03 +00:00
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
}
2020-04-01 22:52:43 +00:00
function disableButtons() {
2020-11-24 07:16:03 +00:00
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
2020-04-01 22:52:43 +00:00
}
function enableInput() {
return setInputDisabled(this.getInput(), false);
}
function disableInput() {
return setInputDisabled(this.getInput(), true);
}
2020-04-01 22:52:43 +00:00
function showValidationMessage(error) {
var domCache = privateProps.domCache.get(this);
2020-11-25 09:31:52 +00:00
var params = privateProps.innerParams.get(this);
2020-04-01 22:52:43 +00:00
setInnerHtml(domCache.validationMessage, error);
2020-11-25 09:31:52 +00:00
domCache.validationMessage.className = swalClasses['validation-message'];
if (params.customClass && params.customClass.validationMessage) {
addClass(domCache.validationMessage, params.customClass.validationMessage);
}
2020-04-01 22:52:43 +00:00
show(domCache.validationMessage);
var input = this.getInput();
2020-04-01 22:52:43 +00:00
if (input) {
input.setAttribute('aria-invalid', true);
input.setAttribute('aria-describedBy', swalClasses['validation-message']);
focusInput(input);
addClass(input, swalClasses.inputerror);
}
2020-04-01 22:52:43 +00:00
} // Hide block with validation message
2020-04-01 22:52:43 +00:00
function resetValidationMessage$1() {
var domCache = privateProps.domCache.get(this);
if (domCache.validationMessage) {
hide(domCache.validationMessage);
}
2020-04-01 22:52:43 +00:00
var input = this.getInput();
if (input) {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedBy');
removeClass(input, swalClasses.inputerror);
}
}
2020-04-01 22:52:43 +00:00
function getProgressSteps$1() {
var domCache = privateProps.domCache.get(this);
return domCache.progressSteps;
}
2020-04-01 22:52:43 +00:00
var Timer = /*#__PURE__*/function () {
function Timer(callback, delay) {
_classCallCheck(this, Timer);
this.callback = callback;
this.remaining = delay;
this.running = false;
this.start();
}
_createClass(Timer, [{
key: "start",
value: function start() {
if (!this.running) {
this.running = true;
this.started = new Date();
this.id = setTimeout(this.callback, this.remaining);
}
2020-04-01 22:52:43 +00:00
return this.remaining;
}
}, {
key: "stop",
value: function stop() {
if (this.running) {
this.running = false;
clearTimeout(this.id);
this.remaining -= new Date() - this.started;
}
2020-04-01 22:52:43 +00:00
return this.remaining;
}
}, {
key: "increase",
value: function increase(n) {
var running = this.running;
2020-04-01 22:52:43 +00:00
if (running) {
this.stop();
}
2020-04-01 22:52:43 +00:00
this.remaining += n;
2020-04-01 22:52:43 +00:00
if (running) {
this.start();
}
2020-04-01 22:52:43 +00:00
return this.remaining;
}
}, {
key: "getTimerLeft",
value: function getTimerLeft() {
if (this.running) {
this.stop();
this.start();
}
2020-04-01 22:52:43 +00:00
return this.remaining;
}
}, {
key: "isRunning",
value: function isRunning() {
return this.running;
}
}]);
return Timer;
}();
2020-04-01 22:52:43 +00:00
var defaultInputValidators = {
email: function email(string, validationMessage) {
return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
},
url: function url(string, validationMessage) {
2020-07-23 21:12:30 +00:00
// taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
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');
2020-04-01 22:52:43 +00:00
}
};
2020-04-01 22:52:43 +00:00
function setDefaultInputValidators(params) {
// Use default `inputValidator` for supported input types if not provided
if (!params.inputValidator) {
Object.keys(defaultInputValidators).forEach(function (key) {
if (params.input === key) {
params.inputValidator = defaultInputValidators[key];
}
});
}
}
2020-04-01 22:52:43 +00:00
function validateCustomTargetElement(params) {
// Determine if the custom target element is valid
if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
warn('Target parameter is not valid, defaulting to "body"');
params.target = 'body';
}
}
/**
* Set type, text and actions on popup
*
* @param params
* @returns {boolean}
*/
2020-04-01 22:52:43 +00:00
function setParameters(params) {
setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm
2020-04-01 22:52:43 +00:00
if (params.showLoaderOnConfirm && !params.preConfirm) {
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');
} // params.animation will be actually used in renderPopup.js
// but in case when params.animation is a function, we need to call that function
// before popup (re)initialization, so it'll be possible to check Swal.isVisible()
// inside the params.animation function
2020-04-01 22:52:43 +00:00
params.animation = callIfFunction(params.animation);
validateCustomTargetElement(params); // Replace newlines with <br> in title
2020-04-01 22:52:43 +00:00
if (typeof params.title === 'string') {
params.title = params.title.split('\n').join('<br />');
}
2020-04-01 22:52:43 +00:00
init(params);
}
2020-12-23 07:17:49 +00:00
var swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
var getTemplateParams = function getTemplateParams(params) {
var template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;
if (!template) {
return {};
}
var templateContent = template.content || template; // IE11
showWarningsForElements(templateContent);
var result = _extends(getSwalParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
return result;
};
var getSwalParams = function getSwalParams(templateContent) {
var result = {};
toArray(templateContent.querySelectorAll('swal-param')).forEach(function (param) {
showWarningsForAttributes(param, ['name', 'value']);
var paramName = param.getAttribute('name');
var value = param.getAttribute('value');
if (typeof defaultParams[paramName] === 'boolean' && value === 'false') {
value = false;
}
if (_typeof(defaultParams[paramName]) === 'object') {
value = JSON.parse(value);
}
result[paramName] = value;
});
return result;
};
var getSwalButtons = function getSwalButtons(templateContent) {
var result = {};
toArray(templateContent.querySelectorAll('swal-button')).forEach(function (button) {
showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
var type = button.getAttribute('type');
result["".concat(type, "ButtonText")] = button.innerHTML;
result["show".concat(capitalizeFirstLetter(type), "Button")] = true;
if (button.hasAttribute('color')) {
result["".concat(type, "ButtonColor")] = button.getAttribute('color');
}
if (button.hasAttribute('aria-label')) {
result["".concat(type, "ButtonAriaLabel")] = button.getAttribute('aria-label');
}
});
return result;
};
var getSwalImage = function getSwalImage(templateContent) {
var result = {};
var image = templateContent.querySelector('swal-image');
if (image) {
showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
if (image.hasAttribute('src')) {
result.imageUrl = image.getAttribute('src');
}
if (image.hasAttribute('width')) {
result.imageWidth = image.getAttribute('width');
}
if (image.hasAttribute('height')) {
result.imageHeight = image.getAttribute('height');
}
if (image.hasAttribute('alt')) {
result.imageAlt = image.getAttribute('alt');
}
}
return result;
};
var getSwalIcon = function getSwalIcon(templateContent) {
var result = {};
var icon = templateContent.querySelector('swal-icon');
if (icon) {
showWarningsForAttributes(icon, ['type', 'color']);
if (icon.hasAttribute('type')) {
result.icon = icon.getAttribute('type');
}
if (icon.hasAttribute('color')) {
result.iconColor = icon.getAttribute('color');
}
result.iconHtml = icon.innerHTML;
}
return result;
};
var getSwalInput = function getSwalInput(templateContent) {
var result = {};
var input = templateContent.querySelector('swal-input');
if (input) {
showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
result.input = input.getAttribute('type') || 'text';
if (input.hasAttribute('label')) {
result.inputLabel = input.getAttribute('label');
}
if (input.hasAttribute('placeholder')) {
result.inputPlaceholder = input.getAttribute('placeholder');
}
if (input.hasAttribute('value')) {
result.inputValue = input.getAttribute('value');
}
}
var inputOptions = templateContent.querySelectorAll('swal-input-option');
if (inputOptions.length) {
result.inputOptions = {};
toArray(inputOptions).forEach(function (option) {
showWarningsForAttributes(option, ['value']);
var optionValue = option.getAttribute('value');
var optionName = option.innerHTML;
result.inputOptions[optionValue] = optionName;
});
}
return result;
};
var getSwalStringParams = function getSwalStringParams(templateContent, paramNames) {
var result = {};
for (var i in paramNames) {
var paramName = paramNames[i];
var tag = templateContent.querySelector(paramName);
if (tag) {
showWarningsForAttributes(tag, []);
result[paramName.replace(/^swal-/, '')] = tag.innerHTML;
}
}
return result;
};
var showWarningsForElements = function showWarningsForElements(template) {
var allowedElements = swalStringParams.concat(['swal-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
2021-02-02 06:47:35 +00:00
toArray(template.querySelectorAll('*')).forEach(function (el) {
if (el.parentNode !== template) {
// can't use template.children because of IE11
return;
}
2020-12-23 07:17:49 +00:00
var tagName = el.tagName.toLowerCase();
if (allowedElements.indexOf(tagName) === -1) {
warn("Unrecognized element <".concat(tagName, ">"));
}
});
};
var showWarningsForAttributes = function showWarningsForAttributes(el, allowedAttributes) {
toArray(el.attributes).forEach(function (attribute) {
if (allowedAttributes.indexOf(attribute.name) === -1) {
warn(["Unrecognized attribute \"".concat(attribute.name, "\" on <").concat(el.tagName.toLowerCase(), ">."), "".concat(allowedAttributes.length ? "Allowed attributes are: ".concat(allowedAttributes.join(', ')) : 'To set the value, use HTML within the element.')]);
}
});
};
2020-11-24 07:16:03 +00:00
var SHOW_CLASS_TIMEOUT = 10;
2020-04-01 22:52:43 +00:00
/**
* Open popup, add necessary classes and styles, fix scrollbar
*
2020-11-24 07:16:03 +00:00
* @param params
2020-04-01 22:52:43 +00:00
*/
var openPopup = function openPopup(params) {
var container = getContainer();
var popup = getPopup();
2020-11-24 07:16:03 +00:00
if (typeof params.willOpen === 'function') {
params.willOpen(popup);
} else if (typeof params.onBeforeOpen === 'function') {
params.onBeforeOpen(popup); // @deprecated
}
var bodyStyles = window.getComputedStyle(document.body);
var initialBodyOverflow = bodyStyles.overflowY;
2020-04-01 22:52:43 +00:00
addClasses$1(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'
2020-11-24 07:16:03 +00:00
setTimeout(function () {
setScrollingVisibility(container, popup);
}, SHOW_CLASS_TIMEOUT);
2020-04-01 22:52:43 +00:00
if (isModal()) {
fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
setAriaHidden();
2020-04-01 22:52:43 +00:00
}
2020-04-01 22:52:43 +00:00
if (!isToast() && !globalState.previousActiveElement) {
globalState.previousActiveElement = document.activeElement;
}
2020-11-24 07:16:03 +00:00
runDidOpen(popup, params);
removeClass(container, swalClasses['no-transition']);
};
var runDidOpen = function runDidOpen(popup, params) {
if (typeof params.didOpen === 'function') {
2020-04-01 22:52:43 +00:00
setTimeout(function () {
2020-11-24 07:16:03 +00:00
return params.didOpen(popup);
2020-04-01 22:52:43 +00:00
});
2020-11-24 07:16:03 +00:00
} else if (typeof params.onOpen === 'function') {
setTimeout(function () {
return params.onOpen(popup);
}); // @deprecated
2020-04-01 22:52:43 +00:00
}
};
2020-11-24 07:16:03 +00:00
var swalOpenAnimationFinished = function swalOpenAnimationFinished(event) {
2020-04-01 22:52:43 +00:00
var popup = getPopup();
2020-04-01 22:52:43 +00:00
if (event.target !== popup) {
return;
}
2020-04-01 22:52:43 +00:00
var container = getContainer();
popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
container.style.overflowY = 'auto';
2020-11-24 07:16:03 +00:00
};
2020-04-01 22:52:43 +00:00
var setScrollingVisibility = function setScrollingVisibility(container, popup) {
if (animationEndEvent && hasCssAnimation(popup)) {
container.style.overflowY = 'hidden';
popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
} else {
container.style.overflowY = 'auto';
}
2020-04-01 22:52:43 +00:00
};
var fixScrollContainer = function fixScrollContainer(container, scrollbarPadding, initialBodyOverflow) {
2020-04-01 22:52:43 +00:00
iOSfix();
IEfix();
if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
2020-04-01 22:52:43 +00:00
fixScrollbar();
} // sweetalert2/issues/1247
2020-04-01 22:52:43 +00:00
setTimeout(function () {
container.scrollTop = 0;
});
};
var addClasses$1 = function addClasses(container, popup, params) {
2020-11-24 07:16:03 +00:00
addClass(container, params.showClass.backdrop); // the workaround with setting/unsetting opacity is needed for #2019 and 2059
popup.style.setProperty('opacity', '0', 'important');
show(popup);
setTimeout(function () {
// Animate popup right after showing it
addClass(popup, params.showClass.popup); // and remove the opacity workaround
popup.style.removeProperty('opacity');
}, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
2020-04-01 22:52:43 +00:00
addClass([document.documentElement, document.body], swalClasses.shown);
if (params.heightAuto && params.backdrop && !params.toast) {
addClass([document.documentElement, document.body], swalClasses['height-auto']);
}
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
var handleInputOptionsAndValue = function handleInputOptionsAndValue(instance, params) {
if (params.input === 'select' || params.input === 'radio') {
handleInputOptions(instance, params);
} else if (['text', 'email', 'number', 'tel', 'textarea'].indexOf(params.input) !== -1 && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
2020-04-01 22:52:43 +00:00
handleInputValue(instance, params);
}
2020-04-01 22:52:43 +00:00
};
var getInputValue = function getInputValue(instance, innerParams) {
var input = instance.getInput();
if (!input) {
return null;
}
2020-04-01 22:52:43 +00:00
switch (innerParams.input) {
case 'checkbox':
return getCheckboxValue(input);
2020-04-01 22:52:43 +00:00
case 'radio':
return getRadioValue(input);
2020-04-01 22:52:43 +00:00
case 'file':
return getFileValue(input);
2020-04-01 22:52:43 +00:00
default:
return innerParams.inputAutoTrim ? input.value.trim() : input.value;
}
};
2020-04-01 22:52:43 +00:00
var getCheckboxValue = function getCheckboxValue(input) {
return input.checked ? 1 : 0;
};
2020-04-01 22:52:43 +00:00
var getRadioValue = function getRadioValue(input) {
return input.checked ? input.value : null;
};
2020-04-01 22:52:43 +00:00
var getFileValue = function getFileValue(input) {
return input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
};
2020-04-01 22:52:43 +00:00
var handleInputOptions = function handleInputOptions(instance, params) {
var content = getContent();
2020-04-01 22:52:43 +00:00
var processInputOptions = function processInputOptions(inputOptions) {
return populateInputOptions[params.input](content, formatInputOptions(inputOptions), params);
};
if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
2021-02-23 11:22:20 +00:00
showLoading(getConfirmButton());
asPromise(params.inputOptions).then(function (inputOptions) {
2020-04-01 22:52:43 +00:00
instance.hideLoading();
processInputOptions(inputOptions);
});
} else if (_typeof(params.inputOptions) === 'object') {
processInputOptions(params.inputOptions);
} else {
error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(_typeof(params.inputOptions)));
}
};
2020-04-01 22:52:43 +00:00
var handleInputValue = function handleInputValue(instance, params) {
var input = instance.getInput();
hide(input);
asPromise(params.inputValue).then(function (inputValue) {
2020-04-01 22:52:43 +00:00
input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : "".concat(inputValue);
show(input);
input.focus();
instance.hideLoading();
})["catch"](function (err) {
error("Error in inputValue promise: ".concat(err));
input.value = '';
show(input);
input.focus();
instance.hideLoading();
});
};
2020-04-01 22:52:43 +00:00
var populateInputOptions = {
select: function select(content, inputOptions, params) {
var select = getChildByClass(content, swalClasses.select);
var renderOption = function renderOption(parent, optionLabel, optionValue) {
2020-04-01 22:52:43 +00:00
var option = document.createElement('option');
option.value = optionValue;
setInnerHtml(option, optionLabel);
2020-12-23 07:17:49 +00:00
option.selected = isSelected(optionValue, params.inputValue);
parent.appendChild(option);
};
inputOptions.forEach(function (inputOption) {
var optionValue = inputOption[0];
var optionLabel = inputOption[1]; // <optgroup> spec:
// https://www.w3.org/TR/html401/interact/forms.html#h-17.6
// "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
// check whether this is a <optgroup>
if (Array.isArray(optionLabel)) {
// if it is an array, then it is an <optgroup>
var optgroup = document.createElement('optgroup');
optgroup.label = optionValue;
optgroup.disabled = false; // not configurable for now
select.appendChild(optgroup);
optionLabel.forEach(function (o) {
return renderOption(optgroup, o[1], o[0]);
});
} else {
// case of <option>
renderOption(select, optionLabel, optionValue);
}
2020-04-01 22:52:43 +00:00
});
select.focus();
},
radio: function radio(content, inputOptions, params) {
var radio = getChildByClass(content, swalClasses.radio);
inputOptions.forEach(function (inputOption) {
var radioValue = inputOption[0];
var radioLabel = inputOption[1];
var radioInput = document.createElement('input');
var radioLabelElement = document.createElement('label');
radioInput.type = 'radio';
radioInput.name = swalClasses.radio;
radioInput.value = radioValue;
2020-12-23 07:17:49 +00:00
if (isSelected(radioValue, params.inputValue)) {
2020-04-01 22:52:43 +00:00
radioInput.checked = true;
}
2020-04-01 22:52:43 +00:00
var label = document.createElement('span');
setInnerHtml(label, radioLabel);
label.className = swalClasses.label;
radioLabelElement.appendChild(radioInput);
radioLabelElement.appendChild(label);
radio.appendChild(radioLabelElement);
});
var radios = radio.querySelectorAll('input');
2020-04-01 22:52:43 +00:00
if (radios.length) {
radios[0].focus();
}
}
};
/**
* Converts `inputOptions` into an array of `[value, label]`s
* @param inputOptions
*/
2020-04-01 22:52:43 +00:00
var formatInputOptions = function formatInputOptions(inputOptions) {
var result = [];
2020-04-01 22:52:43 +00:00
if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
inputOptions.forEach(function (value, key) {
var valueFormatted = value;
if (_typeof(valueFormatted) === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
2020-04-01 22:52:43 +00:00
});
} else {
Object.keys(inputOptions).forEach(function (key) {
var valueFormatted = inputOptions[key];
if (_typeof(valueFormatted) === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
2020-04-01 22:52:43 +00:00
});
}
2020-04-01 22:52:43 +00:00
return result;
};
2020-12-23 07:17:49 +00:00
var isSelected = function isSelected(optionValue, inputValue) {
return inputValue && inputValue.toString() === optionValue.toString();
};
2020-04-01 22:52:43 +00:00
var handleConfirmButtonClick = function handleConfirmButtonClick(instance, innerParams) {
instance.disableButtons();
2020-04-01 22:52:43 +00:00
if (innerParams.input) {
2020-11-25 09:31:52 +00:00
handleConfirmOrDenyWithInput(instance, innerParams, 'confirm');
2020-04-01 22:52:43 +00:00
} else {
confirm(instance, innerParams, true);
}
};
2020-11-25 09:31:52 +00:00
var handleDenyButtonClick = function handleDenyButtonClick(instance, innerParams) {
instance.disableButtons();
2020-11-24 07:16:03 +00:00
2020-11-25 09:31:52 +00:00
if (innerParams.returnInputValueOnDeny) {
handleConfirmOrDenyWithInput(instance, innerParams, 'deny');
} else {
deny(instance, innerParams, false);
}
2020-11-24 07:16:03 +00:00
};
2020-04-01 22:52:43 +00:00
var handleCancelButtonClick = function handleCancelButtonClick(instance, dismissWith) {
instance.disableButtons();
dismissWith(DismissReason.cancel);
};
2020-11-25 09:31:52 +00:00
var handleConfirmOrDenyWithInput = function handleConfirmOrDenyWithInput(instance, innerParams, type
/* type is either 'confirm' or 'deny' */
) {
2020-04-01 22:52:43 +00:00
var inputValue = getInputValue(instance, innerParams);
2020-04-01 22:52:43 +00:00
if (innerParams.inputValidator) {
2020-11-25 09:31:52 +00:00
handleInputValidator(instance, innerParams, inputValue);
2020-04-01 22:52:43 +00:00
} else if (!instance.getInput().checkValidity()) {
instance.enableButtons();
instance.showValidationMessage(innerParams.validationMessage);
2020-11-25 09:31:52 +00:00
} else if (type === 'deny') {
deny(instance, innerParams, inputValue);
2020-04-01 22:52:43 +00:00
} else {
confirm(instance, innerParams, inputValue);
}
};
2020-11-25 09:31:52 +00:00
var handleInputValidator = function handleInputValidator(instance, innerParams, inputValue) {
instance.disableInput();
var validationPromise = Promise.resolve().then(function () {
return asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage));
2020-11-24 07:16:03 +00:00
});
2020-11-25 09:31:52 +00:00
validationPromise.then(function (validationMessage) {
instance.enableButtons();
instance.enableInput();
if (validationMessage) {
instance.showValidationMessage(validationMessage);
} else {
confirm(instance, innerParams, inputValue);
}
});
};
var deny = function deny(instance, innerParams, value) {
2021-02-02 06:47:35 +00:00
if (innerParams.showLoaderOnDeny) {
showLoading(getDenyButton());
}
2020-11-25 09:31:52 +00:00
if (innerParams.preDeny) {
var preDenyPromise = Promise.resolve().then(function () {
return asPromise(innerParams.preDeny(value, innerParams.validationMessage));
});
preDenyPromise.then(function (preDenyValue) {
if (preDenyValue === false) {
instance.hideLoading();
} else {
instance.closePopup({
isDenied: true,
value: typeof preDenyValue === 'undefined' ? value : preDenyValue
});
}
});
} else {
instance.closePopup({
isDenied: true,
value: value
});
}
2020-11-24 07:16:03 +00:00
};
2020-04-01 22:52:43 +00:00
var succeedWith = function succeedWith(instance, value) {
instance.closePopup({
2020-11-24 07:16:03 +00:00
isConfirmed: true,
2020-04-01 22:52:43 +00:00
value: value
});
};
2020-04-01 22:52:43 +00:00
var confirm = function confirm(instance, innerParams, value) {
if (innerParams.showLoaderOnConfirm) {
showLoading(); // TODO: make showLoading an *instance* method
}
2020-04-01 22:52:43 +00:00
if (innerParams.preConfirm) {
instance.resetValidationMessage();
var preConfirmPromise = Promise.resolve().then(function () {
return asPromise(innerParams.preConfirm(value, innerParams.validationMessage));
2020-04-01 22:52:43 +00:00
});
preConfirmPromise.then(function (preConfirmValue) {
if (isVisible(getValidationMessage()) || preConfirmValue === false) {
instance.hideLoading();
} else {
succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
}
});
} else {
succeedWith(instance, value);
}
};
2020-04-01 22:52:43 +00:00
var addKeydownHandler = function addKeydownHandler(instance, globalState, innerParams, dismissWith) {
if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = false;
}
2020-04-01 22:52:43 +00:00
if (!innerParams.toast) {
globalState.keydownHandler = function (e) {
return keydownHandler(instance, e, dismissWith);
};
2020-04-01 22:52:43 +00:00
globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = true;
}
}; // Focus handling
2020-04-01 22:52:43 +00:00
var setFocus = function setFocus(innerParams, index, increment) {
var focusableElements = getFocusableElements(); // search for visible elements and select the next possible match
2020-12-23 07:17:49 +00:00
if (focusableElements.length) {
2020-04-01 22:52:43 +00:00
index = index + increment; // rollover to first item
2020-04-01 22:52:43 +00:00
if (index === focusableElements.length) {
index = 0; // go to last item
} else if (index === -1) {
index = focusableElements.length - 1;
}
2020-04-01 22:52:43 +00:00
return focusableElements[index].focus();
} // no visible focusable elements, focus the popup
2020-04-01 22:52:43 +00:00
getPopup().focus();
};
2020-11-24 07:16:03 +00:00
var arrowKeysNextButton = ['ArrowRight', 'ArrowDown', 'Right', 'Down' // IE11
];
var arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp', 'Left', 'Up' // IE11
2020-04-01 22:52:43 +00:00
];
var escKeys = ['Escape', 'Esc' // IE11
];
2020-04-01 22:52:43 +00:00
var keydownHandler = function keydownHandler(instance, e, dismissWith) {
var innerParams = privateProps.innerParams.get(instance);
2020-04-01 22:52:43 +00:00
if (innerParams.stopKeydownPropagation) {
e.stopPropagation();
} // ENTER
2020-04-01 22:52:43 +00:00
if (e.key === 'Enter') {
handleEnter(instance, e, innerParams); // TAB
} else if (e.key === 'Tab') {
handleTab(e, innerParams); // ARROWS - switch focus between buttons
2020-11-24 07:16:03 +00:00
} else if ([].concat(arrowKeysNextButton, arrowKeysPreviousButton).indexOf(e.key) !== -1) {
handleArrows(e.key); // ESC
2020-04-01 22:52:43 +00:00
} else if (escKeys.indexOf(e.key) !== -1) {
handleEsc(e, innerParams, dismissWith);
}
};
2020-04-01 22:52:43 +00:00
var handleEnter = function handleEnter(instance, e, innerParams) {
// #720 #721
if (e.isComposing) {
return;
}
2020-04-01 22:52:43 +00:00
if (e.target && instance.getInput() && e.target.outerHTML === instance.getInput().outerHTML) {
if (['textarea', 'file'].indexOf(innerParams.input) !== -1) {
return; // do not submit
}
2020-04-01 22:52:43 +00:00
clickConfirm();
e.preventDefault();
}
};
2020-04-01 22:52:43 +00:00
var handleTab = function handleTab(e, innerParams) {
var targetElement = e.target;
var focusableElements = getFocusableElements();
var btnIndex = -1;
2020-04-01 22:52:43 +00:00
for (var i = 0; i < focusableElements.length; i++) {
if (targetElement === focusableElements[i]) {
btnIndex = i;
break;
}
}
2020-04-01 22:52:43 +00:00
if (!e.shiftKey) {
// Cycle to the next button
setFocus(innerParams, btnIndex, 1);
} else {
// Cycle to the prev button
setFocus(innerParams, btnIndex, -1);
}
2020-04-01 22:52:43 +00:00
e.stopPropagation();
e.preventDefault();
};
2020-11-24 07:16:03 +00:00
var handleArrows = function handleArrows(key) {
2020-04-01 22:52:43 +00:00
var confirmButton = getConfirmButton();
2020-11-24 07:16:03 +00:00
var denyButton = getDenyButton();
var cancelButton = getCancelButton();
2020-11-24 07:16:03 +00:00
if (!([confirmButton, denyButton, cancelButton].indexOf(document.activeElement) !== -1)) {
return;
}
var sibling = arrowKeysNextButton.indexOf(key) !== -1 ? 'nextElementSibling' : 'previousElementSibling';
var buttonToFocus = document.activeElement[sibling];
if (buttonToFocus) {
buttonToFocus.focus();
2020-04-01 22:52:43 +00:00
}
};
2020-04-01 22:52:43 +00:00
var handleEsc = function handleEsc(e, innerParams, dismissWith) {
if (callIfFunction(innerParams.allowEscapeKey)) {
e.preventDefault();
dismissWith(DismissReason.esc);
}
};
2020-04-01 22:52:43 +00:00
var handlePopupClick = function handlePopupClick(instance, domCache, dismissWith) {
var innerParams = privateProps.innerParams.get(instance);
2020-04-01 22:52:43 +00:00
if (innerParams.toast) {
handleToastClick(instance, domCache, dismissWith);
} else {
// Ignore click events that had mousedown on the popup but mouseup on the container
// This can happen when the user drags a slider
handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup
2020-04-01 22:52:43 +00:00
handleContainerMousedown(domCache);
handleModalClick(instance, domCache, dismissWith);
}
};
2020-04-01 22:52:43 +00:00
var handleToastClick = function handleToastClick(instance, domCache, dismissWith) {
// Closing toast by internal click
domCache.popup.onclick = function () {
var innerParams = privateProps.innerParams.get(instance);
2020-12-30 07:42:58 +00:00
if (innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton || innerParams.timer || innerParams.input) {
2020-04-01 22:52:43 +00:00
return;
}
2020-04-01 22:52:43 +00:00
dismissWith(DismissReason.close);
};
};
2020-04-01 22:52:43 +00:00
var ignoreOutsideClick = false;
2020-04-01 22:52:43 +00:00
var handleModalMousedown = function handleModalMousedown(domCache) {
domCache.popup.onmousedown = function () {
domCache.container.onmouseup = function (e) {
domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't
// have any other direct children aside of the popup
2020-04-01 22:52:43 +00:00
if (e.target === domCache.container) {
ignoreOutsideClick = true;
}
};
};
};
2020-04-01 22:52:43 +00:00
var handleContainerMousedown = function handleContainerMousedown(domCache) {
domCache.container.onmousedown = function () {
domCache.popup.onmouseup = function (e) {
domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup
2020-04-01 22:52:43 +00:00
if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
ignoreOutsideClick = true;
}
};
};
};
2020-04-01 22:52:43 +00:00
var handleModalClick = function handleModalClick(instance, domCache, dismissWith) {
domCache.container.onclick = function (e) {
var innerParams = privateProps.innerParams.get(instance);
2020-04-01 22:52:43 +00:00
if (ignoreOutsideClick) {
ignoreOutsideClick = false;
return;
}
2020-04-01 22:52:43 +00:00
if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
dismissWith(DismissReason.backdrop);
}
};
};
2020-04-01 22:52:43 +00:00
function _main(userParams) {
2020-12-23 07:17:49 +00:00
var mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
showWarningsForParams(_extends({}, mixinParams, userParams));
2020-04-01 22:52:43 +00:00
if (globalState.currentInstance) {
globalState.currentInstance._destroy();
}
2020-04-01 22:52:43 +00:00
globalState.currentInstance = this;
2020-12-23 07:17:49 +00:00
var innerParams = prepareParams(userParams, mixinParams);
2020-04-01 22:52:43 +00:00
setParameters(innerParams);
Object.freeze(innerParams); // clear the previous timer
2020-04-01 22:52:43 +00:00
if (globalState.timeout) {
globalState.timeout.stop();
delete globalState.timeout;
} // clear the restore focus timeout
2020-04-01 22:52:43 +00:00
clearTimeout(globalState.restoreFocusTimeout);
var domCache = populateDomCache(this);
render(this, innerParams);
privateProps.innerParams.set(this, innerParams);
return swalPromise(this, domCache, innerParams);
}
2020-12-23 07:17:49 +00:00
var prepareParams = function prepareParams(userParams, mixinParams) {
var templateParams = getTemplateParams(userParams);
var showClass = _extends({}, defaultParams.showClass, mixinParams.showClass, templateParams.showClass, userParams.showClass);
var hideClass = _extends({}, defaultParams.hideClass, mixinParams.hideClass, templateParams.hideClass, userParams.hideClass);
2020-12-23 07:17:49 +00:00
var params = _extends({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
2020-04-01 22:52:43 +00:00
params.showClass = showClass;
params.hideClass = hideClass; // @deprecated
2020-04-01 22:52:43 +00:00
if (userParams.animation === false) {
params.showClass = {
popup: 'swal2-noanimation',
backdrop: 'swal2-noanimation'
};
params.hideClass = {};
}
2020-04-01 22:52:43 +00:00
return params;
};
2020-04-01 22:52:43 +00:00
var swalPromise = function swalPromise(instance, domCache, innerParams) {
return new Promise(function (resolve) {
// functions to handle all closings/dismissals
var dismissWith = function dismissWith(dismiss) {
instance.closePopup({
2020-11-24 07:16:03 +00:00
isDismissed: true,
2020-04-01 22:52:43 +00:00
dismiss: dismiss
});
};
privateMethods.swalPromiseResolve.set(instance, resolve);
domCache.confirmButton.onclick = function () {
return handleConfirmButtonClick(instance, innerParams);
};
2020-11-24 07:16:03 +00:00
domCache.denyButton.onclick = function () {
2020-11-25 09:31:52 +00:00
return handleDenyButtonClick(instance, innerParams);
2020-11-24 07:16:03 +00:00
};
2020-04-01 22:52:43 +00:00
domCache.cancelButton.onclick = function () {
return handleCancelButtonClick(instance, dismissWith);
};
domCache.closeButton.onclick = function () {
return dismissWith(DismissReason.close);
};
2020-04-01 22:52:43 +00:00
handlePopupClick(instance, domCache, dismissWith);
addKeydownHandler(instance, globalState, innerParams, dismissWith);
2020-04-01 22:52:43 +00:00
if (innerParams.toast && (innerParams.input || innerParams.footer || innerParams.showCloseButton)) {
addClass(document.body, swalClasses['toast-column']);
} else {
removeClass(document.body, swalClasses['toast-column']);
}
2020-04-01 22:52:43 +00:00
handleInputOptionsAndValue(instance, innerParams);
openPopup(innerParams);
setupTimer(globalState, innerParams, dismissWith);
initFocus(domCache, innerParams); // Scroll container to top on open (#1247, #1946)
2020-04-01 22:52:43 +00:00
setTimeout(function () {
domCache.container.scrollTop = 0;
});
2020-04-01 22:52:43 +00:00
});
};
2020-04-01 22:52:43 +00:00
var populateDomCache = function populateDomCache(instance) {
var domCache = {
popup: getPopup(),
container: getContainer(),
content: getContent(),
actions: getActions(),
confirmButton: getConfirmButton(),
2020-11-24 07:16:03 +00:00
denyButton: getDenyButton(),
2020-04-01 22:52:43 +00:00
cancelButton: getCancelButton(),
2020-11-24 07:16:03 +00:00
loader: getLoader(),
2020-04-01 22:52:43 +00:00
closeButton: getCloseButton(),
validationMessage: getValidationMessage(),
progressSteps: getProgressSteps()
};
privateProps.domCache.set(instance, domCache);
return domCache;
};
2020-04-01 22:52:43 +00:00
var setupTimer = function setupTimer(globalState$$1, innerParams, dismissWith) {
var timerProgressBar = getTimerProgressBar();
hide(timerProgressBar);
if (innerParams.timer) {
globalState$$1.timeout = new Timer(function () {
dismissWith('timer');
delete globalState$$1.timeout;
}, innerParams.timer);
if (innerParams.timerProgressBar) {
show(timerProgressBar);
setTimeout(function () {
2021-01-11 13:35:52 +00:00
if (globalState$$1.timeout && globalState$$1.timeout.running) {
// timer can be already stopped or unset at this point
2020-04-01 22:52:43 +00:00
animateTimerProgressBar(innerParams.timer);
}
});
}
2020-04-01 22:52:43 +00:00
}
};
2020-04-01 22:52:43 +00:00
var initFocus = function initFocus(domCache, innerParams) {
if (innerParams.toast) {
return;
}
2020-04-01 22:52:43 +00:00
if (!callIfFunction(innerParams.allowEnterKey)) {
return blurActiveElement();
}
2020-11-24 07:16:03 +00:00
if (!focusButton(domCache, innerParams)) {
setFocus(innerParams, -1, 1);
}
};
var focusButton = function focusButton(domCache, innerParams) {
if (innerParams.focusDeny && isVisible(domCache.denyButton)) {
domCache.denyButton.focus();
return true;
}
2020-04-01 22:52:43 +00:00
if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {
2020-11-24 07:16:03 +00:00
domCache.cancelButton.focus();
return true;
2020-04-01 22:52:43 +00:00
}
2020-04-01 22:52:43 +00:00
if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {
2020-11-24 07:16:03 +00:00
domCache.confirmButton.focus();
return true;
2020-04-01 22:52:43 +00:00
}
2020-11-24 07:16:03 +00:00
return false;
2020-04-01 22:52:43 +00:00
};
2020-04-01 22:52:43 +00:00
var blurActiveElement = function blurActiveElement() {
if (document.activeElement && typeof document.activeElement.blur === 'function') {
document.activeElement.blur();
}
};
2020-04-01 22:52:43 +00:00
/**
* Updates popup parameters.
*/
2020-04-01 22:52:43 +00:00
function update(params) {
var popup = getPopup();
var innerParams = privateProps.innerParams.get(this);
2020-04-01 22:52:43 +00:00
if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
return warn("You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.");
}
2020-04-01 22:52:43 +00:00
var validUpdatableParams = {}; // assign valid params from `params` to `defaults`
2020-04-01 22:52:43 +00:00
Object.keys(params).forEach(function (param) {
if (Swal.isUpdatableParameter(param)) {
validUpdatableParams[param] = params[param];
} else {
2020-11-24 07:16:03 +00:00
warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md"));
2020-04-01 22:52:43 +00:00
}
});
2020-04-01 22:52:43 +00:00
var updatedParams = _extends({}, innerParams, validUpdatableParams);
2020-04-01 22:52:43 +00:00
render(this, updatedParams);
privateProps.innerParams.set(this, updatedParams);
Object.defineProperties(this, {
params: {
value: _extends({}, this.params, params),
writable: false,
enumerable: true
}
});
}
2020-04-01 22:52:43 +00:00
function _destroy() {
var domCache = privateProps.domCache.get(this);
var innerParams = privateProps.innerParams.get(this);
2020-04-01 22:52:43 +00:00
if (!innerParams) {
return; // This instance has already been destroyed
} // Check if there is another Swal closing
2020-04-01 22:52:43 +00:00
if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
} // Check if there is a swal disposal defer timer
2020-04-01 22:52:43 +00:00
if (globalState.deferDisposalTimer) {
clearTimeout(globalState.deferDisposalTimer);
delete globalState.deferDisposalTimer;
}
2020-11-24 07:16:03 +00:00
runDidDestroy(innerParams);
2020-04-01 22:52:43 +00:00
disposeSwal(this);
}
2020-11-24 07:16:03 +00:00
var runDidDestroy = function runDidDestroy(innerParams) {
if (typeof innerParams.didDestroy === 'function') {
innerParams.didDestroy();
} else if (typeof innerParams.onDestroy === 'function') {
innerParams.onDestroy(); // @deprecated
}
};
2020-04-01 22:52:43 +00:00
var disposeSwal = function disposeSwal(instance) {
// Unset this.params so GC will dispose it (#1569)
delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)
2020-04-01 22:52:43 +00:00
delete globalState.keydownHandler;
delete globalState.keydownTarget; // Unset WeakMaps so GC will be able to dispose them (#1569)
2020-04-01 22:52:43 +00:00
unsetWeakMaps(privateProps);
unsetWeakMaps(privateMethods);
};
2020-04-01 22:52:43 +00:00
var unsetWeakMaps = function unsetWeakMaps(obj) {
for (var i in obj) {
obj[i] = new WeakMap();
}
};
2020-04-01 22:52:43 +00:00
var instanceMethods = /*#__PURE__*/Object.freeze({
hideLoading: hideLoading,
disableLoading: hideLoading,
getInput: getInput$1,
close: close,
closePopup: close,
closeModal: close,
closeToast: close,
enableButtons: enableButtons,
disableButtons: disableButtons,
enableInput: enableInput,
disableInput: disableInput,
showValidationMessage: showValidationMessage,
resetValidationMessage: resetValidationMessage$1,
getProgressSteps: getProgressSteps$1,
_main: _main,
update: update,
_destroy: _destroy
});
var currentInstance;
var SweetAlert = /*#__PURE__*/function () {
function SweetAlert() {
_classCallCheck(this, SweetAlert);
// Prevent run in Node env
if (typeof window === 'undefined') {
return;
} // Check for the existence of Promise
if (typeof Promise === 'undefined') {
error('This package requires a Promise library, please include a shim to enable it in this browser (See: https://github.com/sweetalert2/sweetalert2/wiki/Migration-from-SweetAlert-to-SweetAlert2#1-ie-support)');
}
currentInstance = this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
2020-04-01 22:52:43 +00:00
}
var outerParams = Object.freeze(this.constructor.argsToParams(args));
Object.defineProperties(this, {
params: {
value: outerParams,
writable: false,
enumerable: true,
configurable: true
}
});
var promise = this._main(this.params);
privateProps.promise.set(this, promise);
} // `catch` cannot be the name of a module export, so we define our thenable methods here instead
_createClass(SweetAlert, [{
key: "then",
value: function then(onFulfilled) {
var promise = privateProps.promise.get(this);
return promise.then(onFulfilled);
}
}, {
key: "finally",
value: function _finally(onFinally) {
var promise = privateProps.promise.get(this);
return promise["finally"](onFinally);
}
}]);
return SweetAlert;
}(); // Assign instance methods from src/instanceMethods/*.js to prototype
2020-04-01 22:52:43 +00:00
_extends(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor
2020-04-01 22:52:43 +00:00
_extends(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility
2020-04-01 22:52:43 +00:00
Object.keys(instanceMethods).forEach(function (key) {
SweetAlert[key] = function () {
if (currentInstance) {
var _currentInstance;
2020-04-01 22:52:43 +00:00
return (_currentInstance = currentInstance)[key].apply(_currentInstance, arguments);
}
};
});
SweetAlert.DismissReason = DismissReason;
2021-02-23 11:22:20 +00:00
SweetAlert.version = '10.15.5';
2020-04-01 22:52:43 +00:00
var Swal = SweetAlert;
Swal["default"] = Swal;
2020-04-01 22:52:43 +00:00
return Swal;
2020-04-01 22:52:43 +00:00
}));
if (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}