sweetalert2.js 97 KB

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