sweetalert2.js 100 KB

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