sweetalert2.js 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910
  1. /*!
  2. * sweetalert2 v8.17.6
  3. * Released under the MIT License.
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  7. typeof define === 'function' && define.amd ? define(factory) :
  8. (global.Sweetalert2 = factory());
  9. }(this, (function () { 'use strict';
  10. function _typeof(obj) {
  11. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  12. _typeof = function (obj) {
  13. return typeof obj;
  14. };
  15. } else {
  16. _typeof = function (obj) {
  17. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  18. };
  19. }
  20. return _typeof(obj);
  21. }
  22. function _classCallCheck(instance, Constructor) {
  23. if (!(instance instanceof Constructor)) {
  24. throw new TypeError("Cannot call a class as a function");
  25. }
  26. }
  27. function _defineProperties(target, props) {
  28. for (var i = 0; i < props.length; i++) {
  29. var descriptor = props[i];
  30. descriptor.enumerable = descriptor.enumerable || false;
  31. descriptor.configurable = true;
  32. if ("value" in descriptor) descriptor.writable = true;
  33. Object.defineProperty(target, descriptor.key, descriptor);
  34. }
  35. }
  36. function _createClass(Constructor, protoProps, staticProps) {
  37. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  38. if (staticProps) _defineProperties(Constructor, staticProps);
  39. return Constructor;
  40. }
  41. function _extends() {
  42. _extends = Object.assign || function (target) {
  43. for (var i = 1; i < arguments.length; i++) {
  44. var source = arguments[i];
  45. for (var key in source) {
  46. if (Object.prototype.hasOwnProperty.call(source, key)) {
  47. target[key] = source[key];
  48. }
  49. }
  50. }
  51. return target;
  52. };
  53. return _extends.apply(this, arguments);
  54. }
  55. function _inherits(subClass, superClass) {
  56. if (typeof superClass !== "function" && superClass !== null) {
  57. throw new TypeError("Super expression must either be null or a function");
  58. }
  59. subClass.prototype = Object.create(superClass && superClass.prototype, {
  60. constructor: {
  61. value: subClass,
  62. writable: true,
  63. configurable: true
  64. }
  65. });
  66. if (superClass) _setPrototypeOf(subClass, superClass);
  67. }
  68. function _getPrototypeOf(o) {
  69. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  70. return o.__proto__ || Object.getPrototypeOf(o);
  71. };
  72. return _getPrototypeOf(o);
  73. }
  74. function _setPrototypeOf(o, p) {
  75. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  76. o.__proto__ = p;
  77. return o;
  78. };
  79. return _setPrototypeOf(o, p);
  80. }
  81. function isNativeReflectConstruct() {
  82. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  83. if (Reflect.construct.sham) return false;
  84. if (typeof Proxy === "function") return true;
  85. try {
  86. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  87. return true;
  88. } catch (e) {
  89. return false;
  90. }
  91. }
  92. function _construct(Parent, args, Class) {
  93. if (isNativeReflectConstruct()) {
  94. _construct = Reflect.construct;
  95. } else {
  96. _construct = function _construct(Parent, args, Class) {
  97. var a = [null];
  98. a.push.apply(a, args);
  99. var Constructor = Function.bind.apply(Parent, a);
  100. var instance = new Constructor();
  101. if (Class) _setPrototypeOf(instance, Class.prototype);
  102. return instance;
  103. };
  104. }
  105. return _construct.apply(null, arguments);
  106. }
  107. function _assertThisInitialized(self) {
  108. if (self === void 0) {
  109. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  110. }
  111. return self;
  112. }
  113. function _possibleConstructorReturn(self, call) {
  114. if (call && (typeof call === "object" || typeof call === "function")) {
  115. return call;
  116. }
  117. return _assertThisInitialized(self);
  118. }
  119. function _superPropBase(object, property) {
  120. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  121. object = _getPrototypeOf(object);
  122. if (object === null) break;
  123. }
  124. return object;
  125. }
  126. function _get(target, property, receiver) {
  127. if (typeof Reflect !== "undefined" && Reflect.get) {
  128. _get = Reflect.get;
  129. } else {
  130. _get = function _get(target, property, receiver) {
  131. var base = _superPropBase(target, property);
  132. if (!base) return;
  133. var desc = Object.getOwnPropertyDescriptor(base, property);
  134. if (desc.get) {
  135. return desc.get.call(receiver);
  136. }
  137. return desc.value;
  138. };
  139. }
  140. return _get(target, property, receiver || target);
  141. }
  142. var consolePrefix = 'SweetAlert2:';
  143. /**
  144. * Filter the unique values into a new array
  145. * @param arr
  146. */
  147. var uniqueArray = function uniqueArray(arr) {
  148. var result = [];
  149. for (var i = 0; i < arr.length; i++) {
  150. if (result.indexOf(arr[i]) === -1) {
  151. result.push(arr[i]);
  152. }
  153. }
  154. return result;
  155. };
  156. /**
  157. * Returns the array ob object values (Object.values isn't supported in IE11)
  158. * @param obj
  159. */
  160. var objectValues = function objectValues(obj) {
  161. return Object.keys(obj).map(function (key) {
  162. return obj[key];
  163. });
  164. };
  165. /**
  166. * Convert NodeList to Array
  167. * @param nodeList
  168. */
  169. var toArray = function toArray(nodeList) {
  170. return Array.prototype.slice.call(nodeList);
  171. };
  172. /**
  173. * Standardise console warnings
  174. * @param message
  175. */
  176. var warn = function warn(message) {
  177. console.warn("".concat(consolePrefix, " ").concat(message));
  178. };
  179. /**
  180. * Standardise console errors
  181. * @param message
  182. */
  183. var error = function error(message) {
  184. console.error("".concat(consolePrefix, " ").concat(message));
  185. };
  186. /**
  187. * Private global state for `warnOnce`
  188. * @type {Array}
  189. * @private
  190. */
  191. var previousWarnOnceMessages = [];
  192. /**
  193. * Show a console warning, but only if it hasn't already been shown
  194. * @param message
  195. */
  196. var warnOnce = function warnOnce(message) {
  197. if (!(previousWarnOnceMessages.indexOf(message) !== -1)) {
  198. previousWarnOnceMessages.push(message);
  199. warn(message);
  200. }
  201. };
  202. /**
  203. * Show a one-time console warning about deprecated params/methods
  204. */
  205. var warnAboutDepreation = function warnAboutDepreation(deprecatedParam, useInstead) {
  206. warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead."));
  207. };
  208. /**
  209. * If `arg` is a function, call it (with no arguments or context) and return the result.
  210. * Otherwise, just pass the value through
  211. * @param arg
  212. */
  213. var callIfFunction = function callIfFunction(arg) {
  214. return typeof arg === 'function' ? arg() : arg;
  215. };
  216. var isPromise = function isPromise(arg) {
  217. return arg && Promise.resolve(arg) === arg;
  218. };
  219. var DismissReason = Object.freeze({
  220. cancel: 'cancel',
  221. backdrop: 'backdrop',
  222. close: 'close',
  223. esc: 'esc',
  224. timer: 'timer'
  225. });
  226. var argsToParams = function argsToParams(args) {
  227. var params = {};
  228. switch (_typeof(args[0])) {
  229. case 'object':
  230. _extends(params, args[0]);
  231. break;
  232. default:
  233. ['title', 'html', 'type'].forEach(function (name, index) {
  234. switch (_typeof(args[index])) {
  235. case 'string':
  236. params[name] = args[index];
  237. break;
  238. case 'undefined':
  239. break;
  240. default:
  241. error("Unexpected type of ".concat(name, "! Expected \"string\", got ").concat(_typeof(args[index])));
  242. }
  243. });
  244. }
  245. return params;
  246. };
  247. var swalPrefix = 'swal2-';
  248. var prefix = function prefix(items) {
  249. var result = {};
  250. for (var i in items) {
  251. result[items[i]] = swalPrefix + items[i];
  252. }
  253. return result;
  254. };
  255. var swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'toast', 'toast-shown', 'toast-column', 'fade', 'show', 'hide', 'noanimation', 'close', 'title', 'header', 'content', 'actions', 'confirm', 'cancel', 'footer', 'icon', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', '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']);
  256. var iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
  257. var states = {
  258. previousBodyPadding: null
  259. };
  260. var hasClass = function hasClass(elem, className) {
  261. return elem.classList.contains(className);
  262. };
  263. var removeCustomClasses = function removeCustomClasses(elem) {
  264. toArray(elem.classList).forEach(function (className) {
  265. if (!(objectValues(swalClasses).indexOf(className) !== -1) && !(objectValues(iconTypes).indexOf(className) !== -1)) {
  266. elem.classList.remove(className);
  267. }
  268. });
  269. };
  270. var applyCustomClass = function applyCustomClass(elem, customClass, className) {
  271. removeCustomClasses(elem);
  272. if (customClass && customClass[className]) {
  273. if (typeof customClass[className] !== 'string' && !customClass[className].forEach) {
  274. return warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(_typeof(customClass[className]), "\""));
  275. }
  276. addClass(elem, customClass[className]);
  277. }
  278. };
  279. function getInput(content, inputType) {
  280. if (!inputType) {
  281. return null;
  282. }
  283. switch (inputType) {
  284. case 'select':
  285. case 'textarea':
  286. case 'file':
  287. return getChildByClass(content, swalClasses[inputType]);
  288. case 'checkbox':
  289. return content.querySelector(".".concat(swalClasses.checkbox, " input"));
  290. case 'radio':
  291. return content.querySelector(".".concat(swalClasses.radio, " input:checked")) || content.querySelector(".".concat(swalClasses.radio, " input:first-child"));
  292. case 'range':
  293. return content.querySelector(".".concat(swalClasses.range, " input"));
  294. default:
  295. return getChildByClass(content, swalClasses.input);
  296. }
  297. }
  298. var focusInput = function focusInput(input) {
  299. input.focus(); // place cursor at end of text in text input
  300. if (input.type !== 'file') {
  301. // http://stackoverflow.com/a/2345915
  302. var val = input.value;
  303. input.value = '';
  304. input.value = val;
  305. }
  306. };
  307. var toggleClass = function toggleClass(target, classList, condition) {
  308. if (!target || !classList) {
  309. return;
  310. }
  311. if (typeof classList === 'string') {
  312. classList = classList.split(/\s+/).filter(Boolean);
  313. }
  314. classList.forEach(function (className) {
  315. if (target.forEach) {
  316. target.forEach(function (elem) {
  317. condition ? elem.classList.add(className) : elem.classList.remove(className);
  318. });
  319. } else {
  320. condition ? target.classList.add(className) : target.classList.remove(className);
  321. }
  322. });
  323. };
  324. var addClass = function addClass(target, classList) {
  325. toggleClass(target, classList, true);
  326. };
  327. var removeClass = function removeClass(target, classList) {
  328. toggleClass(target, classList, false);
  329. };
  330. var getChildByClass = function getChildByClass(elem, className) {
  331. for (var i = 0; i < elem.childNodes.length; i++) {
  332. if (hasClass(elem.childNodes[i], className)) {
  333. return elem.childNodes[i];
  334. }
  335. }
  336. };
  337. var applyNumericalStyle = function applyNumericalStyle(elem, property, value) {
  338. if (value || parseInt(value) === 0) {
  339. elem.style[property] = typeof value === 'number' ? value + 'px' : value;
  340. } else {
  341. elem.style.removeProperty(property);
  342. }
  343. };
  344. var show = function show(elem) {
  345. var display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
  346. elem.style.opacity = '';
  347. elem.style.display = display;
  348. };
  349. var hide = function hide(elem) {
  350. elem.style.opacity = '';
  351. elem.style.display = 'none';
  352. };
  353. var toggle = function toggle(elem, condition, display) {
  354. condition ? show(elem, display) : hide(elem);
  355. }; // borrowed from jquery $(elem).is(':visible') implementation
  356. var isVisible = function isVisible(elem) {
  357. return !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
  358. };
  359. var isScrollable = function isScrollable(elem) {
  360. return !!(elem.scrollHeight > elem.clientHeight);
  361. }; // borrowed from https://stackoverflow.com/a/46352119
  362. var hasCssAnimation = function hasCssAnimation(elem) {
  363. var style = window.getComputedStyle(elem);
  364. var animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
  365. var transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
  366. return animDuration > 0 || transDuration > 0;
  367. };
  368. var contains = function contains(haystack, needle) {
  369. if (typeof haystack.contains === 'function') {
  370. return haystack.contains(needle);
  371. }
  372. };
  373. var getContainer = function getContainer() {
  374. return document.body.querySelector('.' + swalClasses.container);
  375. };
  376. var elementBySelector = function elementBySelector(selectorString) {
  377. var container = getContainer();
  378. return container ? container.querySelector(selectorString) : null;
  379. };
  380. var elementByClass = function elementByClass(className) {
  381. return elementBySelector('.' + className);
  382. };
  383. var getPopup = function getPopup() {
  384. return elementByClass(swalClasses.popup);
  385. };
  386. var getIcons = function getIcons() {
  387. var popup = getPopup();
  388. return toArray(popup.querySelectorAll('.' + swalClasses.icon));
  389. };
  390. var getIcon = function getIcon() {
  391. var visibleIcon = getIcons().filter(function (icon) {
  392. return isVisible(icon);
  393. });
  394. return visibleIcon.length ? visibleIcon[0] : null;
  395. };
  396. var getTitle = function getTitle() {
  397. return elementByClass(swalClasses.title);
  398. };
  399. var getContent = function getContent() {
  400. return elementByClass(swalClasses.content);
  401. };
  402. var getImage = function getImage() {
  403. return elementByClass(swalClasses.image);
  404. };
  405. var getProgressSteps = function getProgressSteps() {
  406. return elementByClass(swalClasses['progress-steps']);
  407. };
  408. var getValidationMessage = function getValidationMessage() {
  409. return elementByClass(swalClasses['validation-message']);
  410. };
  411. var getConfirmButton = function getConfirmButton() {
  412. return elementBySelector('.' + swalClasses.actions + ' .' + swalClasses.confirm);
  413. };
  414. var getCancelButton = function getCancelButton() {
  415. return elementBySelector('.' + swalClasses.actions + ' .' + swalClasses.cancel);
  416. };
  417. var getActions = function getActions() {
  418. return elementByClass(swalClasses.actions);
  419. };
  420. var getHeader = function getHeader() {
  421. return elementByClass(swalClasses.header);
  422. };
  423. var getFooter = function getFooter() {
  424. return elementByClass(swalClasses.footer);
  425. };
  426. var getCloseButton = function getCloseButton() {
  427. return elementByClass(swalClasses.close);
  428. }; // https://github.com/jkup/focusable/blob/master/index.js
  429. 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";
  430. var getFocusableElements = function getFocusableElements() {
  431. var focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex
  432. .sort(function (a, b) {
  433. a = parseInt(a.getAttribute('tabindex'));
  434. b = parseInt(b.getAttribute('tabindex'));
  435. if (a > b) {
  436. return 1;
  437. } else if (a < b) {
  438. return -1;
  439. }
  440. return 0;
  441. });
  442. var otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(function (el) {
  443. return el.getAttribute('tabindex') !== '-1';
  444. });
  445. return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(function (el) {
  446. return isVisible(el);
  447. });
  448. };
  449. var isModal = function isModal() {
  450. return !isToast() && !document.body.classList.contains(swalClasses['no-backdrop']);
  451. };
  452. var isToast = function isToast() {
  453. return document.body.classList.contains(swalClasses['toast-shown']);
  454. };
  455. var isLoading = function isLoading() {
  456. return getPopup().hasAttribute('data-loading');
  457. };
  458. // Detect Node env
  459. var isNodeEnv = function isNodeEnv() {
  460. return typeof window === 'undefined' || typeof document === 'undefined';
  461. };
  462. 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, "\">\n <span class=\"swal2-x-mark\"><span class=\"swal2-x-mark-line-left\"></span><span class=\"swal2-x-mark-line-right\"></span></span>\n </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, "\">\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 </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, "\"></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 <button type=\"button\" class=\"").concat(swalClasses.confirm, "\">OK</button>\n <button type=\"button\" class=\"").concat(swalClasses.cancel, "\">Cancel</button>\n </div>\n <div class=\"").concat(swalClasses.footer, "\">\n </div>\n </div>\n").replace(/(^|\n)\s*/g, '');
  463. var resetOldContainer = function resetOldContainer() {
  464. var oldContainer = getContainer();
  465. if (!oldContainer) {
  466. return;
  467. }
  468. oldContainer.parentNode.removeChild(oldContainer);
  469. removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
  470. };
  471. var oldInputVal; // IE11 workaround, see #1109 for details
  472. var resetValidationMessage = function resetValidationMessage(e) {
  473. if (Swal.isVisible() && oldInputVal !== e.target.value) {
  474. Swal.resetValidationMessage();
  475. }
  476. oldInputVal = e.target.value;
  477. };
  478. var addInputChangeListeners = function addInputChangeListeners() {
  479. var content = getContent();
  480. var input = getChildByClass(content, swalClasses.input);
  481. var file = getChildByClass(content, swalClasses.file);
  482. var range = content.querySelector(".".concat(swalClasses.range, " input"));
  483. var rangeOutput = content.querySelector(".".concat(swalClasses.range, " output"));
  484. var select = getChildByClass(content, swalClasses.select);
  485. var checkbox = content.querySelector(".".concat(swalClasses.checkbox, " input"));
  486. var textarea = getChildByClass(content, swalClasses.textarea);
  487. input.oninput = resetValidationMessage;
  488. file.onchange = resetValidationMessage;
  489. select.onchange = resetValidationMessage;
  490. checkbox.onchange = resetValidationMessage;
  491. textarea.oninput = resetValidationMessage;
  492. range.oninput = function (e) {
  493. resetValidationMessage(e);
  494. rangeOutput.value = range.value;
  495. };
  496. range.onchange = function (e) {
  497. resetValidationMessage(e);
  498. range.nextSibling.value = range.value;
  499. };
  500. };
  501. var getTarget = function getTarget(target) {
  502. return typeof target === 'string' ? document.querySelector(target) : target;
  503. };
  504. var setupAccessibility = function setupAccessibility(params) {
  505. var popup = getPopup();
  506. popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
  507. popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
  508. if (!params.toast) {
  509. popup.setAttribute('aria-modal', 'true');
  510. }
  511. };
  512. var setupRTL = function setupRTL(targetElement) {
  513. if (window.getComputedStyle(targetElement).direction === 'rtl') {
  514. addClass(getContainer(), swalClasses.rtl);
  515. }
  516. };
  517. /*
  518. * Add modal + backdrop to DOM
  519. */
  520. var init = function init(params) {
  521. // Clean up the old popup container if it exists
  522. resetOldContainer();
  523. /* istanbul ignore if */
  524. if (isNodeEnv()) {
  525. error('SweetAlert2 requires document to initialize');
  526. return;
  527. }
  528. var container = document.createElement('div');
  529. container.className = swalClasses.container;
  530. container.innerHTML = sweetHTML;
  531. var targetElement = getTarget(params.target);
  532. targetElement.appendChild(container);
  533. setupAccessibility(params);
  534. setupRTL(targetElement);
  535. addInputChangeListeners();
  536. };
  537. var parseHtmlToContainer = function parseHtmlToContainer(param, target) {
  538. // DOM element
  539. if (param instanceof HTMLElement) {
  540. target.appendChild(param); // JQuery element(s)
  541. } else if (_typeof(param) === 'object') {
  542. handleJqueryElem(target, param); // Plain string
  543. } else if (param) {
  544. target.innerHTML = param;
  545. }
  546. };
  547. var handleJqueryElem = function handleJqueryElem(target, elem) {
  548. target.innerHTML = '';
  549. if (0 in elem) {
  550. for (var i = 0; i in elem; i++) {
  551. target.appendChild(elem[i].cloneNode(true));
  552. }
  553. } else {
  554. target.appendChild(elem.cloneNode(true));
  555. }
  556. };
  557. var animationEndEvent = function () {
  558. // Prevent run in Node env
  559. /* istanbul ignore if */
  560. if (isNodeEnv()) {
  561. return false;
  562. }
  563. var testEl = document.createElement('div');
  564. var transEndEventNames = {
  565. WebkitAnimation: 'webkitAnimationEnd',
  566. OAnimation: 'oAnimationEnd oanimationend',
  567. animation: 'animationend'
  568. };
  569. for (var i in transEndEventNames) {
  570. if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
  571. return transEndEventNames[i];
  572. }
  573. }
  574. return false;
  575. }();
  576. // Measure width of scrollbar
  577. // https://github.com/twbs/bootstrap/blob/master/js/modal.js#L279-L286
  578. var measureScrollbar = function measureScrollbar() {
  579. var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
  580. if (supportsTouch) {
  581. return 0;
  582. }
  583. var scrollDiv = document.createElement('div');
  584. scrollDiv.style.width = '50px';
  585. scrollDiv.style.height = '50px';
  586. scrollDiv.style.overflow = 'scroll';
  587. document.body.appendChild(scrollDiv);
  588. var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
  589. document.body.removeChild(scrollDiv);
  590. return scrollbarWidth;
  591. };
  592. var renderActions = function renderActions(instance, params) {
  593. var actions = getActions();
  594. var confirmButton = getConfirmButton();
  595. var cancelButton = getCancelButton(); // Actions (buttons) wrapper
  596. if (!params.showConfirmButton && !params.showCancelButton) {
  597. hide(actions);
  598. } // Custom class
  599. applyCustomClass(actions, params.customClass, 'actions'); // Render confirm button
  600. renderButton(confirmButton, 'confirm', params); // render Cancel Button
  601. renderButton(cancelButton, 'cancel', params);
  602. if (params.buttonsStyling) {
  603. handleButtonsStyling(confirmButton, cancelButton, params);
  604. } else {
  605. removeClass([confirmButton, cancelButton], swalClasses.styled);
  606. confirmButton.style.backgroundColor = confirmButton.style.borderLeftColor = confirmButton.style.borderRightColor = '';
  607. cancelButton.style.backgroundColor = cancelButton.style.borderLeftColor = cancelButton.style.borderRightColor = '';
  608. }
  609. if (params.reverseButtons) {
  610. confirmButton.parentNode.insertBefore(cancelButton, confirmButton);
  611. }
  612. };
  613. function handleButtonsStyling(confirmButton, cancelButton, params) {
  614. addClass([confirmButton, cancelButton], swalClasses.styled); // Buttons background colors
  615. if (params.confirmButtonColor) {
  616. confirmButton.style.backgroundColor = params.confirmButtonColor;
  617. }
  618. if (params.cancelButtonColor) {
  619. cancelButton.style.backgroundColor = params.cancelButtonColor;
  620. } // Loading state
  621. var confirmButtonBackgroundColor = window.getComputedStyle(confirmButton).getPropertyValue('background-color');
  622. confirmButton.style.borderLeftColor = confirmButtonBackgroundColor;
  623. confirmButton.style.borderRightColor = confirmButtonBackgroundColor;
  624. }
  625. function renderButton(button, buttonType, params) {
  626. toggle(button, params['showC' + buttonType.substring(1) + 'Button'], 'inline-block');
  627. button.innerHTML = params[buttonType + 'ButtonText']; // Set caption text
  628. button.setAttribute('aria-label', params[buttonType + 'ButtonAriaLabel']); // ARIA label
  629. // Add buttons custom classes
  630. button.className = swalClasses[buttonType];
  631. applyCustomClass(button, params.customClass, buttonType + 'Button');
  632. addClass(button, params[buttonType + 'ButtonClass']);
  633. }
  634. function handleBackdropParam(container, backdrop) {
  635. if (typeof backdrop === 'string') {
  636. container.style.background = backdrop;
  637. } else if (!backdrop) {
  638. addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
  639. }
  640. }
  641. function handlePositionParam(container, position) {
  642. if (position in swalClasses) {
  643. addClass(container, swalClasses[position]);
  644. } else {
  645. warn('The "position" parameter is not valid, defaulting to "center"');
  646. addClass(container, swalClasses.center);
  647. }
  648. }
  649. function handleGrowParam(container, grow) {
  650. if (grow && typeof grow === 'string') {
  651. var growClass = 'grow-' + grow;
  652. if (growClass in swalClasses) {
  653. addClass(container, swalClasses[growClass]);
  654. }
  655. }
  656. }
  657. var renderContainer = function renderContainer(instance, params) {
  658. var container = getContainer();
  659. if (!container) {
  660. return;
  661. }
  662. handleBackdropParam(container, params.backdrop);
  663. if (!params.backdrop && params.allowOutsideClick) {
  664. warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
  665. }
  666. handlePositionParam(container, params.position);
  667. handleGrowParam(container, params.grow); // Custom class
  668. applyCustomClass(container, params.customClass, 'container');
  669. if (params.customContainerClass) {
  670. // @deprecated
  671. addClass(container, params.customContainerClass);
  672. }
  673. };
  674. /**
  675. * This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has.
  676. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  677. * This is the approach that Babel will probably take to implement private methods/fields
  678. * https://github.com/tc39/proposal-private-methods
  679. * https://github.com/babel/babel/pull/7555
  680. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  681. * then we can use that language feature.
  682. */
  683. var privateProps = {
  684. promise: new WeakMap(),
  685. innerParams: new WeakMap(),
  686. domCache: new WeakMap()
  687. };
  688. var inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
  689. var renderInput = function renderInput(instance, params) {
  690. var content = getContent();
  691. var innerParams = privateProps.innerParams.get(instance);
  692. var rerender = !innerParams || params.input !== innerParams.input;
  693. inputTypes.forEach(function (inputType) {
  694. var inputClass = swalClasses[inputType];
  695. var inputContainer = getChildByClass(content, inputClass); // set attributes
  696. setAttributes(inputType, params.inputAttributes); // set class
  697. setClass(inputContainer, inputClass, params);
  698. if (rerender) {
  699. hide(inputContainer);
  700. }
  701. });
  702. if (params.input && rerender) {
  703. showInput(params);
  704. }
  705. };
  706. var showInput = function showInput(params) {
  707. if (!renderInputType[params.input]) {
  708. return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\""));
  709. }
  710. var input = renderInputType[params.input](params);
  711. show(input); // input autofocus
  712. setTimeout(function () {
  713. focusInput(input);
  714. });
  715. };
  716. var removeAttributes = function removeAttributes(input) {
  717. for (var i = 0; i < input.attributes.length; i++) {
  718. var attrName = input.attributes[i].name;
  719. if (!(['type', 'value', 'style'].indexOf(attrName) !== -1)) {
  720. input.removeAttribute(attrName);
  721. }
  722. }
  723. };
  724. var setAttributes = function setAttributes(inputType, inputAttributes) {
  725. var input = getInput(getContent(), inputType);
  726. if (!input) {
  727. return;
  728. }
  729. removeAttributes(input);
  730. for (var attr in inputAttributes) {
  731. // Do not set a placeholder for <input type="range">
  732. // it'll crash Edge, #1298
  733. if (inputType === 'range' && attr === 'placeholder') {
  734. continue;
  735. }
  736. input.setAttribute(attr, inputAttributes[attr]);
  737. }
  738. };
  739. var setClass = function setClass(inputContainer, inputClass, params) {
  740. inputContainer.className = inputClass;
  741. if (params.inputClass) {
  742. addClass(inputContainer, params.inputClass);
  743. }
  744. if (params.customClass) {
  745. addClass(inputContainer, params.customClass.input);
  746. }
  747. };
  748. var setInputPlaceholder = function setInputPlaceholder(input, params) {
  749. if (!input.placeholder || params.inputPlaceholder) {
  750. input.placeholder = params.inputPlaceholder;
  751. }
  752. };
  753. var renderInputType = {};
  754. renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = function (params) {
  755. var input = getChildByClass(getContent(), swalClasses.input);
  756. if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') {
  757. input.value = params.inputValue;
  758. } else if (!isPromise(params.inputValue)) {
  759. warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(_typeof(params.inputValue), "\""));
  760. }
  761. setInputPlaceholder(input, params);
  762. input.type = params.input;
  763. return input;
  764. };
  765. renderInputType.file = function (params) {
  766. var input = getChildByClass(getContent(), swalClasses.file);
  767. setInputPlaceholder(input, params);
  768. input.type = params.input;
  769. return input;
  770. };
  771. renderInputType.range = function (params) {
  772. var range = getChildByClass(getContent(), swalClasses.range);
  773. var rangeInput = range.querySelector('input');
  774. var rangeOutput = range.querySelector('output');
  775. rangeInput.value = params.inputValue;
  776. rangeInput.type = params.input;
  777. rangeOutput.value = params.inputValue;
  778. return range;
  779. };
  780. renderInputType.select = function (params) {
  781. var select = getChildByClass(getContent(), swalClasses.select);
  782. select.innerHTML = '';
  783. if (params.inputPlaceholder) {
  784. var placeholder = document.createElement('option');
  785. placeholder.innerHTML = params.inputPlaceholder;
  786. placeholder.value = '';
  787. placeholder.disabled = true;
  788. placeholder.selected = true;
  789. select.appendChild(placeholder);
  790. }
  791. return select;
  792. };
  793. renderInputType.radio = function () {
  794. var radio = getChildByClass(getContent(), swalClasses.radio);
  795. radio.innerHTML = '';
  796. return radio;
  797. };
  798. renderInputType.checkbox = function (params) {
  799. var checkbox = getChildByClass(getContent(), swalClasses.checkbox);
  800. var checkboxInput = getInput(getContent(), 'checkbox');
  801. checkboxInput.type = 'checkbox';
  802. checkboxInput.value = 1;
  803. checkboxInput.id = swalClasses.checkbox;
  804. checkboxInput.checked = Boolean(params.inputValue);
  805. var label = checkbox.querySelector('span');
  806. label.innerHTML = params.inputPlaceholder;
  807. return checkbox;
  808. };
  809. renderInputType.textarea = function (params) {
  810. var textarea = getChildByClass(getContent(), swalClasses.textarea);
  811. textarea.value = params.inputValue;
  812. setInputPlaceholder(textarea, params);
  813. if ('MutationObserver' in window) {
  814. // #1699
  815. var initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
  816. var popupPadding = parseInt(window.getComputedStyle(getPopup()).paddingLeft) + parseInt(window.getComputedStyle(getPopup()).paddingRight);
  817. var outputsize = function outputsize() {
  818. var contentWidth = textarea.offsetWidth + popupPadding;
  819. if (contentWidth > initialPopupWidth) {
  820. getPopup().style.width = contentWidth + 'px';
  821. } else {
  822. getPopup().style.width = null;
  823. }
  824. };
  825. new MutationObserver(outputsize).observe(textarea, {
  826. attributes: true,
  827. attributeFilter: ['style']
  828. });
  829. }
  830. return textarea;
  831. };
  832. var renderContent = function renderContent(instance, params) {
  833. var content = getContent().querySelector('#' + swalClasses.content); // Content as HTML
  834. if (params.html) {
  835. parseHtmlToContainer(params.html, content);
  836. show(content, 'block'); // Content as plain text
  837. } else if (params.text) {
  838. content.textContent = params.text;
  839. show(content, 'block'); // No content
  840. } else {
  841. hide(content);
  842. }
  843. renderInput(instance, params); // Custom class
  844. applyCustomClass(getContent(), params.customClass, 'content');
  845. };
  846. var renderFooter = function renderFooter(instance, params) {
  847. var footer = getFooter();
  848. toggle(footer, params.footer);
  849. if (params.footer) {
  850. parseHtmlToContainer(params.footer, footer);
  851. } // Custom class
  852. applyCustomClass(footer, params.customClass, 'footer');
  853. };
  854. var renderCloseButton = function renderCloseButton(instance, params) {
  855. var closeButton = getCloseButton();
  856. closeButton.innerHTML = params.closeButtonHtml; // Custom class
  857. applyCustomClass(closeButton, params.customClass, 'closeButton');
  858. toggle(closeButton, params.showCloseButton);
  859. closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
  860. };
  861. var renderIcon = function renderIcon(instance, params) {
  862. var innerParams = privateProps.innerParams.get(instance); // if the icon with the given type already rendered,
  863. // apply the custom class without re-rendering the icon
  864. if (innerParams && params.type === innerParams.type && getIcon()) {
  865. applyCustomClass(getIcon(), params.customClass, 'icon');
  866. return;
  867. }
  868. hideAllIcons();
  869. if (!params.type) {
  870. return;
  871. }
  872. adjustSuccessIconBackgoundColor();
  873. if (Object.keys(iconTypes).indexOf(params.type) !== -1) {
  874. var icon = elementBySelector(".".concat(swalClasses.icon, ".").concat(iconTypes[params.type]));
  875. show(icon); // Custom class
  876. applyCustomClass(icon, params.customClass, 'icon'); // Animate icon
  877. toggleClass(icon, "swal2-animate-".concat(params.type, "-icon"), params.animation);
  878. } else {
  879. error("Unknown type! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.type, "\""));
  880. }
  881. };
  882. var hideAllIcons = function hideAllIcons() {
  883. var icons = getIcons();
  884. for (var i = 0; i < icons.length; i++) {
  885. hide(icons[i]);
  886. }
  887. }; // Adjust success icon background color to match the popup background color
  888. var adjustSuccessIconBackgoundColor = function adjustSuccessIconBackgoundColor() {
  889. var popup = getPopup();
  890. var popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
  891. var successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
  892. for (var i = 0; i < successIconParts.length; i++) {
  893. successIconParts[i].style.backgroundColor = popupBackgroundColor;
  894. }
  895. };
  896. var renderImage = function renderImage(instance, params) {
  897. var image = getImage();
  898. if (!params.imageUrl) {
  899. return hide(image);
  900. }
  901. show(image); // Src, alt
  902. image.setAttribute('src', params.imageUrl);
  903. image.setAttribute('alt', params.imageAlt); // Width, height
  904. applyNumericalStyle(image, 'width', params.imageWidth);
  905. applyNumericalStyle(image, 'height', params.imageHeight); // Class
  906. image.className = swalClasses.image;
  907. applyCustomClass(image, params.customClass, 'image');
  908. if (params.imageClass) {
  909. addClass(image, params.imageClass);
  910. }
  911. };
  912. var createStepElement = function createStepElement(step) {
  913. var stepEl = document.createElement('li');
  914. addClass(stepEl, swalClasses['progress-step']);
  915. stepEl.innerHTML = step;
  916. return stepEl;
  917. };
  918. var createLineElement = function createLineElement(params) {
  919. var lineEl = document.createElement('li');
  920. addClass(lineEl, swalClasses['progress-step-line']);
  921. if (params.progressStepsDistance) {
  922. lineEl.style.width = params.progressStepsDistance;
  923. }
  924. return lineEl;
  925. };
  926. var renderProgressSteps = function renderProgressSteps(instance, params) {
  927. var progressStepsContainer = getProgressSteps();
  928. if (!params.progressSteps || params.progressSteps.length === 0) {
  929. return hide(progressStepsContainer);
  930. }
  931. show(progressStepsContainer);
  932. progressStepsContainer.innerHTML = '';
  933. var currentProgressStep = parseInt(params.currentProgressStep === null ? Swal.getQueueStep() : params.currentProgressStep);
  934. if (currentProgressStep >= params.progressSteps.length) {
  935. warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
  936. }
  937. params.progressSteps.forEach(function (step, index) {
  938. var stepEl = createStepElement(step);
  939. progressStepsContainer.appendChild(stepEl);
  940. if (index === currentProgressStep) {
  941. addClass(stepEl, swalClasses['active-progress-step']);
  942. }
  943. if (index !== params.progressSteps.length - 1) {
  944. var lineEl = createLineElement(step);
  945. progressStepsContainer.appendChild(lineEl);
  946. }
  947. });
  948. };
  949. var renderTitle = function renderTitle(instance, params) {
  950. var title = getTitle();
  951. toggle(title, params.title || params.titleText);
  952. if (params.title) {
  953. parseHtmlToContainer(params.title, title);
  954. }
  955. if (params.titleText) {
  956. title.innerText = params.titleText;
  957. } // Custom class
  958. applyCustomClass(title, params.customClass, 'title');
  959. };
  960. var renderHeader = function renderHeader(instance, params) {
  961. var header = getHeader(); // Custom class
  962. applyCustomClass(header, params.customClass, 'header'); // Progress steps
  963. renderProgressSteps(instance, params); // Icon
  964. renderIcon(instance, params); // Image
  965. renderImage(instance, params); // Title
  966. renderTitle(instance, params); // Close button
  967. renderCloseButton(instance, params);
  968. };
  969. var renderPopup = function renderPopup(instance, params) {
  970. var popup = getPopup(); // Width
  971. applyNumericalStyle(popup, 'width', params.width); // Padding
  972. applyNumericalStyle(popup, 'padding', params.padding); // Background
  973. if (params.background) {
  974. popup.style.background = params.background;
  975. } // Default Class
  976. popup.className = swalClasses.popup;
  977. if (params.toast) {
  978. addClass([document.documentElement, document.body], swalClasses['toast-shown']);
  979. addClass(popup, swalClasses.toast);
  980. } else {
  981. addClass(popup, swalClasses.modal);
  982. } // Custom class
  983. applyCustomClass(popup, params.customClass, 'popup');
  984. if (typeof params.customClass === 'string') {
  985. addClass(popup, params.customClass);
  986. } // CSS animation
  987. toggleClass(popup, swalClasses.noanimation, !params.animation);
  988. };
  989. var render = function render(instance, params) {
  990. renderPopup(instance, params);
  991. renderContainer(instance, params);
  992. renderHeader(instance, params);
  993. renderContent(instance, params);
  994. renderActions(instance, params);
  995. renderFooter(instance, params);
  996. if (typeof params.onRender === 'function') {
  997. params.onRender(getPopup());
  998. }
  999. };
  1000. /*
  1001. * Global function to determine if SweetAlert2 popup is shown
  1002. */
  1003. var isVisible$1 = function isVisible$$1() {
  1004. return isVisible(getPopup());
  1005. };
  1006. /*
  1007. * Global function to click 'Confirm' button
  1008. */
  1009. var clickConfirm = function clickConfirm() {
  1010. return getConfirmButton() && getConfirmButton().click();
  1011. };
  1012. /*
  1013. * Global function to click 'Cancel' button
  1014. */
  1015. var clickCancel = function clickCancel() {
  1016. return getCancelButton() && getCancelButton().click();
  1017. };
  1018. function fire() {
  1019. var Swal = this;
  1020. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  1021. args[_key] = arguments[_key];
  1022. }
  1023. return _construct(Swal, args);
  1024. }
  1025. /**
  1026. * Returns an extended version of `Swal` containing `params` as defaults.
  1027. * Useful for reusing Swal configuration.
  1028. *
  1029. * For example:
  1030. *
  1031. * Before:
  1032. * const textPromptOptions = { input: 'text', showCancelButton: true }
  1033. * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
  1034. * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
  1035. *
  1036. * After:
  1037. * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
  1038. * const {value: firstName} = await TextPrompt('What is your first name?')
  1039. * const {value: lastName} = await TextPrompt('What is your last name?')
  1040. *
  1041. * @param mixinParams
  1042. */
  1043. function mixin(mixinParams) {
  1044. var MixinSwal =
  1045. /*#__PURE__*/
  1046. function (_this) {
  1047. _inherits(MixinSwal, _this);
  1048. function MixinSwal() {
  1049. _classCallCheck(this, MixinSwal);
  1050. return _possibleConstructorReturn(this, _getPrototypeOf(MixinSwal).apply(this, arguments));
  1051. }
  1052. _createClass(MixinSwal, [{
  1053. key: "_main",
  1054. value: function _main(params) {
  1055. return _get(_getPrototypeOf(MixinSwal.prototype), "_main", this).call(this, _extends({}, mixinParams, params));
  1056. }
  1057. }]);
  1058. return MixinSwal;
  1059. }(this);
  1060. return MixinSwal;
  1061. }
  1062. // private global state for the queue feature
  1063. var currentSteps = [];
  1064. /*
  1065. * Global function for chaining sweetAlert popups
  1066. */
  1067. var queue = function queue(steps) {
  1068. var Swal = this;
  1069. currentSteps = steps;
  1070. var resetAndResolve = function resetAndResolve(resolve, value) {
  1071. currentSteps = [];
  1072. document.body.removeAttribute('data-swal2-queue-step');
  1073. resolve(value);
  1074. };
  1075. var queueResult = [];
  1076. return new Promise(function (resolve) {
  1077. (function step(i, callback) {
  1078. if (i < currentSteps.length) {
  1079. document.body.setAttribute('data-swal2-queue-step', i);
  1080. Swal.fire(currentSteps[i]).then(function (result) {
  1081. if (typeof result.value !== 'undefined') {
  1082. queueResult.push(result.value);
  1083. step(i + 1, callback);
  1084. } else {
  1085. resetAndResolve(resolve, {
  1086. dismiss: result.dismiss
  1087. });
  1088. }
  1089. });
  1090. } else {
  1091. resetAndResolve(resolve, {
  1092. value: queueResult
  1093. });
  1094. }
  1095. })(0);
  1096. });
  1097. };
  1098. /*
  1099. * Global function for getting the index of current popup in queue
  1100. */
  1101. var getQueueStep = function getQueueStep() {
  1102. return document.body.getAttribute('data-swal2-queue-step');
  1103. };
  1104. /*
  1105. * Global function for inserting a popup to the queue
  1106. */
  1107. var insertQueueStep = function insertQueueStep(step, index) {
  1108. if (index && index < currentSteps.length) {
  1109. return currentSteps.splice(index, 0, step);
  1110. }
  1111. return currentSteps.push(step);
  1112. };
  1113. /*
  1114. * Global function for deleting a popup from the queue
  1115. */
  1116. var deleteQueueStep = function deleteQueueStep(index) {
  1117. if (typeof currentSteps[index] !== 'undefined') {
  1118. currentSteps.splice(index, 1);
  1119. }
  1120. };
  1121. /**
  1122. * Show spinner instead of Confirm button and disable Cancel button
  1123. */
  1124. var showLoading = function showLoading() {
  1125. var popup = getPopup();
  1126. if (!popup) {
  1127. Swal.fire('');
  1128. }
  1129. popup = getPopup();
  1130. var actions = getActions();
  1131. var confirmButton = getConfirmButton();
  1132. var cancelButton = getCancelButton();
  1133. show(actions);
  1134. show(confirmButton);
  1135. addClass([popup, actions], swalClasses.loading);
  1136. confirmButton.disabled = true;
  1137. cancelButton.disabled = true;
  1138. popup.setAttribute('data-loading', true);
  1139. popup.setAttribute('aria-busy', true);
  1140. popup.focus();
  1141. };
  1142. var RESTORE_FOCUS_TIMEOUT = 100;
  1143. var globalState = {};
  1144. var focusPreviousActiveElement = function focusPreviousActiveElement() {
  1145. if (globalState.previousActiveElement && globalState.previousActiveElement.focus) {
  1146. globalState.previousActiveElement.focus();
  1147. globalState.previousActiveElement = null;
  1148. } else if (document.body) {
  1149. document.body.focus();
  1150. }
  1151. }; // Restore previous active (focused) element
  1152. var restoreActiveElement = function restoreActiveElement() {
  1153. return new Promise(function (resolve) {
  1154. var x = window.scrollX;
  1155. var y = window.scrollY;
  1156. globalState.restoreFocusTimeout = setTimeout(function () {
  1157. focusPreviousActiveElement();
  1158. resolve();
  1159. }, RESTORE_FOCUS_TIMEOUT); // issues/900
  1160. if (typeof x !== 'undefined' && typeof y !== 'undefined') {
  1161. // IE doesn't have scrollX/scrollY support
  1162. window.scrollTo(x, y);
  1163. }
  1164. });
  1165. };
  1166. /**
  1167. * If `timer` parameter is set, returns number of milliseconds of timer remained.
  1168. * Otherwise, returns undefined.
  1169. */
  1170. var getTimerLeft = function getTimerLeft() {
  1171. return globalState.timeout && globalState.timeout.getTimerLeft();
  1172. };
  1173. /**
  1174. * Stop timer. Returns number of milliseconds of timer remained.
  1175. * If `timer` parameter isn't set, returns undefined.
  1176. */
  1177. var stopTimer = function stopTimer() {
  1178. return globalState.timeout && globalState.timeout.stop();
  1179. };
  1180. /**
  1181. * Resume timer. Returns number of milliseconds of timer remained.
  1182. * If `timer` parameter isn't set, returns undefined.
  1183. */
  1184. var resumeTimer = function resumeTimer() {
  1185. return globalState.timeout && globalState.timeout.start();
  1186. };
  1187. /**
  1188. * Resume timer. Returns number of milliseconds of timer remained.
  1189. * If `timer` parameter isn't set, returns undefined.
  1190. */
  1191. var toggleTimer = function toggleTimer() {
  1192. var timer = globalState.timeout;
  1193. return timer && (timer.running ? timer.stop() : timer.start());
  1194. };
  1195. /**
  1196. * Increase timer. Returns number of milliseconds of an updated timer.
  1197. * If `timer` parameter isn't set, returns undefined.
  1198. */
  1199. var increaseTimer = function increaseTimer(n) {
  1200. return globalState.timeout && globalState.timeout.increase(n);
  1201. };
  1202. /**
  1203. * Check if timer is running. Returns true if timer is running
  1204. * or false if timer is paused or stopped.
  1205. * If `timer` parameter isn't set, returns undefined
  1206. */
  1207. var isTimerRunning = function isTimerRunning() {
  1208. return globalState.timeout && globalState.timeout.isRunning();
  1209. };
  1210. var defaultParams = {
  1211. title: '',
  1212. titleText: '',
  1213. text: '',
  1214. html: '',
  1215. footer: '',
  1216. type: null,
  1217. toast: false,
  1218. customClass: '',
  1219. customContainerClass: '',
  1220. target: 'body',
  1221. backdrop: true,
  1222. animation: true,
  1223. heightAuto: true,
  1224. allowOutsideClick: true,
  1225. allowEscapeKey: true,
  1226. allowEnterKey: true,
  1227. stopKeydownPropagation: true,
  1228. keydownListenerCapture: false,
  1229. showConfirmButton: true,
  1230. showCancelButton: false,
  1231. preConfirm: null,
  1232. confirmButtonText: 'OK',
  1233. confirmButtonAriaLabel: '',
  1234. confirmButtonColor: null,
  1235. confirmButtonClass: '',
  1236. cancelButtonText: 'Cancel',
  1237. cancelButtonAriaLabel: '',
  1238. cancelButtonColor: null,
  1239. cancelButtonClass: '',
  1240. buttonsStyling: true,
  1241. reverseButtons: false,
  1242. focusConfirm: true,
  1243. focusCancel: false,
  1244. showCloseButton: false,
  1245. closeButtonHtml: '&times;',
  1246. closeButtonAriaLabel: 'Close this dialog',
  1247. showLoaderOnConfirm: false,
  1248. imageUrl: null,
  1249. imageWidth: null,
  1250. imageHeight: null,
  1251. imageAlt: '',
  1252. imageClass: '',
  1253. timer: null,
  1254. width: null,
  1255. padding: null,
  1256. background: null,
  1257. input: null,
  1258. inputPlaceholder: '',
  1259. inputValue: '',
  1260. inputOptions: {},
  1261. inputAutoTrim: true,
  1262. inputClass: '',
  1263. inputAttributes: {},
  1264. inputValidator: null,
  1265. validationMessage: null,
  1266. grow: false,
  1267. position: 'center',
  1268. progressSteps: [],
  1269. currentProgressStep: null,
  1270. progressStepsDistance: null,
  1271. onBeforeOpen: null,
  1272. onOpen: null,
  1273. onRender: null,
  1274. onClose: null,
  1275. onAfterClose: null,
  1276. scrollbarPadding: true
  1277. };
  1278. var updatableParams = ['title', 'titleText', 'text', 'html', 'type', 'customClass', 'showConfirmButton', 'showCancelButton', 'confirmButtonText', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonClass', 'cancelButtonText', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonClass', 'buttonsStyling', 'reverseButtons', 'imageUrl', 'imageWidth', 'imageHeigth', 'imageAlt', 'imageClass', 'progressSteps', 'currentProgressStep'];
  1279. var deprecatedParams = {
  1280. customContainerClass: 'customClass',
  1281. confirmButtonClass: 'customClass',
  1282. cancelButtonClass: 'customClass',
  1283. imageClass: 'customClass',
  1284. inputClass: 'customClass'
  1285. };
  1286. var toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusCancel', 'heightAuto', 'keydownListenerCapture'];
  1287. /**
  1288. * Is valid parameter
  1289. * @param {String} paramName
  1290. */
  1291. var isValidParameter = function isValidParameter(paramName) {
  1292. return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
  1293. };
  1294. /**
  1295. * Is valid parameter for Swal.update() method
  1296. * @param {String} paramName
  1297. */
  1298. var isUpdatableParameter = function isUpdatableParameter(paramName) {
  1299. return updatableParams.indexOf(paramName) !== -1;
  1300. };
  1301. /**
  1302. * Is deprecated parameter
  1303. * @param {String} paramName
  1304. */
  1305. var isDeprecatedParameter = function isDeprecatedParameter(paramName) {
  1306. return deprecatedParams[paramName];
  1307. };
  1308. var checkIfParamIsValid = function checkIfParamIsValid(param) {
  1309. if (!isValidParameter(param)) {
  1310. warn("Unknown parameter \"".concat(param, "\""));
  1311. }
  1312. };
  1313. var checkIfToastParamIsValid = function checkIfToastParamIsValid(param) {
  1314. if (toastIncompatibleParams.indexOf(param) !== -1) {
  1315. warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
  1316. }
  1317. };
  1318. var checkIfParamIsDeprecated = function checkIfParamIsDeprecated(param) {
  1319. if (isDeprecatedParameter(param)) {
  1320. warnAboutDepreation(param, isDeprecatedParameter(param));
  1321. }
  1322. };
  1323. /**
  1324. * Show relevant warnings for given params
  1325. *
  1326. * @param params
  1327. */
  1328. var showWarningsForParams = function showWarningsForParams(params) {
  1329. for (var param in params) {
  1330. checkIfParamIsValid(param);
  1331. if (params.toast) {
  1332. checkIfToastParamIsValid(param);
  1333. }
  1334. checkIfParamIsDeprecated();
  1335. }
  1336. };
  1337. var staticMethods = Object.freeze({
  1338. isValidParameter: isValidParameter,
  1339. isUpdatableParameter: isUpdatableParameter,
  1340. isDeprecatedParameter: isDeprecatedParameter,
  1341. argsToParams: argsToParams,
  1342. isVisible: isVisible$1,
  1343. clickConfirm: clickConfirm,
  1344. clickCancel: clickCancel,
  1345. getContainer: getContainer,
  1346. getPopup: getPopup,
  1347. getTitle: getTitle,
  1348. getContent: getContent,
  1349. getImage: getImage,
  1350. getIcon: getIcon,
  1351. getIcons: getIcons,
  1352. getCloseButton: getCloseButton,
  1353. getActions: getActions,
  1354. getConfirmButton: getConfirmButton,
  1355. getCancelButton: getCancelButton,
  1356. getHeader: getHeader,
  1357. getFooter: getFooter,
  1358. getFocusableElements: getFocusableElements,
  1359. getValidationMessage: getValidationMessage,
  1360. isLoading: isLoading,
  1361. fire: fire,
  1362. mixin: mixin,
  1363. queue: queue,
  1364. getQueueStep: getQueueStep,
  1365. insertQueueStep: insertQueueStep,
  1366. deleteQueueStep: deleteQueueStep,
  1367. showLoading: showLoading,
  1368. enableLoading: showLoading,
  1369. getTimerLeft: getTimerLeft,
  1370. stopTimer: stopTimer,
  1371. resumeTimer: resumeTimer,
  1372. toggleTimer: toggleTimer,
  1373. increaseTimer: increaseTimer,
  1374. isTimerRunning: isTimerRunning
  1375. });
  1376. /**
  1377. * Enables buttons and hide loader.
  1378. */
  1379. function hideLoading() {
  1380. var innerParams = privateProps.innerParams.get(this);
  1381. var domCache = privateProps.domCache.get(this);
  1382. if (!innerParams.showConfirmButton) {
  1383. hide(domCache.confirmButton);
  1384. if (!innerParams.showCancelButton) {
  1385. hide(domCache.actions);
  1386. }
  1387. }
  1388. removeClass([domCache.popup, domCache.actions], swalClasses.loading);
  1389. domCache.popup.removeAttribute('aria-busy');
  1390. domCache.popup.removeAttribute('data-loading');
  1391. domCache.confirmButton.disabled = false;
  1392. domCache.cancelButton.disabled = false;
  1393. }
  1394. function getInput$1(instance) {
  1395. var innerParams = privateProps.innerParams.get(instance || this);
  1396. var domCache = privateProps.domCache.get(instance || this);
  1397. if (!domCache) {
  1398. return null;
  1399. }
  1400. return getInput(domCache.content, innerParams.input);
  1401. }
  1402. var fixScrollbar = function fixScrollbar() {
  1403. // for queues, do not do this more than once
  1404. if (states.previousBodyPadding !== null) {
  1405. return;
  1406. } // if the body has overflow
  1407. if (document.body.scrollHeight > window.innerHeight) {
  1408. // add padding so the content doesn't shift after removal of scrollbar
  1409. states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
  1410. document.body.style.paddingRight = states.previousBodyPadding + measureScrollbar() + 'px';
  1411. }
  1412. };
  1413. var undoScrollbar = function undoScrollbar() {
  1414. if (states.previousBodyPadding !== null) {
  1415. document.body.style.paddingRight = states.previousBodyPadding + 'px';
  1416. states.previousBodyPadding = null;
  1417. }
  1418. };
  1419. /* istanbul ignore next */
  1420. var iOSfix = function iOSfix() {
  1421. var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  1422. if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
  1423. var offset = document.body.scrollTop;
  1424. document.body.style.top = offset * -1 + 'px';
  1425. addClass(document.body, swalClasses.iosfix);
  1426. lockBodyScroll();
  1427. }
  1428. };
  1429. var lockBodyScroll = function lockBodyScroll() {
  1430. // #1246
  1431. var container = getContainer();
  1432. var preventTouchMove;
  1433. container.ontouchstart = function (e) {
  1434. preventTouchMove = e.target === container || !isScrollable(container) && e.target.tagName !== 'INPUT' // #1603
  1435. ;
  1436. };
  1437. container.ontouchmove = function (e) {
  1438. if (preventTouchMove) {
  1439. e.preventDefault();
  1440. e.stopPropagation();
  1441. }
  1442. };
  1443. };
  1444. /* istanbul ignore next */
  1445. var undoIOSfix = function undoIOSfix() {
  1446. if (hasClass(document.body, swalClasses.iosfix)) {
  1447. var offset = parseInt(document.body.style.top, 10);
  1448. removeClass(document.body, swalClasses.iosfix);
  1449. document.body.style.top = '';
  1450. document.body.scrollTop = offset * -1;
  1451. }
  1452. };
  1453. var isIE11 = function isIE11() {
  1454. return !!window.MSInputMethodContext && !!document.documentMode;
  1455. }; // Fix IE11 centering sweetalert2/issues/933
  1456. /* istanbul ignore next */
  1457. var fixVerticalPositionIE = function fixVerticalPositionIE() {
  1458. var container = getContainer();
  1459. var popup = getPopup();
  1460. container.style.removeProperty('align-items');
  1461. if (popup.offsetTop < 0) {
  1462. container.style.alignItems = 'flex-start';
  1463. }
  1464. };
  1465. /* istanbul ignore next */
  1466. var IEfix = function IEfix() {
  1467. if (typeof window !== 'undefined' && isIE11()) {
  1468. fixVerticalPositionIE();
  1469. window.addEventListener('resize', fixVerticalPositionIE);
  1470. }
  1471. };
  1472. /* istanbul ignore next */
  1473. var undoIEfix = function undoIEfix() {
  1474. if (typeof window !== 'undefined' && isIE11()) {
  1475. window.removeEventListener('resize', fixVerticalPositionIE);
  1476. }
  1477. };
  1478. // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
  1479. // elements not within the active modal dialog will not be surfaced if a user opens a screen
  1480. // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
  1481. var setAriaHidden = function setAriaHidden() {
  1482. var bodyChildren = toArray(document.body.children);
  1483. bodyChildren.forEach(function (el) {
  1484. if (el === getContainer() || contains(el, getContainer())) {
  1485. return;
  1486. }
  1487. if (el.hasAttribute('aria-hidden')) {
  1488. el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
  1489. }
  1490. el.setAttribute('aria-hidden', 'true');
  1491. });
  1492. };
  1493. var unsetAriaHidden = function unsetAriaHidden() {
  1494. var bodyChildren = toArray(document.body.children);
  1495. bodyChildren.forEach(function (el) {
  1496. if (el.hasAttribute('data-previous-aria-hidden')) {
  1497. el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
  1498. el.removeAttribute('data-previous-aria-hidden');
  1499. } else {
  1500. el.removeAttribute('aria-hidden');
  1501. }
  1502. });
  1503. };
  1504. /**
  1505. * This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has.
  1506. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  1507. * This is the approach that Babel will probably take to implement private methods/fields
  1508. * https://github.com/tc39/proposal-private-methods
  1509. * https://github.com/babel/babel/pull/7555
  1510. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  1511. * then we can use that language feature.
  1512. */
  1513. var privateMethods = {
  1514. swalPromiseResolve: new WeakMap()
  1515. };
  1516. /*
  1517. * Instance method to close sweetAlert
  1518. */
  1519. function removePopupAndResetState(instance, container, isToast, onAfterClose) {
  1520. if (isToast) {
  1521. triggerOnAfterCloseAndDispose(instance, onAfterClose);
  1522. } else {
  1523. restoreActiveElement().then(function () {
  1524. return triggerOnAfterCloseAndDispose(instance, onAfterClose);
  1525. });
  1526. globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
  1527. capture: globalState.keydownListenerCapture
  1528. });
  1529. globalState.keydownHandlerAdded = false;
  1530. }
  1531. if (container.parentNode) {
  1532. container.parentNode.removeChild(container);
  1533. }
  1534. if (isModal()) {
  1535. undoScrollbar();
  1536. undoIOSfix();
  1537. undoIEfix();
  1538. unsetAriaHidden();
  1539. }
  1540. removeBodyClasses();
  1541. }
  1542. function removeBodyClasses() {
  1543. removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['toast-column']]);
  1544. }
  1545. function disposeSwal(instance) {
  1546. // Unset this.params so GC will dispose it (#1569)
  1547. delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)
  1548. delete globalState.keydownHandler;
  1549. delete globalState.keydownTarget; // Unset WeakMaps so GC will be able to dispose them (#1569)
  1550. unsetWeakMaps(privateProps);
  1551. unsetWeakMaps(privateMethods);
  1552. }
  1553. function close(resolveValue) {
  1554. var popup = getPopup();
  1555. if (!popup || hasClass(popup, swalClasses.hide)) {
  1556. return;
  1557. }
  1558. var innerParams = privateProps.innerParams.get(this);
  1559. if (!innerParams) {
  1560. return;
  1561. }
  1562. var swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
  1563. removeClass(popup, swalClasses.show);
  1564. addClass(popup, swalClasses.hide);
  1565. handlePopupAnimation(this, popup, innerParams); // Resolve Swal promise
  1566. swalPromiseResolve(resolveValue || {});
  1567. }
  1568. var handlePopupAnimation = function handlePopupAnimation(instance, popup, innerParams) {
  1569. var container = getContainer(); // If animation is supported, animate
  1570. var animationIsSupported = animationEndEvent && hasCssAnimation(popup);
  1571. var onClose = innerParams.onClose,
  1572. onAfterClose = innerParams.onAfterClose;
  1573. if (onClose !== null && typeof onClose === 'function') {
  1574. onClose(popup);
  1575. }
  1576. if (animationIsSupported) {
  1577. animatePopup(instance, popup, container, onAfterClose);
  1578. } else {
  1579. // Otherwise, remove immediately
  1580. removePopupAndResetState(instance, container, isToast(), onAfterClose);
  1581. }
  1582. };
  1583. var animatePopup = function animatePopup(instance, popup, container, onAfterClose) {
  1584. globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, isToast(), onAfterClose);
  1585. popup.addEventListener(animationEndEvent, function (e) {
  1586. if (e.target === popup) {
  1587. globalState.swalCloseEventFinishedCallback();
  1588. delete globalState.swalCloseEventFinishedCallback;
  1589. }
  1590. });
  1591. };
  1592. var unsetWeakMaps = function unsetWeakMaps(obj) {
  1593. for (var i in obj) {
  1594. obj[i] = new WeakMap();
  1595. }
  1596. };
  1597. var triggerOnAfterCloseAndDispose = function triggerOnAfterCloseAndDispose(instance, onAfterClose) {
  1598. setTimeout(function () {
  1599. if (onAfterClose !== null && typeof onAfterClose === 'function') {
  1600. onAfterClose();
  1601. }
  1602. if (!getPopup()) {
  1603. disposeSwal(instance);
  1604. }
  1605. });
  1606. };
  1607. function setButtonsDisabled(instance, buttons, disabled) {
  1608. var domCache = privateProps.domCache.get(instance);
  1609. buttons.forEach(function (button) {
  1610. domCache[button].disabled = disabled;
  1611. });
  1612. }
  1613. function setInputDisabled(input, disabled) {
  1614. if (!input) {
  1615. return false;
  1616. }
  1617. if (input.type === 'radio') {
  1618. var radiosContainer = input.parentNode.parentNode;
  1619. var radios = radiosContainer.querySelectorAll('input');
  1620. for (var i = 0; i < radios.length; i++) {
  1621. radios[i].disabled = disabled;
  1622. }
  1623. } else {
  1624. input.disabled = disabled;
  1625. }
  1626. }
  1627. function enableButtons() {
  1628. setButtonsDisabled(this, ['confirmButton', 'cancelButton'], false);
  1629. }
  1630. function disableButtons() {
  1631. setButtonsDisabled(this, ['confirmButton', 'cancelButton'], true);
  1632. } // @deprecated
  1633. function enableConfirmButton() {
  1634. warnAboutDepreation('Swal.enableConfirmButton()', "Swal.getConfirmButton().removeAttribute('disabled')");
  1635. setButtonsDisabled(this, ['confirmButton'], false);
  1636. } // @deprecated
  1637. function disableConfirmButton() {
  1638. warnAboutDepreation('Swal.disableConfirmButton()', "Swal.getConfirmButton().setAttribute('disabled', '')");
  1639. setButtonsDisabled(this, ['confirmButton'], true);
  1640. }
  1641. function enableInput() {
  1642. return setInputDisabled(this.getInput(), false);
  1643. }
  1644. function disableInput() {
  1645. return setInputDisabled(this.getInput(), true);
  1646. }
  1647. function showValidationMessage(error) {
  1648. var domCache = privateProps.domCache.get(this);
  1649. domCache.validationMessage.innerHTML = error;
  1650. var popupComputedStyle = window.getComputedStyle(domCache.popup);
  1651. domCache.validationMessage.style.marginLeft = "-".concat(popupComputedStyle.getPropertyValue('padding-left'));
  1652. domCache.validationMessage.style.marginRight = "-".concat(popupComputedStyle.getPropertyValue('padding-right'));
  1653. show(domCache.validationMessage);
  1654. var input = this.getInput();
  1655. if (input) {
  1656. input.setAttribute('aria-invalid', true);
  1657. input.setAttribute('aria-describedBy', swalClasses['validation-message']);
  1658. focusInput(input);
  1659. addClass(input, swalClasses.inputerror);
  1660. }
  1661. } // Hide block with validation message
  1662. function resetValidationMessage$1() {
  1663. var domCache = privateProps.domCache.get(this);
  1664. if (domCache.validationMessage) {
  1665. hide(domCache.validationMessage);
  1666. }
  1667. var input = this.getInput();
  1668. if (input) {
  1669. input.removeAttribute('aria-invalid');
  1670. input.removeAttribute('aria-describedBy');
  1671. removeClass(input, swalClasses.inputerror);
  1672. }
  1673. }
  1674. function getProgressSteps$1() {
  1675. warnAboutDepreation('Swal.getProgressSteps()', "const swalInstance = Swal.fire({progressSteps: ['1', '2', '3']}); const progressSteps = swalInstance.params.progressSteps");
  1676. var innerParams = privateProps.innerParams.get(this);
  1677. return innerParams.progressSteps;
  1678. }
  1679. function setProgressSteps(progressSteps) {
  1680. warnAboutDepreation('Swal.setProgressSteps()', 'Swal.update()');
  1681. var innerParams = privateProps.innerParams.get(this);
  1682. var updatedParams = _extends({}, innerParams, {
  1683. progressSteps: progressSteps
  1684. });
  1685. renderProgressSteps(this, updatedParams);
  1686. privateProps.innerParams.set(this, updatedParams);
  1687. }
  1688. function showProgressSteps() {
  1689. var domCache = privateProps.domCache.get(this);
  1690. show(domCache.progressSteps);
  1691. }
  1692. function hideProgressSteps() {
  1693. var domCache = privateProps.domCache.get(this);
  1694. hide(domCache.progressSteps);
  1695. }
  1696. var Timer =
  1697. /*#__PURE__*/
  1698. function () {
  1699. function Timer(callback, delay) {
  1700. _classCallCheck(this, Timer);
  1701. this.callback = callback;
  1702. this.remaining = delay;
  1703. this.running = false;
  1704. this.start();
  1705. }
  1706. _createClass(Timer, [{
  1707. key: "start",
  1708. value: function start() {
  1709. if (!this.running) {
  1710. this.running = true;
  1711. this.started = new Date();
  1712. this.id = setTimeout(this.callback, this.remaining);
  1713. }
  1714. return this.remaining;
  1715. }
  1716. }, {
  1717. key: "stop",
  1718. value: function stop() {
  1719. if (this.running) {
  1720. this.running = false;
  1721. clearTimeout(this.id);
  1722. this.remaining -= new Date() - this.started;
  1723. }
  1724. return this.remaining;
  1725. }
  1726. }, {
  1727. key: "increase",
  1728. value: function increase(n) {
  1729. var running = this.running;
  1730. if (running) {
  1731. this.stop();
  1732. }
  1733. this.remaining += n;
  1734. if (running) {
  1735. this.start();
  1736. }
  1737. return this.remaining;
  1738. }
  1739. }, {
  1740. key: "getTimerLeft",
  1741. value: function getTimerLeft() {
  1742. if (this.running) {
  1743. this.stop();
  1744. this.start();
  1745. }
  1746. return this.remaining;
  1747. }
  1748. }, {
  1749. key: "isRunning",
  1750. value: function isRunning() {
  1751. return this.running;
  1752. }
  1753. }]);
  1754. return Timer;
  1755. }();
  1756. var defaultInputValidators = {
  1757. email: function email(string, validationMessage) {
  1758. 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');
  1759. },
  1760. url: function url(string, validationMessage) {
  1761. // taken from https://stackoverflow.com/a/3809435 with a small change from #1306
  1762. return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
  1763. }
  1764. };
  1765. function setDefaultInputValidators(params) {
  1766. // Use default `inputValidator` for supported input types if not provided
  1767. if (!params.inputValidator) {
  1768. Object.keys(defaultInputValidators).forEach(function (key) {
  1769. if (params.input === key) {
  1770. params.inputValidator = defaultInputValidators[key];
  1771. }
  1772. });
  1773. }
  1774. }
  1775. function validateCustomTargetElement(params) {
  1776. // Determine if the custom target element is valid
  1777. if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
  1778. warn('Target parameter is not valid, defaulting to "body"');
  1779. params.target = 'body';
  1780. }
  1781. }
  1782. /**
  1783. * Set type, text and actions on popup
  1784. *
  1785. * @param params
  1786. * @returns {boolean}
  1787. */
  1788. function setParameters(params) {
  1789. setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm
  1790. if (params.showLoaderOnConfirm && !params.preConfirm) {
  1791. 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');
  1792. } // params.animation will be actually used in renderPopup.js
  1793. // but in case when params.animation is a function, we need to call that function
  1794. // before popup (re)initialization, so it'll be possible to check Swal.isVisible()
  1795. // inside the params.animation function
  1796. params.animation = callIfFunction(params.animation);
  1797. validateCustomTargetElement(params); // Replace newlines with <br> in title
  1798. if (typeof params.title === 'string') {
  1799. params.title = params.title.split('\n').join('<br />');
  1800. }
  1801. init(params);
  1802. }
  1803. function swalOpenAnimationFinished(popup, container) {
  1804. popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
  1805. container.style.overflowY = 'auto';
  1806. }
  1807. /**
  1808. * Open popup, add necessary classes and styles, fix scrollbar
  1809. *
  1810. * @param {Array} params
  1811. */
  1812. var openPopup = function openPopup(params) {
  1813. var container = getContainer();
  1814. var popup = getPopup();
  1815. if (typeof params.onBeforeOpen === 'function') {
  1816. params.onBeforeOpen(popup);
  1817. }
  1818. addClasses(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'
  1819. setScrollingVisibility(container, popup);
  1820. if (isModal()) {
  1821. fixScrollContainer(container, params.scrollbarPadding);
  1822. }
  1823. if (!isToast() && !globalState.previousActiveElement) {
  1824. globalState.previousActiveElement = document.activeElement;
  1825. }
  1826. if (typeof params.onOpen === 'function') {
  1827. setTimeout(function () {
  1828. return params.onOpen(popup);
  1829. });
  1830. }
  1831. };
  1832. var setScrollingVisibility = function setScrollingVisibility(container, popup) {
  1833. if (animationEndEvent && hasCssAnimation(popup)) {
  1834. container.style.overflowY = 'hidden';
  1835. popup.addEventListener(animationEndEvent, swalOpenAnimationFinished.bind(null, popup, container));
  1836. } else {
  1837. container.style.overflowY = 'auto';
  1838. }
  1839. };
  1840. var fixScrollContainer = function fixScrollContainer(container, scrollbarPadding) {
  1841. iOSfix();
  1842. IEfix();
  1843. setAriaHidden();
  1844. if (scrollbarPadding) {
  1845. fixScrollbar();
  1846. } // sweetalert2/issues/1247
  1847. setTimeout(function () {
  1848. container.scrollTop = 0;
  1849. });
  1850. };
  1851. var addClasses = function addClasses(container, popup, params) {
  1852. if (params.animation) {
  1853. addClass(popup, swalClasses.show);
  1854. addClass(container, swalClasses.fade);
  1855. }
  1856. show(popup);
  1857. addClass([document.documentElement, document.body, container], swalClasses.shown);
  1858. if (params.heightAuto && params.backdrop && !params.toast) {
  1859. addClass([document.documentElement, document.body], swalClasses['height-auto']);
  1860. }
  1861. };
  1862. var handleInputOptionsAndValue = function handleInputOptionsAndValue(instance, params) {
  1863. if (params.input === 'select' || params.input === 'radio') {
  1864. handleInputOptions(instance, params);
  1865. } else if (['text', 'email', 'number', 'tel', 'textarea'].indexOf(params.input) !== -1 && isPromise(params.inputValue)) {
  1866. handleInputValue(instance, params);
  1867. }
  1868. };
  1869. var handleInputOptions = function handleInputOptions(instance, params) {
  1870. var content = getContent();
  1871. var processInputOptions = function processInputOptions(inputOptions) {
  1872. return populateInputOptions[params.input](content, formatInputOptions(inputOptions), params);
  1873. };
  1874. if (isPromise(params.inputOptions)) {
  1875. showLoading();
  1876. params.inputOptions.then(function (inputOptions) {
  1877. instance.hideLoading();
  1878. processInputOptions(inputOptions);
  1879. });
  1880. } else if (_typeof(params.inputOptions) === 'object') {
  1881. processInputOptions(params.inputOptions);
  1882. } else {
  1883. error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(_typeof(params.inputOptions)));
  1884. }
  1885. };
  1886. var handleInputValue = function handleInputValue(instance, params) {
  1887. var input = instance.getInput();
  1888. hide(input);
  1889. params.inputValue.then(function (inputValue) {
  1890. input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : inputValue + '';
  1891. show(input);
  1892. input.focus();
  1893. instance.hideLoading();
  1894. })["catch"](function (err) {
  1895. error('Error in inputValue promise: ' + err);
  1896. input.value = '';
  1897. show(input);
  1898. input.focus();
  1899. instance.hideLoading();
  1900. });
  1901. };
  1902. var populateInputOptions = {
  1903. select: function select(content, inputOptions, params) {
  1904. var select = getChildByClass(content, swalClasses.select);
  1905. inputOptions.forEach(function (inputOption) {
  1906. var optionValue = inputOption[0];
  1907. var optionLabel = inputOption[1];
  1908. var option = document.createElement('option');
  1909. option.value = optionValue;
  1910. option.innerHTML = optionLabel;
  1911. if (params.inputValue.toString() === optionValue.toString()) {
  1912. option.selected = true;
  1913. }
  1914. select.appendChild(option);
  1915. });
  1916. select.focus();
  1917. },
  1918. radio: function radio(content, inputOptions, params) {
  1919. var radio = getChildByClass(content, swalClasses.radio);
  1920. inputOptions.forEach(function (inputOption) {
  1921. var radioValue = inputOption[0];
  1922. var radioLabel = inputOption[1];
  1923. var radioInput = document.createElement('input');
  1924. var radioLabelElement = document.createElement('label');
  1925. radioInput.type = 'radio';
  1926. radioInput.name = swalClasses.radio;
  1927. radioInput.value = radioValue;
  1928. if (params.inputValue.toString() === radioValue.toString()) {
  1929. radioInput.checked = true;
  1930. }
  1931. var label = document.createElement('span');
  1932. label.innerHTML = radioLabel;
  1933. label.className = swalClasses.label;
  1934. radioLabelElement.appendChild(radioInput);
  1935. radioLabelElement.appendChild(label);
  1936. radio.appendChild(radioLabelElement);
  1937. });
  1938. var radios = radio.querySelectorAll('input');
  1939. if (radios.length) {
  1940. radios[0].focus();
  1941. }
  1942. }
  1943. /**
  1944. * Converts `inputOptions` into an array of `[value, label]`s
  1945. * @param inputOptions
  1946. */
  1947. };
  1948. var formatInputOptions = function formatInputOptions(inputOptions) {
  1949. var result = [];
  1950. if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
  1951. inputOptions.forEach(function (value, key) {
  1952. result.push([key, value]);
  1953. });
  1954. } else {
  1955. Object.keys(inputOptions).forEach(function (key) {
  1956. result.push([key, inputOptions[key]]);
  1957. });
  1958. }
  1959. return result;
  1960. };
  1961. var handleConfirmButtonClick = function handleConfirmButtonClick(instance, innerParams) {
  1962. instance.disableButtons();
  1963. if (innerParams.input) {
  1964. handleConfirmWithInput(instance, innerParams);
  1965. } else {
  1966. confirm(instance, innerParams, true);
  1967. }
  1968. };
  1969. var handleCancelButtonClick = function handleCancelButtonClick(instance, dismissWith) {
  1970. instance.disableButtons();
  1971. dismissWith(DismissReason.cancel);
  1972. };
  1973. var handleConfirmWithInput = function handleConfirmWithInput(instance, innerParams) {
  1974. var inputValue = getInputValue(instance, innerParams);
  1975. if (innerParams.inputValidator) {
  1976. instance.disableInput();
  1977. var validationPromise = Promise.resolve().then(function () {
  1978. return innerParams.inputValidator(inputValue, innerParams.validationMessage);
  1979. });
  1980. validationPromise.then(function (validationMessage) {
  1981. instance.enableButtons();
  1982. instance.enableInput();
  1983. if (validationMessage) {
  1984. instance.showValidationMessage(validationMessage);
  1985. } else {
  1986. confirm(instance, innerParams, inputValue);
  1987. }
  1988. });
  1989. } else if (!instance.getInput().checkValidity()) {
  1990. instance.enableButtons();
  1991. instance.showValidationMessage(innerParams.validationMessage);
  1992. } else {
  1993. confirm(instance, innerParams, inputValue);
  1994. }
  1995. };
  1996. var succeedWith = function succeedWith(instance, value) {
  1997. instance.closePopup({
  1998. value: value
  1999. });
  2000. };
  2001. var confirm = function confirm(instance, innerParams, value) {
  2002. if (innerParams.showLoaderOnConfirm) {
  2003. showLoading(); // TODO: make showLoading an *instance* method
  2004. }
  2005. if (innerParams.preConfirm) {
  2006. instance.resetValidationMessage();
  2007. var preConfirmPromise = Promise.resolve().then(function () {
  2008. return innerParams.preConfirm(value, innerParams.validationMessage);
  2009. });
  2010. preConfirmPromise.then(function (preConfirmValue) {
  2011. if (isVisible(getValidationMessage()) || preConfirmValue === false) {
  2012. instance.hideLoading();
  2013. } else {
  2014. succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
  2015. }
  2016. });
  2017. } else {
  2018. succeedWith(instance, value);
  2019. }
  2020. };
  2021. var getInputValue = function getInputValue(instance, innerParams) {
  2022. var input = instance.getInput();
  2023. if (!input) {
  2024. return null;
  2025. }
  2026. switch (innerParams.input) {
  2027. case 'checkbox':
  2028. return getCheckboxValue(input);
  2029. case 'radio':
  2030. return getRadioValue(input);
  2031. case 'file':
  2032. return getFileValue(input);
  2033. default:
  2034. return innerParams.inputAutoTrim ? input.value.trim() : input.value;
  2035. }
  2036. };
  2037. var getCheckboxValue = function getCheckboxValue(input) {
  2038. return input.checked ? 1 : 0;
  2039. };
  2040. var getRadioValue = function getRadioValue(input) {
  2041. return input.checked ? input.value : null;
  2042. };
  2043. var getFileValue = function getFileValue(input) {
  2044. return input.files.length ? input.files[0] : null;
  2045. };
  2046. var addKeydownHandler = function addKeydownHandler(instance, globalState, innerParams, dismissWith) {
  2047. if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
  2048. globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
  2049. capture: globalState.keydownListenerCapture
  2050. });
  2051. globalState.keydownHandlerAdded = false;
  2052. }
  2053. if (!innerParams.toast) {
  2054. globalState.keydownHandler = function (e) {
  2055. return keydownHandler(instance, e, innerParams, dismissWith);
  2056. };
  2057. globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
  2058. globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
  2059. globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
  2060. capture: globalState.keydownListenerCapture
  2061. });
  2062. globalState.keydownHandlerAdded = true;
  2063. }
  2064. }; // Focus handling
  2065. var setFocus = function setFocus(innerParams, index, increment) {
  2066. var focusableElements = getFocusableElements(); // search for visible elements and select the next possible match
  2067. for (var i = 0; i < focusableElements.length; i++) {
  2068. index = index + increment; // rollover to first item
  2069. if (index === focusableElements.length) {
  2070. index = 0; // go to last item
  2071. } else if (index === -1) {
  2072. index = focusableElements.length - 1;
  2073. }
  2074. return focusableElements[index].focus();
  2075. } // no visible focusable elements, focus the popup
  2076. getPopup().focus();
  2077. };
  2078. var arrowKeys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Left', 'Right', 'Up', 'Down' // IE11
  2079. ];
  2080. var escKeys = ['Escape', 'Esc' // IE11
  2081. ];
  2082. var keydownHandler = function keydownHandler(instance, e, innerParams, dismissWith) {
  2083. if (innerParams.stopKeydownPropagation) {
  2084. e.stopPropagation();
  2085. } // ENTER
  2086. if (e.key === 'Enter') {
  2087. handleEnter(instance, e, innerParams); // TAB
  2088. } else if (e.key === 'Tab') {
  2089. handleTab(e, innerParams); // ARROWS - switch focus between buttons
  2090. } else if (arrowKeys.indexOf(e.key) !== -1) {
  2091. handleArrows(); // ESC
  2092. } else if (escKeys.indexOf(e.key) !== -1) {
  2093. handleEsc(e, innerParams, dismissWith);
  2094. }
  2095. };
  2096. var handleEnter = function handleEnter(instance, e, innerParams) {
  2097. // #720 #721
  2098. if (e.isComposing) {
  2099. return;
  2100. }
  2101. if (e.target && instance.getInput() && e.target.outerHTML === instance.getInput().outerHTML) {
  2102. if (['textarea', 'file'].indexOf(innerParams.input) !== -1) {
  2103. return; // do not submit
  2104. }
  2105. clickConfirm();
  2106. e.preventDefault();
  2107. }
  2108. };
  2109. var handleTab = function handleTab(e, innerParams) {
  2110. var targetElement = e.target;
  2111. var focusableElements = getFocusableElements();
  2112. var btnIndex = -1;
  2113. for (var i = 0; i < focusableElements.length; i++) {
  2114. if (targetElement === focusableElements[i]) {
  2115. btnIndex = i;
  2116. break;
  2117. }
  2118. }
  2119. if (!e.shiftKey) {
  2120. // Cycle to the next button
  2121. setFocus(innerParams, btnIndex, 1);
  2122. } else {
  2123. // Cycle to the prev button
  2124. setFocus(innerParams, btnIndex, -1);
  2125. }
  2126. e.stopPropagation();
  2127. e.preventDefault();
  2128. };
  2129. var handleArrows = function handleArrows() {
  2130. var confirmButton = getConfirmButton();
  2131. var cancelButton = getCancelButton(); // focus Cancel button if Confirm button is currently focused
  2132. if (document.activeElement === confirmButton && isVisible(cancelButton)) {
  2133. cancelButton.focus(); // and vice versa
  2134. } else if (document.activeElement === cancelButton && isVisible(confirmButton)) {
  2135. confirmButton.focus();
  2136. }
  2137. };
  2138. var handleEsc = function handleEsc(e, innerParams, dismissWith) {
  2139. if (callIfFunction(innerParams.allowEscapeKey)) {
  2140. e.preventDefault();
  2141. dismissWith(DismissReason.esc);
  2142. }
  2143. };
  2144. var handlePopupClick = function handlePopupClick(domCache, innerParams, dismissWith) {
  2145. if (innerParams.toast) {
  2146. handleToastClick(domCache, innerParams, dismissWith);
  2147. } else {
  2148. // Ignore click events that had mousedown on the popup but mouseup on the container
  2149. // This can happen when the user drags a slider
  2150. handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup
  2151. handleContainerMousedown(domCache);
  2152. handleModalClick(domCache, innerParams, dismissWith);
  2153. }
  2154. };
  2155. var handleToastClick = function handleToastClick(domCache, innerParams, dismissWith) {
  2156. // Closing toast by internal click
  2157. domCache.popup.onclick = function () {
  2158. if (innerParams.showConfirmButton || innerParams.showCancelButton || innerParams.showCloseButton || innerParams.input) {
  2159. return;
  2160. }
  2161. dismissWith(DismissReason.close);
  2162. };
  2163. };
  2164. var ignoreOutsideClick = false;
  2165. var handleModalMousedown = function handleModalMousedown(domCache) {
  2166. domCache.popup.onmousedown = function () {
  2167. domCache.container.onmouseup = function (e) {
  2168. domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't
  2169. // have any other direct children aside of the popup
  2170. if (e.target === domCache.container) {
  2171. ignoreOutsideClick = true;
  2172. }
  2173. };
  2174. };
  2175. };
  2176. var handleContainerMousedown = function handleContainerMousedown(domCache) {
  2177. domCache.container.onmousedown = function () {
  2178. domCache.popup.onmouseup = function (e) {
  2179. domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup
  2180. if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
  2181. ignoreOutsideClick = true;
  2182. }
  2183. };
  2184. };
  2185. };
  2186. var handleModalClick = function handleModalClick(domCache, innerParams, dismissWith) {
  2187. domCache.container.onclick = function (e) {
  2188. if (ignoreOutsideClick) {
  2189. ignoreOutsideClick = false;
  2190. return;
  2191. }
  2192. if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
  2193. dismissWith(DismissReason.backdrop);
  2194. }
  2195. };
  2196. };
  2197. function _main(userParams) {
  2198. showWarningsForParams(userParams); // Check if there is another Swal closing
  2199. if (getPopup() && globalState.swalCloseEventFinishedCallback) {
  2200. globalState.swalCloseEventFinishedCallback();
  2201. delete globalState.swalCloseEventFinishedCallback;
  2202. } // Check if there is a swal disposal defer timer
  2203. if (globalState.deferDisposalTimer) {
  2204. clearTimeout(globalState.deferDisposalTimer);
  2205. delete globalState.deferDisposalTimer;
  2206. }
  2207. var innerParams = _extends({}, defaultParams, userParams);
  2208. setParameters(innerParams);
  2209. Object.freeze(innerParams); // clear the previous timer
  2210. if (globalState.timeout) {
  2211. globalState.timeout.stop();
  2212. delete globalState.timeout;
  2213. } // clear the restore focus timeout
  2214. clearTimeout(globalState.restoreFocusTimeout);
  2215. var domCache = populateDomCache(this);
  2216. render(this, innerParams);
  2217. privateProps.innerParams.set(this, innerParams);
  2218. return swalPromise(this, domCache, innerParams);
  2219. }
  2220. var swalPromise = function swalPromise(instance, domCache, innerParams) {
  2221. return new Promise(function (resolve) {
  2222. // functions to handle all closings/dismissals
  2223. var dismissWith = function dismissWith(dismiss) {
  2224. instance.closePopup({
  2225. dismiss: dismiss
  2226. });
  2227. };
  2228. privateMethods.swalPromiseResolve.set(instance, resolve);
  2229. setupTimer(globalState, innerParams, dismissWith);
  2230. domCache.confirmButton.onclick = function () {
  2231. return handleConfirmButtonClick(instance, innerParams);
  2232. };
  2233. domCache.cancelButton.onclick = function () {
  2234. return handleCancelButtonClick(instance, dismissWith);
  2235. };
  2236. domCache.closeButton.onclick = function () {
  2237. return dismissWith(DismissReason.close);
  2238. };
  2239. handlePopupClick(domCache, innerParams, dismissWith);
  2240. addKeydownHandler(instance, globalState, innerParams, dismissWith);
  2241. if (innerParams.toast && (innerParams.input || innerParams.footer || innerParams.showCloseButton)) {
  2242. addClass(document.body, swalClasses['toast-column']);
  2243. } else {
  2244. removeClass(document.body, swalClasses['toast-column']);
  2245. }
  2246. handleInputOptionsAndValue(instance, innerParams);
  2247. openPopup(innerParams);
  2248. initFocus(domCache, innerParams); // Scroll container to top on open (#1247)
  2249. domCache.container.scrollTop = 0;
  2250. });
  2251. };
  2252. var populateDomCache = function populateDomCache(instance) {
  2253. var domCache = {
  2254. popup: getPopup(),
  2255. container: getContainer(),
  2256. content: getContent(),
  2257. actions: getActions(),
  2258. confirmButton: getConfirmButton(),
  2259. cancelButton: getCancelButton(),
  2260. closeButton: getCloseButton(),
  2261. validationMessage: getValidationMessage(),
  2262. progressSteps: getProgressSteps()
  2263. };
  2264. privateProps.domCache.set(instance, domCache);
  2265. return domCache;
  2266. };
  2267. var setupTimer = function setupTimer(globalState$$1, innerParams, dismissWith) {
  2268. if (innerParams.timer) {
  2269. globalState$$1.timeout = new Timer(function () {
  2270. dismissWith('timer');
  2271. delete globalState$$1.timeout;
  2272. }, innerParams.timer);
  2273. }
  2274. };
  2275. var initFocus = function initFocus(domCache, innerParams) {
  2276. if (innerParams.toast) {
  2277. return;
  2278. }
  2279. if (!callIfFunction(innerParams.allowEnterKey)) {
  2280. return blurActiveElement();
  2281. }
  2282. if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {
  2283. return domCache.cancelButton.focus();
  2284. }
  2285. if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {
  2286. return domCache.confirmButton.focus();
  2287. }
  2288. setFocus(innerParams, -1, 1);
  2289. };
  2290. var blurActiveElement = function blurActiveElement() {
  2291. if (document.activeElement && typeof document.activeElement.blur === 'function') {
  2292. document.activeElement.blur();
  2293. }
  2294. };
  2295. /**
  2296. * Updates popup parameters.
  2297. */
  2298. function update(params) {
  2299. var validUpdatableParams = {}; // assign valid params from `params` to `defaults`
  2300. Object.keys(params).forEach(function (param) {
  2301. if (Swal.isUpdatableParameter(param)) {
  2302. validUpdatableParams[param] = params[param];
  2303. } else {
  2304. warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js"));
  2305. }
  2306. });
  2307. var innerParams = privateProps.innerParams.get(this);
  2308. var updatedParams = _extends({}, innerParams, validUpdatableParams);
  2309. render(this, updatedParams);
  2310. privateProps.innerParams.set(this, updatedParams);
  2311. Object.defineProperties(this, {
  2312. params: {
  2313. value: _extends({}, this.params, params),
  2314. writable: false,
  2315. enumerable: true
  2316. }
  2317. });
  2318. }
  2319. var instanceMethods = Object.freeze({
  2320. hideLoading: hideLoading,
  2321. disableLoading: hideLoading,
  2322. getInput: getInput$1,
  2323. close: close,
  2324. closePopup: close,
  2325. closeModal: close,
  2326. closeToast: close,
  2327. enableButtons: enableButtons,
  2328. disableButtons: disableButtons,
  2329. enableConfirmButton: enableConfirmButton,
  2330. disableConfirmButton: disableConfirmButton,
  2331. enableInput: enableInput,
  2332. disableInput: disableInput,
  2333. showValidationMessage: showValidationMessage,
  2334. resetValidationMessage: resetValidationMessage$1,
  2335. getProgressSteps: getProgressSteps$1,
  2336. setProgressSteps: setProgressSteps,
  2337. showProgressSteps: showProgressSteps,
  2338. hideProgressSteps: hideProgressSteps,
  2339. _main: _main,
  2340. update: update
  2341. });
  2342. var currentInstance; // SweetAlert constructor
  2343. function SweetAlert() {
  2344. // Prevent run in Node env
  2345. /* istanbul ignore if */
  2346. if (typeof window === 'undefined') {
  2347. return;
  2348. } // Check for the existence of Promise
  2349. /* istanbul ignore if */
  2350. if (typeof Promise === 'undefined') {
  2351. 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)');
  2352. }
  2353. currentInstance = this;
  2354. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2355. args[_key] = arguments[_key];
  2356. }
  2357. var outerParams = Object.freeze(this.constructor.argsToParams(args));
  2358. Object.defineProperties(this, {
  2359. params: {
  2360. value: outerParams,
  2361. writable: false,
  2362. enumerable: true,
  2363. configurable: true
  2364. }
  2365. });
  2366. var promise = this._main(this.params);
  2367. privateProps.promise.set(this, promise);
  2368. } // `catch` cannot be the name of a module export, so we define our thenable methods here instead
  2369. SweetAlert.prototype.then = function (onFulfilled) {
  2370. var promise = privateProps.promise.get(this);
  2371. return promise.then(onFulfilled);
  2372. };
  2373. SweetAlert.prototype["finally"] = function (onFinally) {
  2374. var promise = privateProps.promise.get(this);
  2375. return promise["finally"](onFinally);
  2376. }; // Assign instance methods from src/instanceMethods/*.js to prototype
  2377. _extends(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor
  2378. _extends(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility
  2379. Object.keys(instanceMethods).forEach(function (key) {
  2380. SweetAlert[key] = function () {
  2381. if (currentInstance) {
  2382. var _currentInstance;
  2383. return (_currentInstance = currentInstance)[key].apply(_currentInstance, arguments);
  2384. }
  2385. };
  2386. });
  2387. SweetAlert.DismissReason = DismissReason;
  2388. SweetAlert.version = '8.17.6';
  2389. var Swal = SweetAlert;
  2390. Swal["default"] = Swal;
  2391. return Swal;
  2392. })));
  2393. if (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}