WELearn网课助手
// ==UserScript==
// @name WELearn网课助手
// @namespace http://tampermonkey.net/
// @description 显示WE Learn随行课堂题目答案;支持班级测试;自动答题;刷时长;开放自定义参数
// @version 0.8.2
// @author SSmJaE
// @license GPL-3.0
// @compatible Chrome
// @match https://course.sflep.com/*
// @match https://centercourseware.sflep.com/*
// @run-at document-end
// @connect localhost
// @connect 47.97.90.127
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @require https://cdn.jsdelivr.net/npm/vue/dist/vue.js
// ==/UserScript==
/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ function webpackJsonpCallback(data) {
/******/ var chunkIds = data[0];
/******/ var moreModules = data[1];
/******/
/******/
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, resolves = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ resolves.push(installedChunks[chunkId][0]);
/******/ }
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(data);
/******/
/******/ while(resolves.length) {
/******/ resolves.shift()();
/******/ }
/******/
/******/ };
/******/
/******/
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // Promise = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ 0: 0
/******/ };
/******/
/******/
/******/
/******/ // script path function
/******/ function jsonpScriptSrc(chunkId) {
/******/ return __webpack_require__.p + "" + chunkId + ".WElearnHelper0.8.2.js"
/******/ }
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // The chunk loading function for additional chunks
/******/ // Since all referenced chunks are already included
/******/ // in this file, this function is empty here.
/******/ __webpack_require__.e = function requireEnsure() {
/******/ return Promise.resolve();
/******/ };
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
/******/
/******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
/******/ jsonpArray.push = webpackJsonpCallback;
/******/ jsonpArray = jsonpArray.slice();
/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
/******/ var parentJsonpFunction = oldJsonpFunction;
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 32);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Global; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BASE_URL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return DEBUG_MODE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return QUERY_INTERVAL; });
var Global = {
messages: [],
USER_SETTINGS: {},
collapse: true,
showExamQueryButton: false
}; // *--------------------以下为常量
var BASE_URL;
var DEBUG_MODE;
if (false) {} else {
// BASE_URL = "http://localhost:8000/api/welearn";
BASE_URL = "http://47.97.90.127/api/welearn";
DEBUG_MODE = false;
}
var VERSION = "0.8.2";
var QUERY_INTERVAL = 3000; //单位ms
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(20);
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return sleep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return makeDraggable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return requestErrorHandler; });
/* unused harmony export appendToSideBar */
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _global__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0);
function sleep(ms) {
return new Promise(function (resolve) {
return setTimeout(resolve, ms);
});
}
function addMessage(_x) {
return _addMessage.apply(this, arguments);
}
/**实现拖动*/
function _addMessage() {
_addMessage = Object(_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(info) {
var type,
_args = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
type = _args.length > 1 && _args[1] !== undefined ? _args[1] : "normal";
if (!(type !== "hr")) {
_context.next = 4;
break;
}
if (!(info === null || info === "")) {
_context.next = 4;
break;
}
return _context.abrupt("return");
case 4:
_global__WEBPACK_IMPORTED_MODULE_2__[/* Global */ "c"].messages.push({
info: String(info),
type: type
});
if (!_global__WEBPACK_IMPORTED_MODULE_2__[/* Global */ "c"].USER_SETTINGS.autoSlide) {
_context.next = 9;
break;
}
_context.next = 8;
return sleep(10);
case 8:
//等待message渲染完成,不然不会拉到最底
document.querySelector("#container-messages").scrollBy(0, 1000);
case 9:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _addMessage.apply(this, arguments);
}
function makeDraggable(handle, container) {
function getProperty(ele, prop) {
return parseInt(window.getComputedStyle(ele)[prop]);
}
var draggable = false,
pastX,
pastY,
containerWidth,
containerHeight,
containerLeft = getProperty(container, "left"),
containerTop = getProperty(container, "top"),
windowWidth = window.innerWidth,
windowHeight = window.innerHeight;
handle.addEventListener("mousedown", function (e) {
handle.style.cursor = "grabbing";
draggable = true;
pastX = e.clientX;
pastY = e.clientY;
containerWidth = getProperty(container, "width");
containerHeight = getProperty(container, "height");
}, false);
document.addEventListener("mousemove", function (e) {
if (draggable === true) {
var currentX = e.clientX,
currentY = e.clientY,
diffX = currentX - pastX,
diffY = currentY - pastY;
var targetX = containerLeft + diffX;
var targetY = containerTop + diffY;
if (targetX <= 0) targetX = 0;
if (targetY <= 0) targetY = 0;
if (targetX >= windowWidth - containerWidth) targetX = windowWidth - containerWidth;
if (targetY >= windowHeight - containerHeight) targetY = windowHeight - containerHeight;
container.style.left = targetX + "px";
container.style.top = targetY + "px";
}
});
handle.addEventListener("mouseup", function () {
handle.style.cursor = "grab";
draggable = false;
containerLeft = getProperty(container, "left");
containerTop = getProperty(container, "top");
}, false); //防止意外未退出拖动状态
document.body.addEventListener("keydown", function (e) {
if (e.key === "Escape") {
// console.log(e);
handle.style.cursor = "grab";
draggable = false;
containerLeft = getProperty(container, "left");
containerTop = getProperty(container, "top");
}
}, false);
}
/** 通过装饰器,实现请求失败时,输出定制化的提示信息 */
function requestErrorHandler() {
var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "请求异常,稍后再试";
return function (target, propertyKey, descriptor) {
var originalMethod = descriptor.value;
descriptor.value = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var result = originalMethod.apply(this, args);
result["catch"](function (error) {
addMessage("".concat(message), "error"); // addMessage(`${error}`, "error");
});
return result;
};
return descriptor;
};
}
/**
* 注册按钮至侧边栏,class应为iconfont class
*/
function appendToSideBar(id, className, name) {
try {
if (!document.querySelector("sidebar-button-style")) {
var buttonStyle = document.createElement("style");
buttonStyle.id = "sidebar-button-style";
buttonStyle.setAttribute("type", "text/css");
buttonStyle.innerHTML = "\n .courseware_sidebar_2 .sidebar-button {\n color: white;\n z-index: 100;\n font-size: 23px;\n cursor: pointer;\n position: relative;\n left: 15px;\n top: 5px;\n text-align: center; \n }\n\n .courseware_sidebar_2 .sidebar-button:hover {\n color: rgb(0,230,227);\n background: #3b3b3b 100px 100px;\n }\n \n .courseware_sidebar_2 .sidebar-button a { \n color: #494949; \n font-size: 14px; \n line-height: 20px;\n position: relative;\n left: -15px;\n }\n\n .courseware_sidebar_2 .sidebar-button:hover a {\n color: #ccc;\n }\n ";
document.body.append(buttonStyle);
}
var button = document.createElement("span");
button.id = "".concat(id);
button.className = "sidebar-button ".concat(className);
button.innerHTML = "<a>".concat(name, "</a>");
document.querySelector(".courseware_sidebar_2 ul.c_s_2 li").appendChild(button);
return button; //可以跨域添加元素,但是无法跨域操作元素
// (top.frames[0].document.querySelector(
// "container-setting-button",
// ) as HTMLElement).style.display = "none";
//todo 还是说,必须要分成两步?不然解释不了为什么上方可以修改style
} catch (error) {
console.log(error);
}
}
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _asyncToGenerator; });
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join('');
}; // import a list of modules into the list
// eslint-disable-next-line func-names
list.i = function (modules, mediaQuery, dedupe) {
if (typeof modules === 'string') {
// eslint-disable-next-line no-param-reassign
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
if (dedupe) {
for (var i = 0; i < this.length; i++) {
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for (var _i = 0; _i < modules.length; _i++) {
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
// eslint-disable-next-line no-continue
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return request; });
/* harmony import */ var _babel_runtime_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14);
/* harmony import */ var _src_global__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
function generateFinalUrl(url) {
return url.startsWith("/") ? _src_global__WEBPACK_IMPORTED_MODULE_1__[/* BASE_URL */ "a"] + url : url;
} //todo promise内部类型应该怎么定义
function request(url) {
var init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
method: "GET",
headers: {},
body: ""
};
var body = Object(_babel_runtime_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(init.body) === "object" ? JSON.stringify(init.body) : init.body;
return new Promise(function (resolve, reject) {
GM_xmlhttpRequest({
url: generateFinalUrl(url),
method: init.method,
headers: init.headers,
data: body,
timeout: 5000,
responseType: "json",
onload: function onload(response) {
var code = response.status;
if (code >= 200 && code <= 300) resolve(response);else reject(response);
},
onabort: function onabort(response) {
return reject(response);
},
onerror: function onerror(response) {
return reject(response);
},
ontimeout: function ontimeout(response) {
return reject(response);
}
});
});
} // ['delete', 'get', 'head', 'options', 'post', 'put', 'patch'].forEach(method => {
// GM_fetch2.prototype[method] = (url: string, init: Init) => {
// init = { ...init, method: <METHOD>method.toUpperCase() }
// return GM_fetch.request(url, init)
// };
// })
//todo onFail,可以自定义提示信息,并提供默认提示信息默认值
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
/*!
* sweetalert2 v10.0.2
* Released under the MIT License.
*/
(function (global, factory) {
true ? module.exports = factory() :
undefined;
}(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);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
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;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_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;
};
}
return _construct.apply(null, arguments);
}
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);
}
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);
};
}
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);
}
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]);
}
}
return result;
};
/**
* Capitalize the first letter of a string
* @param str
*/
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)
* @param obj
*/
var objectValues = function objectValues(obj) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
};
/**
* Convert NodeList to Array
* @param nodeList
*/
var toArray = function toArray(nodeList) {
return Array.prototype.slice.call(nodeList);
};
/**
* Standardise console warnings
* @param message
*/
var warn = function warn(message) {
console.warn("".concat(consolePrefix, " ").concat(message));
};
/**
* Standardise console errors
* @param message
*/
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);
}
};
/**
* Show a one-time console warning about deprecated params/methods
*/
var warnAboutDepreation = function warnAboutDepreation(deprecatedParam, useInstead) {
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);
};
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'
});
var isJqueryElement = function isJqueryElement(elem) {
return _typeof(elem) === 'object' && elem.jquery;
};
var isElement = function isElement(elem) {
return elem instanceof Element || isJqueryElement(elem);
};
var argsToParams = function argsToParams(args) {
var params = {};
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;
};
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', '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']);
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 getIcons = function getIcons() {
var popup = getPopup();
return toArray(popup.querySelectorAll(".".concat(swalClasses.icon)));
};
var getIcon = function getIcon() {
var visibleIcon = getIcons().filter(function (icon) {
return isVisible(icon);
});
return visibleIcon.length ? visibleIcon[0] : null;
};
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));
};
var getDenyButton = function getDenyButton() {
return elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny));
};
var getLoader = function getLoader() {
return elementBySelector(".".concat(swalClasses.loader));
};
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;
};
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);
}
});
};
var applyCustomClass = function applyCustomClass(elem, params, className) {
removeCustomClasses(elem, params);
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]), "\""));
}
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"));
case 'radio':
return content.querySelector(".".concat(swalClasses.radio, " input:checked")) || content.querySelector(".".concat(swalClasses.radio, " input:first-child"));
case 'range':
return content.querySelector(".".concat(swalClasses.range, " input"));
default:
return getChildByClass(content, swalClasses.input);
}
}
var focusInput = function focusInput(input) {
input.focus(); // place cursor at end of text in text input
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;
}
if (typeof classList === 'string') {
classList = classList.split(/\s+/).filter(Boolean);
}
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) {
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.opacity = '';
elem.style.display = display;
};
var hide = function hide(elem) {
elem.style.opacity = '';
elem.style.display = 'none';
};
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));
};
/* istanbul ignore next */
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%';
}
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';
};
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, " ").concat(iconTypes.error, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.question, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.warning, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.info, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.success, "\"></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, '');
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;
};
range.onchange = function (e) {
resetValidationMessage(e);
range.nextSibling.value = range.value;
};
};
var getTarget = function getTarget(target) {
return typeof target === 'string' ? document.querySelector(target) : target;
};
var setupAccessibility = function setupAccessibility(params) {
var popup = getPopup();
popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
if (!params.toast) {
popup.setAttribute('aria-modal', 'true');
}
};
var setupRTL = function setupRTL(targetElement) {
if (window.getComputedStyle(targetElement).direction === 'rtl') {
addClass(getContainer(), swalClasses.rtl);
}
};
/*
* Add modal + backdrop to DOM
*/
var init = function init(params) {
// Clean up the old popup container if it exists
var oldContainerExisted = resetOldContainer();
/* istanbul ignore if */
if (isNodeEnv()) {
error('SweetAlert2 requires document to initialize');
return;
}
var container = document.createElement('div');
container.className = swalClasses.container;
if (oldContainerExisted) {
addClass(container, swalClasses['no-transition']);
}
setInnerHtml(container, sweetHTML);
var targetElement = getTarget(params.target);
targetElement.appendChild(container);
setupAccessibility(params);
setupRTL(targetElement);
addInputChangeListeners();
};
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);
}
};
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());
}
};
var handleJqueryElem = function handleJqueryElem(target, elem) {
target.textContent = '';
if (0 in elem) {
for (var i = 0; (i in elem); i++) {
target.appendChild(elem[i].cloneNode(true));
}
} else {
target.appendChild(elem.cloneNode(true));
}
};
var animationEndEvent = function () {
// Prevent run in Node env
/* istanbul ignore if */
if (isNodeEnv()) {
return false;
}
var testEl = document.createElement('div');
var transEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
OAnimation: 'oAnimationEnd oanimationend',
animation: 'animationend'
};
for (var i in transEndEventNames) {
if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
return transEndEventNames[i];
}
}
return false;
}();
// https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
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;
};
var renderActions = function renderActions(instance, params) {
var actions = getActions();
var loader = getLoader();
var confirmButton = getConfirmButton();
var denyButton = getDenyButton();
var cancelButton = getCancelButton(); // Actions (buttons) wrapper
if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
hide(actions);
} // Custom class
applyCustomClass(actions, params, 'actions'); // Render buttons
renderButton(confirmButton, 'confirm', params);
renderButton(denyButton, 'deny', params);
renderButton(cancelButton, 'cancel', params); // Loader
loader.innerHTML = params.loaderHtml;
if (params.buttonsStyling) {
handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
} else {
removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
}
if (params.reverseButtons) {
actions.insertBefore(cancelButton, loader);
actions.insertBefore(denyButton, loader);
actions.insertBefore(confirmButton, loader);
}
};
function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors
if (params.confirmButtonColor) {
confirmButton.style.backgroundColor = params.confirmButtonColor;
}
if (params.denyButtonColor) {
denyButton.style.backgroundColor = params.denyButtonColor;
}
if (params.cancelButtonColor) {
cancelButton.style.backgroundColor = params.cancelButtonColor;
} // Loading state
if (!isLoading()) {
var confirmButtonBackgroundColor = window.getComputedStyle(confirmButton).getPropertyValue('background-color');
confirmButton.style.borderLeftColor = confirmButtonBackgroundColor;
confirmButton.style.borderRightColor = confirmButtonBackgroundColor;
}
}
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")]);
}
function handleBackdropParam(container, backdrop) {
if (typeof backdrop === 'string') {
container.style.background = backdrop;
} else if (!backdrop) {
addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
}
}
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);
}
}
function handleGrowParam(container, grow) {
if (grow && typeof grow === 'string') {
var growClass = "grow-".concat(grow);
if (growClass in swalClasses) {
addClass(container, swalClasses[growClass]);
}
}
}
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;
}
};
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), "\""));
}
setInputPlaceholder(input, params);
input.type = params.input;
return input;
};
renderInputType.file = function (input, params) {
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;
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);
}
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);
if ('MutationObserver' in window) {
// #1699
var initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
var popupPadding = parseInt(window.getComputedStyle(getPopup()).paddingLeft) + parseInt(window.getComputedStyle(getPopup()).paddingRight);
var outputsize = function outputsize() {
var contentWidth = textarea.offsetWidth + popupPadding;
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) {
var content = getContent().querySelector("#".concat(swalClasses.content)); // Content as HTML
if (params.html) {
parseHtmlToContainer(params.html, content);
show(content, 'block'); // Content as plain text
} else if (params.text) {
content.textContent = params.text;
show(content, 'block'); // No content
} else {
hide(content);
}
renderInput(instance, params); // Custom class
applyCustomClass(getContent(), params, 'content');
};
var renderFooter = function renderFooter(instance, params) {
var footer = getFooter();
toggle(footer, params.footer);
if (params.footer) {
parseHtmlToContainer(params.footer, footer);
} // Custom class
applyCustomClass(footer, params, 'footer');
};
var renderCloseButton = function renderCloseButton(instance, params) {
var closeButton = getCloseButton();
setInnerHtml(closeButton, params.closeButtonHtml); // Custom class
applyCustomClass(closeButton, params, 'closeButton');
toggle(closeButton, params.showCloseButton);
closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
};
var renderIcon = function renderIcon(instance, params) {
var innerParams = privateProps.innerParams.get(instance); // if the give icon already rendered, apply the custom class without re-rendering the icon
if (innerParams && params.icon === innerParams.icon && getIcon()) {
applyCustomClass(getIcon(), params, 'icon');
return;
}
hideAllIcons();
if (!params.icon) {
return;
}
if (Object.keys(iconTypes).indexOf(params.icon) !== -1) {
var icon = elementBySelector(".".concat(swalClasses.icon, ".").concat(iconTypes[params.icon]));
show(icon); // Custom or default content
setContent(icon, params);
adjustSuccessIconBackgoundColor(); // Custom class
applyCustomClass(icon, params, 'icon'); // Animate icon
addClass(icon, params.showClass.icon);
} else {
error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\""));
}
};
var hideAllIcons = function hideAllIcons() {
var icons = getIcons();
for (var i = 0; i < icons.length; i++) {
hide(icons[i]);
}
}; // Adjust success icon background color to match the popup background color
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');
for (var i = 0; i < successIconParts.length; i++) {
successIconParts[i].style.backgroundColor = popupBackgroundColor;
}
};
var setContent = function setContent(icon, params) {
icon.textContent = '';
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'
};