sweetalert2.js 100 KB

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