12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401 |
- (function(global){
- //
- // Check for native Promise and it has correct interface
- //
- var NativePromise = global['Promise'];
- var nativePromiseSupported =
- NativePromise &&
- // Some of these methods are missing from
- // Firefox/Chrome experimental implementations
- 'resolve' in NativePromise &&
- 'reject' in NativePromise &&
- 'all' in NativePromise &&
- 'race' in NativePromise &&
- // Older version of the spec had a resolver object
- // as the arg rather than a function
- (function(){
- var resolve;
- new NativePromise(function(r){ resolve = r; });
- return typeof resolve === 'function';
- })();
- //
- // export if necessary
- //
- if (typeof exports !== 'undefined' && exports)
- {
- // node.js
- exports.Promise = nativePromiseSupported ? NativePromise : Promise;
- exports.Polyfill = Promise;
- }
- else
- {
- // AMD
- if (typeof define == 'function' && define.amd)
- {
- define(function(){
- return nativePromiseSupported ? NativePromise : Promise;
- });
- }
- else
- {
- // in browser add to global
- if (!nativePromiseSupported)
- global['Promise'] = Promise;
- }
- }
- //
- // Polyfill
- //
- var PENDING = 'pending';
- var SEALED = 'sealed';
- var FULFILLED = 'fulfilled';
- var REJECTED = 'rejected';
- var NOOP = function(){};
- function isArray(value) {
- return Object.prototype.toString.call(value) === '[object Array]';
- }
- // async calls
- var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout;
- var asyncQueue = [];
- var asyncTimer;
- function asyncFlush(){
- // run promise callbacks
- for (var i = 0; i < asyncQueue.length; i++)
- asyncQueue[i][0](asyncQueue[i][1]);
- // reset async asyncQueue
- asyncQueue = [];
- asyncTimer = false;
- }
- function asyncCall(callback, arg){
- asyncQueue.push([callback, arg]);
- if (!asyncTimer)
- {
- asyncTimer = true;
- asyncSetTimer(asyncFlush, 0);
- }
- }
- function invokeResolver(resolver, promise) {
- function resolvePromise(value) {
- resolve(promise, value);
- }
- function rejectPromise(reason) {
- reject(promise, reason);
- }
- try {
- resolver(resolvePromise, rejectPromise);
- } catch(e) {
- rejectPromise(e);
- }
- }
- function invokeCallback(subscriber){
- var owner = subscriber.owner;
- var settled = owner.state_;
- var value = owner.data_;
- var callback = subscriber[settled];
- var promise = subscriber.then;
- if (typeof callback === 'function')
- {
- settled = FULFILLED;
- try {
- value = callback(value);
- } catch(e) {
- reject(promise, e);
- }
- }
- if (!handleThenable(promise, value))
- {
- if (settled === FULFILLED)
- resolve(promise, value);
- if (settled === REJECTED)
- reject(promise, value);
- }
- }
- function handleThenable(promise, value) {
- var resolved;
- try {
- if (promise === value)
- throw new TypeError('A promises callback cannot return that same promise.');
- if (value && (typeof value === 'function' || typeof value === 'object'))
- {
- var then = value.then; // then should be retrived only once
- if (typeof then === 'function')
- {
- then.call(value, function(val){
- if (!resolved)
- {
- resolved = true;
- if (value !== val)
- resolve(promise, val);
- else
- fulfill(promise, val);
- }
- }, function(reason){
- if (!resolved)
- {
- resolved = true;
- reject(promise, reason);
- }
- });
- return true;
- }
- }
- } catch (e) {
- if (!resolved)
- reject(promise, e);
- return true;
- }
- return false;
- }
- function resolve(promise, value){
- if (promise === value || !handleThenable(promise, value))
- fulfill(promise, value);
- }
- function fulfill(promise, value){
- if (promise.state_ === PENDING)
- {
- promise.state_ = SEALED;
- promise.data_ = value;
- asyncCall(publishFulfillment, promise);
- }
- }
- function reject(promise, reason){
- if (promise.state_ === PENDING)
- {
- promise.state_ = SEALED;
- promise.data_ = reason;
- asyncCall(publishRejection, promise);
- }
- }
- function publish(promise) {
- var callbacks = promise.then_;
- promise.then_ = undefined;
- for (var i = 0; i < callbacks.length; i++) {
- invokeCallback(callbacks[i]);
- }
- }
- function publishFulfillment(promise){
- promise.state_ = FULFILLED;
- publish(promise);
- }
- function publishRejection(promise){
- promise.state_ = REJECTED;
- publish(promise);
- }
- /**
- * @class
- */
- function Promise(resolver){
- if (typeof resolver !== 'function')
- throw new TypeError('Promise constructor takes a function argument');
- if (this instanceof Promise === false)
- throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.');
- this.then_ = [];
- invokeResolver(resolver, this);
- }
- Promise.prototype = {
- constructor: Promise,
- state_: PENDING,
- then_: null,
- data_: undefined,
- then: function(onFulfillment, onRejection){
- var subscriber = {
- owner: this,
- then: new this.constructor(NOOP),
- fulfilled: onFulfillment,
- rejected: onRejection
- };
- if (this.state_ === FULFILLED || this.state_ === REJECTED)
- {
- // already resolved, call callback async
- asyncCall(invokeCallback, subscriber);
- }
- else
- {
- // subscribe
- this.then_.push(subscriber);
- }
- return subscriber.then;
- },
- 'catch': function(onRejection) {
- return this.then(null, onRejection);
- }
- };
- Promise.all = function(promises){
- var Class = this;
- if (!isArray(promises))
- throw new TypeError('You must pass an array to Promise.all().');
- return new Class(function(resolve, reject){
- var results = [];
- var remaining = 0;
- function resolver(index){
- remaining++;
- return function(value){
- results[index] = value;
- if (!--remaining)
- resolve(results);
- };
- }
- for (var i = 0, promise; i < promises.length; i++)
- {
- promise = promises[i];
- if (promise && typeof promise.then === 'function')
- promise.then(resolver(i), reject);
- else
- results[i] = promise;
- }
- if (!remaining)
- resolve(results);
- });
- };
- Promise.race = function(promises){
- var Class = this;
- if (!isArray(promises))
- throw new TypeError('You must pass an array to Promise.race().');
- return new Class(function(resolve, reject) {
- for (var i = 0, promise; i < promises.length; i++)
- {
- promise = promises[i];
- if (promise && typeof promise.then === 'function')
- promise.then(resolve, reject);
- else
- resolve(promise);
- }
- });
- };
- Promise.resolve = function(value){
- var Class = this;
- if (value && typeof value === 'object' && value.constructor === Class)
- return value;
- return new Class(function(resolve){
- resolve(value);
- });
- };
- Promise.reject = function(reason){
- var Class = this;
- return new Class(function(resolve, reject){
- reject(reason);
- });
- };
- })(typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : typeof self != 'undefined' ? self : this);
- /*!
- * sweetalert2 v9.8.2
- * Released under the MIT License.
- */
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = global || self, global.Sweetalert2 = factory());
- }(this, function () { 'use strict';
- function _typeof(obj) {
- "@babel/helpers - typeof";
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function (obj) {
- return typeof obj;
- };
- } else {
- _typeof = function (obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
- }
- return _typeof(obj);
- }
- function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
- function _extends() {
- _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- if (superClass) _setPrototypeOf(subClass, superClass);
- }
- function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- function isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
- try {
- Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
- }
- function _construct(Parent, args, Class) {
- if (isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
- }
- return _assertThisInitialized(self);
- }
- function _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = _getPrototypeOf(object);
- if (object === null) break;
- }
- return object;
- }
- function _get(target, property, receiver) {
- if (typeof Reflect !== "undefined" && Reflect.get) {
- _get = Reflect.get;
- } else {
- _get = function _get(target, property, receiver) {
- var base = _superPropBase(target, property);
- if (!base) return;
- var desc = Object.getOwnPropertyDescriptor(base, property);
- if (desc.get) {
- return desc.get.call(receiver);
- }
- return desc.value;
- };
- }
- return _get(target, property, receiver || target);
- }
- var consolePrefix = 'SweetAlert2:';
- /**
- * Filter the unique values into a new array
- * @param arr
- */
- var uniqueArray = function uniqueArray(arr) {
- var result = [];
- for (var i = 0; i < arr.length; i++) {
- if (result.indexOf(arr[i]) === -1) {
- result.push(arr[i]);
- }
- }
- return result;
- };
- /**
- * Capitalize the first letter of a string
- * @param str
- */
- var capitalizeFirstLetter = function capitalizeFirstLetter(str) {
- return str.charAt(0).toUpperCase() + str.slice(1);
- };
- /**
- * Returns the array ob object values (Object.values isn't supported in IE11)
- * @param obj
- */
- var objectValues = function objectValues(obj) {
- return Object.keys(obj).map(function (key) {
- return obj[key];
- });
- };
- /**
- * Convert NodeList to Array
- * @param nodeList
- */
- var toArray = function toArray(nodeList) {
- return Array.prototype.slice.call(nodeList);
- };
- /**
- * Standardise console warnings
- * @param message
- */
- var warn = function warn(message) {
- console.warn("".concat(consolePrefix, " ").concat(message));
- };
- /**
- * Standardise console errors
- * @param message
- */
- var error = function error(message) {
- console.error("".concat(consolePrefix, " ").concat(message));
- };
- /**
- * Private global state for `warnOnce`
- * @type {Array}
- * @private
- */
- var previousWarnOnceMessages = [];
- /**
- * Show a console warning, but only if it hasn't already been shown
- * @param message
- */
- var warnOnce = function warnOnce(message) {
- if (!(previousWarnOnceMessages.indexOf(message) !== -1)) {
- previousWarnOnceMessages.push(message);
- warn(message);
- }
- };
- /**
- * Show a one-time console warning about deprecated params/methods
- */
- var warnAboutDepreation = function warnAboutDepreation(deprecatedParam, useInstead) {
- warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead."));
- };
- /**
- * If `arg` is a function, call it (with no arguments or context) and return the result.
- * Otherwise, just pass the value through
- * @param arg
- */
- var callIfFunction = function callIfFunction(arg) {
- return typeof arg === 'function' ? arg() : arg;
- };
- var isPromise = function isPromise(arg) {
- return arg && Promise.resolve(arg) === arg;
- };
- var DismissReason = Object.freeze({
- cancel: 'cancel',
- backdrop: 'backdrop',
- close: 'close',
- esc: 'esc',
- timer: 'timer'
- });
- var isJqueryElement = function isJqueryElement(elem) {
- return _typeof(elem) === 'object' && elem.jquery;
- };
- var isElement = function isElement(elem) {
- return elem instanceof Element || isJqueryElement(elem);
- };
- var argsToParams = function argsToParams(args) {
- var params = {};
- if (_typeof(args[0]) === 'object' && !isElement(args[0])) {
- _extends(params, args[0]);
- } else {
- ['title', 'html', 'icon'].forEach(function (name, index) {
- var arg = args[index];
- if (typeof arg === 'string' || isElement(arg)) {
- params[name] = arg;
- } else if (arg !== undefined) {
- error("Unexpected type of ".concat(name, "! Expected \"string\" or \"Element\", got ").concat(_typeof(arg)));
- }
- });
- }
- return params;
- };
- var swalPrefix = 'swal2-';
- var prefix = function prefix(items) {
- var result = {};
- for (var i in items) {
- result[items[i]] = swalPrefix + items[i];
- }
- return result;
- };
- var swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'toast-column', 'show', 'hide', 'close', 'title', 'header', 'content', 'html-container', 'actions', 'confirm', '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', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']);
- var iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
- var getContainer = function getContainer() {
- return document.body.querySelector(".".concat(swalClasses.container));
- };
- var elementBySelector = function elementBySelector(selectorString) {
- var container = getContainer();
- return container ? container.querySelector(selectorString) : null;
- };
- var elementByClass = function elementByClass(className) {
- return elementBySelector(".".concat(className));
- };
- var getPopup = function getPopup() {
- return elementByClass(swalClasses.popup);
- };
- var getIcons = function getIcons() {
- var popup = getPopup();
- return toArray(popup.querySelectorAll(".".concat(swalClasses.icon)));
- };
- var getIcon = function getIcon() {
- var visibleIcon = getIcons().filter(function (icon) {
- return isVisible(icon);
- });
- return visibleIcon.length ? visibleIcon[0] : null;
- };
- var getTitle = function getTitle() {
- return elementByClass(swalClasses.title);
- };
- var getContent = function getContent() {
- return elementByClass(swalClasses.content);
- };
- var getHtmlContainer = function getHtmlContainer() {
- return elementByClass(swalClasses['html-container']);
- };
- var getImage = function getImage() {
- return elementByClass(swalClasses.image);
- };
- var getProgressSteps = function getProgressSteps() {
- return elementByClass(swalClasses['progress-steps']);
- };
- var getValidationMessage = function getValidationMessage() {
- return elementByClass(swalClasses['validation-message']);
- };
- var getConfirmButton = function getConfirmButton() {
- return elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm));
- };
- var getCancelButton = function getCancelButton() {
- return elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel));
- };
- var getActions = function getActions() {
- return elementByClass(swalClasses.actions);
- };
- var getHeader = function getHeader() {
- return elementByClass(swalClasses.header);
- };
- var getFooter = function getFooter() {
- return elementByClass(swalClasses.footer);
- };
- var getTimerProgressBar = function getTimerProgressBar() {
- return elementByClass(swalClasses['timer-progress-bar']);
- };
- var getCloseButton = function getCloseButton() {
- return elementByClass(swalClasses.close);
- }; // https://github.com/jkup/focusable/blob/master/index.js
- var focusable = "\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex=\"0\"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n";
- var getFocusableElements = function getFocusableElements() {
- var focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex
- .sort(function (a, b) {
- a = parseInt(a.getAttribute('tabindex'));
- b = parseInt(b.getAttribute('tabindex'));
- if (a > b) {
- return 1;
- } else if (a < b) {
- return -1;
- }
- return 0;
- });
- var otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(function (el) {
- return el.getAttribute('tabindex') !== '-1';
- });
- return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(function (el) {
- return isVisible(el);
- });
- };
- var isModal = function isModal() {
- return !isToast() && !document.body.classList.contains(swalClasses['no-backdrop']);
- };
- var isToast = function isToast() {
- return document.body.classList.contains(swalClasses['toast-shown']);
- };
- var isLoading = function isLoading() {
- return getPopup().hasAttribute('data-loading');
- };
- var states = {
- previousBodyPadding: null
- };
- var hasClass = function hasClass(elem, className) {
- if (!className) {
- return false;
- }
- var classList = className.split(/\s+/);
- for (var i = 0; i < classList.length; i++) {
- if (!elem.classList.contains(classList[i])) {
- return false;
- }
- }
- return true;
- };
- var removeCustomClasses = function removeCustomClasses(elem, params) {
- toArray(elem.classList).forEach(function (className) {
- if (!(objectValues(swalClasses).indexOf(className) !== -1) && !(objectValues(iconTypes).indexOf(className) !== -1) && !(objectValues(params.showClass).indexOf(className) !== -1)) {
- elem.classList.remove(className);
- }
- });
- };
- var applyCustomClass = function applyCustomClass(elem, params, className) {
- removeCustomClasses(elem, params);
- if (params.customClass && params.customClass[className]) {
- if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
- return warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(_typeof(params.customClass[className]), "\""));
- }
- addClass(elem, params.customClass[className]);
- }
- };
- function getInput(content, inputType) {
- if (!inputType) {
- return null;
- }
- switch (inputType) {
- case 'select':
- case 'textarea':
- case 'file':
- return getChildByClass(content, swalClasses[inputType]);
- case 'checkbox':
- return content.querySelector(".".concat(swalClasses.checkbox, " input"));
- case 'radio':
- return content.querySelector(".".concat(swalClasses.radio, " input:checked")) || content.querySelector(".".concat(swalClasses.radio, " input:first-child"));
- case 'range':
- return content.querySelector(".".concat(swalClasses.range, " input"));
- default:
- return getChildByClass(content, swalClasses.input);
- }
- }
- var focusInput = function focusInput(input) {
- input.focus(); // place cursor at end of text in text input
- if (input.type !== 'file') {
- // http://stackoverflow.com/a/2345915
- var val = input.value;
- input.value = '';
- input.value = val;
- }
- };
- var toggleClass = function toggleClass(target, classList, condition) {
- if (!target || !classList) {
- return;
- }
- if (typeof classList === 'string') {
- classList = classList.split(/\s+/).filter(Boolean);
- }
- classList.forEach(function (className) {
- if (target.forEach) {
- target.forEach(function (elem) {
- condition ? elem.classList.add(className) : elem.classList.remove(className);
- });
- } else {
- condition ? target.classList.add(className) : target.classList.remove(className);
- }
- });
- };
- var addClass = function addClass(target, classList) {
- toggleClass(target, classList, true);
- };
- var removeClass = function removeClass(target, classList) {
- toggleClass(target, classList, false);
- };
- var getChildByClass = function getChildByClass(elem, className) {
- for (var i = 0; i < elem.childNodes.length; i++) {
- if (hasClass(elem.childNodes[i], className)) {
- return elem.childNodes[i];
- }
- }
- };
- var applyNumericalStyle = function applyNumericalStyle(elem, property, value) {
- if (value || parseInt(value) === 0) {
- elem.style[property] = typeof value === 'number' ? "".concat(value, "px") : value;
- } else {
- elem.style.removeProperty(property);
- }
- };
- var show = function show(elem) {
- var display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
- elem.style.opacity = '';
- elem.style.display = display;
- };
- var hide = function hide(elem) {
- elem.style.opacity = '';
- elem.style.display = 'none';
- };
- var toggle = function toggle(elem, condition, display) {
- condition ? show(elem, display) : hide(elem);
- }; // borrowed from jquery $(elem).is(':visible') implementation
- var isVisible = function isVisible(elem) {
- return !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
- };
- /* istanbul ignore next */
- var isScrollable = function isScrollable(elem) {
- return !!(elem.scrollHeight > elem.clientHeight);
- }; // borrowed from https://stackoverflow.com/a/46352119
- var hasCssAnimation = function hasCssAnimation(elem) {
- var style = window.getComputedStyle(elem);
- var animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
- var transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
- return animDuration > 0 || transDuration > 0;
- };
- var contains = function contains(haystack, needle) {
- if (typeof haystack.contains === 'function') {
- return haystack.contains(needle);
- }
- };
- var animateTimerProgressBar = function animateTimerProgressBar(timer) {
- var reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
- var timerProgressBar = getTimerProgressBar();
- if (isVisible(timerProgressBar)) {
- if (reset) {
- timerProgressBar.style.transition = 'none';
- timerProgressBar.style.width = '100%';
- }
- setTimeout(function () {
- timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear");
- timerProgressBar.style.width = '0%';
- }, 10);
- }
- };
- var stopTimerProgressBar = function stopTimerProgressBar() {
- var timerProgressBar = getTimerProgressBar();
- var timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
- timerProgressBar.style.removeProperty('transition');
- timerProgressBar.style.width = '100%';
- var timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
- var timerProgressBarPercent = parseInt(timerProgressBarWidth / timerProgressBarFullWidth * 100);
- timerProgressBar.style.removeProperty('transition');
- timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%");
- };
- // Detect Node env
- var isNodeEnv = function isNodeEnv() {
- return typeof window === 'undefined' || typeof document === 'undefined';
- };
- var sweetHTML = "\n <div aria-labelledby=\"".concat(swalClasses.title, "\" aria-describedby=\"").concat(swalClasses.content, "\" class=\"").concat(swalClasses.popup, "\" tabindex=\"-1\">\n <div class=\"").concat(swalClasses.header, "\">\n <ul class=\"").concat(swalClasses['progress-steps'], "\"></ul>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.error, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.question, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.warning, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.info, "\"></div>\n <div class=\"").concat(swalClasses.icon, " ").concat(iconTypes.success, "\"></div>\n <img class=\"").concat(swalClasses.image, "\" />\n <h2 class=\"").concat(swalClasses.title, "\" id=\"").concat(swalClasses.title, "\"></h2>\n <button type=\"button\" class=\"").concat(swalClasses.close, "\"></button>\n </div>\n <div class=\"").concat(swalClasses.content, "\">\n <div id=\"").concat(swalClasses.content, "\" class=\"").concat(swalClasses['html-container'], "\"></div>\n <input class=\"").concat(swalClasses.input, "\" />\n <input type=\"file\" class=\"").concat(swalClasses.file, "\" />\n <div class=\"").concat(swalClasses.range, "\">\n <input type=\"range\" />\n <output></output>\n </div>\n <select class=\"").concat(swalClasses.select, "\"></select>\n <div class=\"").concat(swalClasses.radio, "\"></div>\n <label for=\"").concat(swalClasses.checkbox, "\" class=\"").concat(swalClasses.checkbox, "\">\n <input type=\"checkbox\" />\n <span class=\"").concat(swalClasses.label, "\"></span>\n </label>\n <textarea class=\"").concat(swalClasses.textarea, "\"></textarea>\n <div class=\"").concat(swalClasses['validation-message'], "\" id=\"").concat(swalClasses['validation-message'], "\"></div>\n </div>\n <div class=\"").concat(swalClasses.actions, "\">\n <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'], "\"></div>\n </div>\n").replace(/(^|\n)\s*/g, '');
- var resetOldContainer = function resetOldContainer() {
- var oldContainer = getContainer();
- if (!oldContainer) {
- return false;
- }
- oldContainer.parentNode.removeChild(oldContainer);
- removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
- return true;
- };
- var oldInputVal; // IE11 workaround, see #1109 for details
- var resetValidationMessage = function resetValidationMessage(e) {
- if (Swal.isVisible() && oldInputVal !== e.target.value) {
- Swal.resetValidationMessage();
- }
- oldInputVal = e.target.value;
- };
- var addInputChangeListeners = function addInputChangeListeners() {
- var content = getContent();
- var input = getChildByClass(content, swalClasses.input);
- var file = getChildByClass(content, swalClasses.file);
- var range = content.querySelector(".".concat(swalClasses.range, " input"));
- var rangeOutput = content.querySelector(".".concat(swalClasses.range, " output"));
- var select = getChildByClass(content, swalClasses.select);
- var checkbox = content.querySelector(".".concat(swalClasses.checkbox, " input"));
- var textarea = getChildByClass(content, swalClasses.textarea);
- input.oninput = resetValidationMessage;
- file.onchange = resetValidationMessage;
- select.onchange = resetValidationMessage;
- checkbox.onchange = resetValidationMessage;
- textarea.oninput = resetValidationMessage;
- range.oninput = function (e) {
- resetValidationMessage(e);
- rangeOutput.value = range.value;
- };
- range.onchange = function (e) {
- resetValidationMessage(e);
- range.nextSibling.value = range.value;
- };
- };
- var getTarget = function getTarget(target) {
- return typeof target === 'string' ? document.querySelector(target) : target;
- };
- var setupAccessibility = function setupAccessibility(params) {
- var popup = getPopup();
- popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
- popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
- if (!params.toast) {
- popup.setAttribute('aria-modal', 'true');
- }
- };
- var setupRTL = function setupRTL(targetElement) {
- if (window.getComputedStyle(targetElement).direction === 'rtl') {
- addClass(getContainer(), swalClasses.rtl);
- }
- };
- /*
- * Add modal + backdrop to DOM
- */
- var init = function init(params) {
- // Clean up the old popup container if it exists
- var oldContainerExisted = resetOldContainer();
- /* istanbul ignore if */
- if (isNodeEnv()) {
- error('SweetAlert2 requires document to initialize');
- return;
- }
- var container = document.createElement('div');
- container.className = swalClasses.container;
- if (oldContainerExisted) {
- addClass(container, swalClasses['no-transition']);
- }
- container.innerHTML = sweetHTML;
- var targetElement = getTarget(params.target);
- targetElement.appendChild(container);
- setupAccessibility(params);
- setupRTL(targetElement);
- addInputChangeListeners();
- };
- var parseHtmlToContainer = function parseHtmlToContainer(param, target) {
- // DOM element
- if (param instanceof HTMLElement) {
- target.appendChild(param); // Object
- } else if (_typeof(param) === 'object') {
- handleObject(param, target); // Plain string
- } else if (param) {
- target.innerHTML = param;
- }
- };
- var handleObject = function handleObject(param, target) {
- // JQuery element(s)
- if (param.jquery) {
- handleJqueryElem(target, param); // For other objects use their string representation
- } else {
- target.innerHTML = param.toString();
- }
- };
- var handleJqueryElem = function handleJqueryElem(target, elem) {
- target.innerHTML = '';
- if (0 in elem) {
- for (var i = 0; i in elem; i++) {
- target.appendChild(elem[i].cloneNode(true));
- }
- } else {
- target.appendChild(elem.cloneNode(true));
- }
- };
- var animationEndEvent = function () {
- // Prevent run in Node env
- /* istanbul ignore if */
- if (isNodeEnv()) {
- return false;
- }
- var testEl = document.createElement('div');
- var transEndEventNames = {
- WebkitAnimation: 'webkitAnimationEnd',
- OAnimation: 'oAnimationEnd oanimationend',
- animation: 'animationend'
- };
- for (var i in transEndEventNames) {
- if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
- return transEndEventNames[i];
- }
- }
- return false;
- }();
- // https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
- var measureScrollbar = function measureScrollbar() {
- var scrollDiv = document.createElement('div');
- scrollDiv.className = swalClasses['scrollbar-measure'];
- document.body.appendChild(scrollDiv);
- var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
- document.body.removeChild(scrollDiv);
- return scrollbarWidth;
- };
- var renderActions = function renderActions(instance, params) {
- var actions = getActions();
- var confirmButton = getConfirmButton();
- var cancelButton = getCancelButton(); // Actions (buttons) wrapper
- if (!params.showConfirmButton && !params.showCancelButton) {
- hide(actions);
- } // Custom class
- applyCustomClass(actions, params, 'actions'); // Render confirm button
- renderButton(confirmButton, 'confirm', params); // render Cancel Button
- renderButton(cancelButton, 'cancel', params);
- if (params.buttonsStyling) {
- handleButtonsStyling(confirmButton, cancelButton, params);
- } else {
- removeClass([confirmButton, cancelButton], swalClasses.styled);
- confirmButton.style.backgroundColor = confirmButton.style.borderLeftColor = confirmButton.style.borderRightColor = '';
- cancelButton.style.backgroundColor = cancelButton.style.borderLeftColor = cancelButton.style.borderRightColor = '';
- }
- if (params.reverseButtons) {
- confirmButton.parentNode.insertBefore(cancelButton, confirmButton);
- }
- };
- function handleButtonsStyling(confirmButton, cancelButton, params) {
- addClass([confirmButton, cancelButton], swalClasses.styled); // Buttons background colors
- if (params.confirmButtonColor) {
- confirmButton.style.backgroundColor = params.confirmButtonColor;
- }
- if (params.cancelButtonColor) {
- cancelButton.style.backgroundColor = params.cancelButtonColor;
- } // Loading state
- var confirmButtonBackgroundColor = window.getComputedStyle(confirmButton).getPropertyValue('background-color');
- confirmButton.style.borderLeftColor = confirmButtonBackgroundColor;
- confirmButton.style.borderRightColor = confirmButtonBackgroundColor;
- }
- function renderButton(button, buttonType, params) {
- toggle(button, params["show".concat(capitalizeFirstLetter(buttonType), "Button")], 'inline-block');
- button.innerHTML = params["".concat(buttonType, "ButtonText")]; // Set caption text
- button.setAttribute('aria-label', params["".concat(buttonType, "ButtonAriaLabel")]); // ARIA label
- // Add buttons custom classes
- button.className = swalClasses[buttonType];
- applyCustomClass(button, params, "".concat(buttonType, "Button"));
- addClass(button, params["".concat(buttonType, "ButtonClass")]);
- }
- function handleBackdropParam(container, backdrop) {
- if (typeof backdrop === 'string') {
- container.style.background = backdrop;
- } else if (!backdrop) {
- addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
- }
- }
- function handlePositionParam(container, position) {
- if (position in swalClasses) {
- addClass(container, swalClasses[position]);
- } else {
- warn('The "position" parameter is not valid, defaulting to "center"');
- addClass(container, swalClasses.center);
- }
- }
- function handleGrowParam(container, grow) {
- if (grow && typeof grow === 'string') {
- var growClass = "grow-".concat(grow);
- if (growClass in swalClasses) {
- addClass(container, swalClasses[growClass]);
- }
- }
- }
- var renderContainer = function renderContainer(instance, params) {
- var container = getContainer();
- if (!container) {
- return;
- }
- handleBackdropParam(container, params.backdrop);
- if (!params.backdrop && params.allowOutsideClick) {
- warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
- }
- handlePositionParam(container, params.position);
- handleGrowParam(container, params.grow); // Custom class
- applyCustomClass(container, params, 'container'); // Set queue step attribute for getQueueStep() method
- var queueStep = document.body.getAttribute('data-swal2-queue-step');
- if (queueStep) {
- container.setAttribute('data-queue-step', queueStep);
- document.body.removeAttribute('data-swal2-queue-step');
- }
- };
- /**
- * This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has.
- * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
- * This is the approach that Babel will probably take to implement private methods/fields
- * https://github.com/tc39/proposal-private-methods
- * https://github.com/babel/babel/pull/7555
- * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
- * then we can use that language feature.
- */
- var privateProps = {
- promise: new WeakMap(),
- innerParams: new WeakMap(),
- domCache: new WeakMap()
- };
- var inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
- var renderInput = function renderInput(instance, params) {
- var content = getContent();
- var innerParams = privateProps.innerParams.get(instance);
- var rerender = !innerParams || params.input !== innerParams.input;
- inputTypes.forEach(function (inputType) {
- var inputClass = swalClasses[inputType];
- var inputContainer = getChildByClass(content, inputClass); // set attributes
- setAttributes(inputType, params.inputAttributes); // set class
- inputContainer.className = inputClass;
- if (rerender) {
- hide(inputContainer);
- }
- });
- if (params.input) {
- if (rerender) {
- showInput(params);
- } // set custom class
- setCustomClass(params);
- }
- };
- var showInput = function showInput(params) {
- if (!renderInputType[params.input]) {
- return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\""));
- }
- var inputContainer = getInputContainer(params.input);
- var input = renderInputType[params.input](inputContainer, params);
- show(input); // input autofocus
- setTimeout(function () {
- focusInput(input);
- });
- };
- var removeAttributes = function removeAttributes(input) {
- for (var i = 0; i < input.attributes.length; i++) {
- var attrName = input.attributes[i].name;
- if (!(['type', 'value', 'style'].indexOf(attrName) !== -1)) {
- input.removeAttribute(attrName);
- }
- }
- };
- var setAttributes = function setAttributes(inputType, inputAttributes) {
- var input = getInput(getContent(), inputType);
- if (!input) {
- return;
- }
- removeAttributes(input);
- for (var attr in inputAttributes) {
- // Do not set a placeholder for <input type="range">
- // it'll crash Edge, #1298
- if (inputType === 'range' && attr === 'placeholder') {
- continue;
- }
- input.setAttribute(attr, inputAttributes[attr]);
- }
- };
- var setCustomClass = function setCustomClass(params) {
- var inputContainer = getInputContainer(params.input);
- if (params.customClass) {
- addClass(inputContainer, params.customClass.input);
- }
- };
- var setInputPlaceholder = function setInputPlaceholder(input, params) {
- if (!input.placeholder || params.inputPlaceholder) {
- input.placeholder = params.inputPlaceholder;
- }
- };
- var getInputContainer = function getInputContainer(inputType) {
- var inputClass = swalClasses[inputType] ? swalClasses[inputType] : swalClasses.input;
- return getChildByClass(getContent(), inputClass);
- };
- var renderInputType = {};
- renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = function (input, params) {
- if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') {
- input.value = params.inputValue;
- } else if (!isPromise(params.inputValue)) {
- warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(_typeof(params.inputValue), "\""));
- }
- setInputPlaceholder(input, params);
- input.type = params.input;
- return input;
- };
- renderInputType.file = function (input, params) {
- setInputPlaceholder(input, params);
- return input;
- };
- renderInputType.range = function (range, params) {
- var rangeInput = range.querySelector('input');
- var rangeOutput = range.querySelector('output');
- rangeInput.value = params.inputValue;
- rangeInput.type = params.input;
- rangeOutput.value = params.inputValue;
- return range;
- };
- renderInputType.select = function (select, params) {
- select.innerHTML = '';
- if (params.inputPlaceholder) {
- var placeholder = document.createElement('option');
- placeholder.innerHTML = params.inputPlaceholder;
- placeholder.value = '';
- placeholder.disabled = true;
- placeholder.selected = true;
- select.appendChild(placeholder);
- }
- return select;
- };
- renderInputType.radio = function (radio) {
- radio.innerHTML = '';
- return radio;
- };
- renderInputType.checkbox = function (checkboxContainer, params) {
- var checkbox = getInput(getContent(), 'checkbox');
- checkbox.value = 1;
- checkbox.id = swalClasses.checkbox;
- checkbox.checked = Boolean(params.inputValue);
- var label = checkboxContainer.querySelector('span');
- label.innerHTML = params.inputPlaceholder;
- return checkboxContainer;
- };
- renderInputType.textarea = function (textarea, params) {
- textarea.value = params.inputValue;
- setInputPlaceholder(textarea, params);
- if ('MutationObserver' in window) {
- // #1699
- var initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
- var popupPadding = parseInt(window.getComputedStyle(getPopup()).paddingLeft) + parseInt(window.getComputedStyle(getPopup()).paddingRight);
- var outputsize = function outputsize() {
- var contentWidth = textarea.offsetWidth + popupPadding;
- if (contentWidth > initialPopupWidth) {
- getPopup().style.width = "".concat(contentWidth, "px");
- } else {
- getPopup().style.width = null;
- }
- };
- new MutationObserver(outputsize).observe(textarea, {
- attributes: true,
- attributeFilter: ['style']
- });
- }
- return textarea;
- };
- var renderContent = function renderContent(instance, params) {
- var content = getContent().querySelector("#".concat(swalClasses.content)); // Content as HTML
- if (params.html) {
- parseHtmlToContainer(params.html, content);
- show(content, 'block'); // Content as plain text
- } else if (params.text) {
- content.textContent = params.text;
- show(content, 'block'); // No content
- } else {
- hide(content);
- }
- renderInput(instance, params); // Custom class
- applyCustomClass(getContent(), params, 'content');
- };
- var renderFooter = function renderFooter(instance, params) {
- var footer = getFooter();
- toggle(footer, params.footer);
- if (params.footer) {
- parseHtmlToContainer(params.footer, footer);
- } // Custom class
- applyCustomClass(footer, params, 'footer');
- };
- var renderCloseButton = function renderCloseButton(instance, params) {
- var closeButton = getCloseButton();
- closeButton.innerHTML = params.closeButtonHtml; // Custom class
- applyCustomClass(closeButton, params, 'closeButton');
- toggle(closeButton, params.showCloseButton);
- closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
- };
- var renderIcon = function renderIcon(instance, params) {
- var innerParams = privateProps.innerParams.get(instance); // if the give icon already rendered, apply the custom class without re-rendering the icon
- if (innerParams && params.icon === innerParams.icon && getIcon()) {
- applyCustomClass(getIcon(), params, 'icon');
- return;
- }
- hideAllIcons();
- if (!params.icon) {
- return;
- }
- if (Object.keys(iconTypes).indexOf(params.icon) !== -1) {
- var icon = elementBySelector(".".concat(swalClasses.icon, ".").concat(iconTypes[params.icon]));
- show(icon); // Custom or default content
- setContent(icon, params);
- adjustSuccessIconBackgoundColor(); // Custom class
- applyCustomClass(icon, params, 'icon'); // Animate icon
- addClass(icon, params.showClass.icon);
- } else {
- error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\""));
- }
- };
- var hideAllIcons = function hideAllIcons() {
- var icons = getIcons();
- for (var i = 0; i < icons.length; i++) {
- hide(icons[i]);
- }
- }; // Adjust success icon background color to match the popup background color
- var adjustSuccessIconBackgoundColor = function adjustSuccessIconBackgoundColor() {
- var popup = getPopup();
- var popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
- var successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
- for (var i = 0; i < successIconParts.length; i++) {
- successIconParts[i].style.backgroundColor = popupBackgroundColor;
- }
- };
- var setContent = function setContent(icon, params) {
- icon.innerHTML = '';
- if (params.iconHtml) {
- icon.innerHTML = iconContent(params.iconHtml);
- } else if (params.icon === 'success') {
- icon.innerHTML = "\n <div class=\"swal2-success-circular-line-left\"></div>\n <span class=\"swal2-success-line-tip\"></span> <span class=\"swal2-success-line-long\"></span>\n <div class=\"swal2-success-ring\"></div> <div class=\"swal2-success-fix\"></div>\n <div class=\"swal2-success-circular-line-right\"></div>\n ";
- } else if (params.icon === 'error') {
- icon.innerHTML = "\n <span class=\"swal2-x-mark\">\n <span class=\"swal2-x-mark-line-left\"></span>\n <span class=\"swal2-x-mark-line-right\"></span>\n </span>\n ";
- } else {
- var defaultIconHtml = {
- question: '?',
- warning: '!',
- info: 'i'
- };
- icon.innerHTML = iconContent(defaultIconHtml[params.icon]);
- }
- };
- var iconContent = function iconContent(content) {
- return "<div class=\"".concat(swalClasses['icon-content'], "\">").concat(content, "</div>");
- };
- var renderImage = function renderImage(instance, params) {
- var image = getImage();
- if (!params.imageUrl) {
- return hide(image);
- }
- show(image); // Src, alt
- image.setAttribute('src', params.imageUrl);
- image.setAttribute('alt', params.imageAlt); // Width, height
- applyNumericalStyle(image, 'width', params.imageWidth);
- applyNumericalStyle(image, 'height', params.imageHeight); // Class
- image.className = swalClasses.image;
- applyCustomClass(image, params, 'image');
- };
- var currentSteps = [];
- /*
- * Global function for chaining sweetAlert popups
- */
- var queue = function queue(steps) {
- var Swal = this;
- currentSteps = steps;
- var resetAndResolve = function resetAndResolve(resolve, value) {
- currentSteps = [];
- resolve(value);
- };
- var queueResult = [];
- return new Promise(function (resolve) {
- (function step(i, callback) {
- if (i < currentSteps.length) {
- document.body.setAttribute('data-swal2-queue-step', i);
- Swal.fire(currentSteps[i]).then(function (result) {
- if (typeof result.value !== 'undefined') {
- queueResult.push(result.value);
- step(i + 1, callback);
- } else {
- resetAndResolve(resolve, {
- dismiss: result.dismiss
- });
- }
- });
- } else {
- resetAndResolve(resolve, {
- value: queueResult
- });
- }
- })(0);
- });
- };
- /*
- * Global function for getting the index of current popup in queue
- */
- var getQueueStep = function getQueueStep() {
- return getContainer().getAttribute('data-queue-step');
- };
- /*
- * Global function for inserting a popup to the queue
- */
- var insertQueueStep = function insertQueueStep(step, index) {
- if (index && index < currentSteps.length) {
- return currentSteps.splice(index, 0, step);
- }
- return currentSteps.push(step);
- };
- /*
- * Global function for deleting a popup from the queue
- */
- var deleteQueueStep = function deleteQueueStep(index) {
- if (typeof currentSteps[index] !== 'undefined') {
- currentSteps.splice(index, 1);
- }
- };
- var createStepElement = function createStepElement(step) {
- var stepEl = document.createElement('li');
- addClass(stepEl, swalClasses['progress-step']);
- stepEl.innerHTML = step;
- return stepEl;
- };
- var createLineElement = function createLineElement(params) {
- var lineEl = document.createElement('li');
- addClass(lineEl, swalClasses['progress-step-line']);
- if (params.progressStepsDistance) {
- lineEl.style.width = params.progressStepsDistance;
- }
- return lineEl;
- };
- var renderProgressSteps = function renderProgressSteps(instance, params) {
- var progressStepsContainer = getProgressSteps();
- if (!params.progressSteps || params.progressSteps.length === 0) {
- return hide(progressStepsContainer);
- }
- show(progressStepsContainer);
- progressStepsContainer.innerHTML = '';
- var currentProgressStep = parseInt(params.currentProgressStep === undefined ? getQueueStep() : params.currentProgressStep);
- if (currentProgressStep >= params.progressSteps.length) {
- warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
- }
- params.progressSteps.forEach(function (step, index) {
- var stepEl = createStepElement(step);
- progressStepsContainer.appendChild(stepEl);
- if (index === currentProgressStep) {
- addClass(stepEl, swalClasses['active-progress-step']);
- }
- if (index !== params.progressSteps.length - 1) {
- var lineEl = createLineElement(step);
- progressStepsContainer.appendChild(lineEl);
- }
- });
- };
- var renderTitle = function renderTitle(instance, params) {
- var title = getTitle();
- toggle(title, params.title || params.titleText);
- if (params.title) {
- parseHtmlToContainer(params.title, title);
- }
- if (params.titleText) {
- title.innerText = params.titleText;
- } // Custom class
- applyCustomClass(title, params, 'title');
- };
- var renderHeader = function renderHeader(instance, params) {
- var header = getHeader(); // Custom class
- applyCustomClass(header, params, 'header'); // Progress steps
- renderProgressSteps(instance, params); // Icon
- renderIcon(instance, params); // Image
- renderImage(instance, params); // Title
- renderTitle(instance, params); // Close button
- renderCloseButton(instance, params);
- };
- var renderPopup = function renderPopup(instance, params) {
- var popup = getPopup(); // Width
- applyNumericalStyle(popup, 'width', params.width); // Padding
- applyNumericalStyle(popup, 'padding', params.padding); // Background
- if (params.background) {
- popup.style.background = params.background;
- } // Classes
- addClasses(popup, params);
- };
- var addClasses = function addClasses(popup, params) {
- // Default Class + showClass when updating Swal.update({})
- popup.className = "".concat(swalClasses.popup, " ").concat(isVisible(popup) ? params.showClass.popup : '');
- if (params.toast) {
- addClass([document.documentElement, document.body], swalClasses['toast-shown']);
- addClass(popup, swalClasses.toast);
- } else {
- addClass(popup, swalClasses.modal);
- } // Custom class
- applyCustomClass(popup, params, 'popup');
- if (typeof params.customClass === 'string') {
- addClass(popup, params.customClass);
- } // Icon class (#1842)
- if (params.icon) {
- addClass(popup, swalClasses["icon-".concat(params.icon)]);
- }
- };
- var render = function render(instance, params) {
- renderPopup(instance, params);
- renderContainer(instance, params);
- renderHeader(instance, params);
- renderContent(instance, params);
- renderActions(instance, params);
- renderFooter(instance, params);
- if (typeof params.onRender === 'function') {
- params.onRender(getPopup());
- }
- };
- /*
- * Global function to determine if SweetAlert2 popup is shown
- */
- var isVisible$1 = function isVisible$$1() {
- return isVisible(getPopup());
- };
- /*
- * Global function to click 'Confirm' button
- */
- var clickConfirm = function clickConfirm() {
- return getConfirmButton() && getConfirmButton().click();
- };
- /*
- * Global function to click 'Cancel' button
- */
- var clickCancel = function clickCancel() {
- return getCancelButton() && getCancelButton().click();
- };
- function fire() {
- var Swal = this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- return _construct(Swal, args);
- }
- /**
- * Returns an extended version of `Swal` containing `params` as defaults.
- * Useful for reusing Swal configuration.
- *
- * For example:
- *
- * Before:
- * const textPromptOptions = { input: 'text', showCancelButton: true }
- * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
- * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
- *
- * After:
- * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
- * const {value: firstName} = await TextPrompt('What is your first name?')
- * const {value: lastName} = await TextPrompt('What is your last name?')
- *
- * @param mixinParams
- */
- function mixin(mixinParams) {
- var MixinSwal =
- /*#__PURE__*/
- function (_this) {
- _inherits(MixinSwal, _this);
- function MixinSwal() {
- _classCallCheck(this, MixinSwal);
- return _possibleConstructorReturn(this, _getPrototypeOf(MixinSwal).apply(this, arguments));
- }
- _createClass(MixinSwal, [{
- key: "_main",
- value: function _main(params) {
- return _get(_getPrototypeOf(MixinSwal.prototype), "_main", this).call(this, _extends({}, mixinParams, params));
- }
- }]);
- return MixinSwal;
- }(this);
- return MixinSwal;
- }
- /**
- * Show spinner instead of Confirm button
- */
- var showLoading = function showLoading() {
- var popup = getPopup();
- if (!popup) {
- Swal.fire();
- }
- popup = getPopup();
- var actions = getActions();
- var confirmButton = getConfirmButton();
- show(actions);
- show(confirmButton, 'inline-block');
- addClass([popup, actions], swalClasses.loading);
- confirmButton.disabled = true;
- popup.setAttribute('data-loading', true);
- popup.setAttribute('aria-busy', true);
- popup.focus();
- };
- var RESTORE_FOCUS_TIMEOUT = 100;
- var globalState = {};
- var focusPreviousActiveElement = function focusPreviousActiveElement() {
- if (globalState.previousActiveElement && globalState.previousActiveElement.focus) {
- globalState.previousActiveElement.focus();
- globalState.previousActiveElement = null;
- } else if (document.body) {
- document.body.focus();
- }
- }; // Restore previous active (focused) element
- var restoreActiveElement = function restoreActiveElement() {
- return new Promise(function (resolve) {
- var x = window.scrollX;
- var y = window.scrollY;
- globalState.restoreFocusTimeout = setTimeout(function () {
- focusPreviousActiveElement();
- resolve();
- }, RESTORE_FOCUS_TIMEOUT); // issues/900
- /* istanbul ignore if */
- if (typeof x !== 'undefined' && typeof y !== 'undefined') {
- // IE doesn't have scrollX/scrollY support
- window.scrollTo(x, y);
- }
- });
- };
- /**
- * If `timer` parameter is set, returns number of milliseconds of timer remained.
- * Otherwise, returns undefined.
- */
- var getTimerLeft = function getTimerLeft() {
- return globalState.timeout && globalState.timeout.getTimerLeft();
- };
- /**
- * Stop timer. Returns number of milliseconds of timer remained.
- * If `timer` parameter isn't set, returns undefined.
- */
- var stopTimer = function stopTimer() {
- if (globalState.timeout) {
- stopTimerProgressBar();
- return globalState.timeout.stop();
- }
- };
- /**
- * Resume timer. Returns number of milliseconds of timer remained.
- * If `timer` parameter isn't set, returns undefined.
- */
- var resumeTimer = function resumeTimer() {
- if (globalState.timeout) {
- var remaining = globalState.timeout.start();
- animateTimerProgressBar(remaining);
- return remaining;
- }
- };
- /**
- * Resume timer. Returns number of milliseconds of timer remained.
- * If `timer` parameter isn't set, returns undefined.
- */
- var toggleTimer = function toggleTimer() {
- var timer = globalState.timeout;
- return timer && (timer.running ? stopTimer() : resumeTimer());
- };
- /**
- * Increase timer. Returns number of milliseconds of an updated timer.
- * If `timer` parameter isn't set, returns undefined.
- */
- var increaseTimer = function increaseTimer(n) {
- if (globalState.timeout) {
- var remaining = globalState.timeout.increase(n);
- animateTimerProgressBar(remaining, true);
- return remaining;
- }
- };
- /**
- * Check if timer is running. Returns true if timer is running
- * or false if timer is paused or stopped.
- * If `timer` parameter isn't set, returns undefined
- */
- var isTimerRunning = function isTimerRunning() {
- return globalState.timeout && globalState.timeout.isRunning();
- };
- var defaultParams = {
- title: '',
- titleText: '',
- text: '',
- html: '',
- footer: '',
- icon: undefined,
- iconHtml: undefined,
- toast: false,
- animation: true,
- showClass: {
- popup: 'swal2-show',
- backdrop: 'swal2-backdrop-show',
- icon: 'swal2-icon-show'
- },
- hideClass: {
- popup: 'swal2-hide',
- backdrop: 'swal2-backdrop-hide',
- icon: 'swal2-icon-hide'
- },
- customClass: undefined,
- target: 'body',
- backdrop: true,
- heightAuto: true,
- allowOutsideClick: true,
- allowEscapeKey: true,
- allowEnterKey: true,
- stopKeydownPropagation: true,
- keydownListenerCapture: false,
- showConfirmButton: true,
- showCancelButton: false,
- preConfirm: undefined,
- confirmButtonText: 'OK',
- confirmButtonAriaLabel: '',
- confirmButtonColor: undefined,
- cancelButtonText: 'Cancel',
- cancelButtonAriaLabel: '',
- cancelButtonColor: undefined,
- buttonsStyling: true,
- reverseButtons: false,
- focusConfirm: true,
- focusCancel: false,
- showCloseButton: false,
- closeButtonHtml: '×',
- closeButtonAriaLabel: 'Close this dialog',
- showLoaderOnConfirm: false,
- imageUrl: undefined,
- imageWidth: undefined,
- imageHeight: undefined,
- imageAlt: '',
- timer: undefined,
- timerProgressBar: false,
- width: undefined,
- padding: undefined,
- background: undefined,
- input: undefined,
- inputPlaceholder: '',
- inputValue: '',
- inputOptions: {},
- inputAutoTrim: true,
- inputAttributes: {},
- inputValidator: undefined,
- validationMessage: undefined,
- grow: false,
- position: 'center',
- progressSteps: [],
- currentProgressStep: undefined,
- progressStepsDistance: undefined,
- onBeforeOpen: undefined,
- onOpen: undefined,
- onRender: undefined,
- onClose: undefined,
- onAfterClose: undefined,
- onDestroy: undefined,
- scrollbarPadding: true
- };
- var updatableParams = ['title', 'titleText', 'text', 'html', 'icon', 'customClass', 'allowOutsideClick', 'allowEscapeKey', 'showConfirmButton', 'showCancelButton', 'confirmButtonText', 'confirmButtonAriaLabel', 'confirmButtonColor', 'cancelButtonText', 'cancelButtonAriaLabel', 'cancelButtonColor', 'buttonsStyling', 'reverseButtons', 'imageUrl', 'imageWidth', 'imageHeight', 'imageAlt', 'progressSteps', 'currentProgressStep'];
- var deprecatedParams = {
- animation: 'showClass" and "hideClass'
- };
- var toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusCancel', 'heightAuto', 'keydownListenerCapture'];
- /**
- * Is valid parameter
- * @param {String} paramName
- */
- var isValidParameter = function isValidParameter(paramName) {
- return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
- };
- /**
- * Is valid parameter for Swal.update() method
- * @param {String} paramName
- */
- var isUpdatableParameter = function isUpdatableParameter(paramName) {
- return updatableParams.indexOf(paramName) !== -1;
- };
- /**
- * Is deprecated parameter
- * @param {String} paramName
- */
- var isDeprecatedParameter = function isDeprecatedParameter(paramName) {
- return deprecatedParams[paramName];
- };
- var checkIfParamIsValid = function checkIfParamIsValid(param) {
- if (!isValidParameter(param)) {
- warn("Unknown parameter \"".concat(param, "\""));
- }
- };
- var checkIfToastParamIsValid = function checkIfToastParamIsValid(param) {
- if (toastIncompatibleParams.indexOf(param) !== -1) {
- warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
- }
- };
- var checkIfParamIsDeprecated = function checkIfParamIsDeprecated(param) {
- if (isDeprecatedParameter(param)) {
- warnAboutDepreation(param, isDeprecatedParameter(param));
- }
- };
- /**
- * Show relevant warnings for given params
- *
- * @param params
- */
- var showWarningsForParams = function showWarningsForParams(params) {
- for (var param in params) {
- checkIfParamIsValid(param);
- if (params.toast) {
- checkIfToastParamIsValid(param);
- }
- checkIfParamIsDeprecated(param);
- }
- };
- var staticMethods = /*#__PURE__*/Object.freeze({
- isValidParameter: isValidParameter,
- isUpdatableParameter: isUpdatableParameter,
- isDeprecatedParameter: isDeprecatedParameter,
- argsToParams: argsToParams,
- isVisible: isVisible$1,
- clickConfirm: clickConfirm,
- clickCancel: clickCancel,
- getContainer: getContainer,
- getPopup: getPopup,
- getTitle: getTitle,
- getContent: getContent,
- getHtmlContainer: getHtmlContainer,
- getImage: getImage,
- getIcon: getIcon,
- getIcons: getIcons,
- getCloseButton: getCloseButton,
- getActions: getActions,
- getConfirmButton: getConfirmButton,
- getCancelButton: getCancelButton,
- getHeader: getHeader,
- getFooter: getFooter,
- getTimerProgressBar: getTimerProgressBar,
- getFocusableElements: getFocusableElements,
- getValidationMessage: getValidationMessage,
- isLoading: isLoading,
- fire: fire,
- mixin: mixin,
- queue: queue,
- getQueueStep: getQueueStep,
- insertQueueStep: insertQueueStep,
- deleteQueueStep: deleteQueueStep,
- showLoading: showLoading,
- enableLoading: showLoading,
- getTimerLeft: getTimerLeft,
- stopTimer: stopTimer,
- resumeTimer: resumeTimer,
- toggleTimer: toggleTimer,
- increaseTimer: increaseTimer,
- isTimerRunning: isTimerRunning
- });
- /**
- * Enables buttons and hide loader.
- */
- function hideLoading() {
- // do nothing if popup is closed
- var innerParams = privateProps.innerParams.get(this);
- if (!innerParams) {
- return;
- }
- var domCache = privateProps.domCache.get(this);
- if (!innerParams.showConfirmButton) {
- hide(domCache.confirmButton);
- if (!innerParams.showCancelButton) {
- hide(domCache.actions);
- }
- }
- removeClass([domCache.popup, domCache.actions], swalClasses.loading);
- domCache.popup.removeAttribute('aria-busy');
- domCache.popup.removeAttribute('data-loading');
- domCache.confirmButton.disabled = false;
- domCache.cancelButton.disabled = false;
- }
- function getInput$1(instance) {
- var innerParams = privateProps.innerParams.get(instance || this);
- var domCache = privateProps.domCache.get(instance || this);
- if (!domCache) {
- return null;
- }
- return getInput(domCache.content, innerParams.input);
- }
- var fixScrollbar = function fixScrollbar() {
- // for queues, do not do this more than once
- if (states.previousBodyPadding !== null) {
- return;
- } // if the body has overflow
- if (document.body.scrollHeight > window.innerHeight) {
- // add padding so the content doesn't shift after removal of scrollbar
- states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
- document.body.style.paddingRight = "".concat(states.previousBodyPadding + measureScrollbar(), "px");
- }
- };
- var undoScrollbar = function undoScrollbar() {
- if (states.previousBodyPadding !== null) {
- document.body.style.paddingRight = "".concat(states.previousBodyPadding, "px");
- states.previousBodyPadding = null;
- }
- };
- /* istanbul ignore file */
- var iOSfix = function iOSfix() {
- var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
- if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
- var offset = document.body.scrollTop;
- document.body.style.top = "".concat(offset * -1, "px");
- addClass(document.body, swalClasses.iosfix);
- lockBodyScroll();
- }
- };
- var lockBodyScroll = function lockBodyScroll() {
- // #1246
- var container = getContainer();
- var preventTouchMove;
- container.ontouchstart = function (e) {
- preventTouchMove = e.target === container || !isScrollable(container) && e.target.tagName !== 'INPUT' // #1603
- ;
- };
- container.ontouchmove = function (e) {
- if (preventTouchMove) {
- e.preventDefault();
- e.stopPropagation();
- }
- };
- };
- var undoIOSfix = function undoIOSfix() {
- if (hasClass(document.body, swalClasses.iosfix)) {
- var offset = parseInt(document.body.style.top, 10);
- removeClass(document.body, swalClasses.iosfix);
- document.body.style.top = '';
- document.body.scrollTop = offset * -1;
- }
- };
- /* istanbul ignore file */
- var isIE11 = function isIE11() {
- return !!window.MSInputMethodContext && !!document.documentMode;
- }; // Fix IE11 centering sweetalert2/issues/933
- var fixVerticalPositionIE = function fixVerticalPositionIE() {
- var container = getContainer();
- var popup = getPopup();
- container.style.removeProperty('align-items');
- if (popup.offsetTop < 0) {
- container.style.alignItems = 'flex-start';
- }
- };
- var IEfix = function IEfix() {
- if (typeof window !== 'undefined' && isIE11()) {
- fixVerticalPositionIE();
- window.addEventListener('resize', fixVerticalPositionIE);
- }
- };
- var undoIEfix = function undoIEfix() {
- if (typeof window !== 'undefined' && isIE11()) {
- window.removeEventListener('resize', fixVerticalPositionIE);
- }
- };
- // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
- // elements not within the active modal dialog will not be surfaced if a user opens a screen
- // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
- var setAriaHidden = function setAriaHidden() {
- var bodyChildren = toArray(document.body.children);
- bodyChildren.forEach(function (el) {
- if (el === getContainer() || contains(el, getContainer())) {
- return;
- }
- if (el.hasAttribute('aria-hidden')) {
- el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
- }
- el.setAttribute('aria-hidden', 'true');
- });
- };
- var unsetAriaHidden = function unsetAriaHidden() {
- var bodyChildren = toArray(document.body.children);
- bodyChildren.forEach(function (el) {
- if (el.hasAttribute('data-previous-aria-hidden')) {
- el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
- el.removeAttribute('data-previous-aria-hidden');
- } else {
- el.removeAttribute('aria-hidden');
- }
- });
- };
- /**
- * This module containts `WeakMap`s for each effectively-"private property" that a `Swal` has.
- * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
- * This is the approach that Babel will probably take to implement private methods/fields
- * https://github.com/tc39/proposal-private-methods
- * https://github.com/babel/babel/pull/7555
- * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
- * then we can use that language feature.
- */
- var privateMethods = {
- swalPromiseResolve: new WeakMap()
- };
- /*
- * Instance method to close sweetAlert
- */
- function removePopupAndResetState(instance, container, isToast$$1, onAfterClose) {
- if (isToast$$1) {
- triggerOnAfterCloseAndDispose(instance, onAfterClose);
- } else {
- restoreActiveElement().then(function () {
- return triggerOnAfterCloseAndDispose(instance, onAfterClose);
- });
- globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
- capture: globalState.keydownListenerCapture
- });
- globalState.keydownHandlerAdded = false;
- }
- if (container.parentNode && !document.body.getAttribute('data-swal2-queue-step')) {
- container.parentNode.removeChild(container);
- }
- if (isModal()) {
- undoScrollbar();
- undoIOSfix();
- undoIEfix();
- unsetAriaHidden();
- }
- removeBodyClasses();
- }
- function removeBodyClasses() {
- removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['toast-column']]);
- }
- function close(resolveValue) {
- var popup = getPopup();
- if (!popup) {
- return;
- }
- var innerParams = privateProps.innerParams.get(this);
- if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
- return;
- }
- var swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
- removeClass(popup, innerParams.showClass.popup);
- addClass(popup, innerParams.hideClass.popup);
- var backdrop = getContainer();
- removeClass(backdrop, innerParams.showClass.backdrop);
- addClass(backdrop, innerParams.hideClass.backdrop);
- handlePopupAnimation(this, popup, innerParams); // Resolve Swal promise
- swalPromiseResolve(resolveValue || {});
- }
- var handlePopupAnimation = function handlePopupAnimation(instance, popup, innerParams) {
- var container = getContainer(); // If animation is supported, animate
- var animationIsSupported = animationEndEvent && hasCssAnimation(popup);
- var onClose = innerParams.onClose,
- onAfterClose = innerParams.onAfterClose;
- if (onClose !== null && typeof onClose === 'function') {
- onClose(popup);
- }
- if (animationIsSupported) {
- animatePopup(instance, popup, container, onAfterClose);
- } else {
- // Otherwise, remove immediately
- removePopupAndResetState(instance, container, isToast(), onAfterClose);
- }
- };
- var animatePopup = function animatePopup(instance, popup, container, onAfterClose) {
- globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, isToast(), onAfterClose);
- popup.addEventListener(animationEndEvent, function (e) {
- if (e.target === popup) {
- globalState.swalCloseEventFinishedCallback();
- delete globalState.swalCloseEventFinishedCallback;
- }
- });
- };
- var triggerOnAfterCloseAndDispose = function triggerOnAfterCloseAndDispose(instance, onAfterClose) {
- setTimeout(function () {
- if (typeof onAfterClose === 'function') {
- onAfterClose();
- }
- instance._destroy();
- });
- };
- function setButtonsDisabled(instance, buttons, disabled) {
- var domCache = privateProps.domCache.get(instance);
- buttons.forEach(function (button) {
- domCache[button].disabled = disabled;
- });
- }
- function setInputDisabled(input, disabled) {
- if (!input) {
- return false;
- }
- if (input.type === 'radio') {
- var radiosContainer = input.parentNode.parentNode;
- var radios = radiosContainer.querySelectorAll('input');
- for (var i = 0; i < radios.length; i++) {
- radios[i].disabled = disabled;
- }
- } else {
- input.disabled = disabled;
- }
- }
- function enableButtons() {
- setButtonsDisabled(this, ['confirmButton', 'cancelButton'], false);
- }
- function disableButtons() {
- setButtonsDisabled(this, ['confirmButton', 'cancelButton'], true);
- }
- function enableInput() {
- return setInputDisabled(this.getInput(), false);
- }
- function disableInput() {
- return setInputDisabled(this.getInput(), true);
- }
- function showValidationMessage(error) {
- var domCache = privateProps.domCache.get(this);
- domCache.validationMessage.innerHTML = error;
- var popupComputedStyle = window.getComputedStyle(domCache.popup);
- domCache.validationMessage.style.marginLeft = "-".concat(popupComputedStyle.getPropertyValue('padding-left'));
- domCache.validationMessage.style.marginRight = "-".concat(popupComputedStyle.getPropertyValue('padding-right'));
- show(domCache.validationMessage);
- var input = this.getInput();
- if (input) {
- input.setAttribute('aria-invalid', true);
- input.setAttribute('aria-describedBy', swalClasses['validation-message']);
- focusInput(input);
- addClass(input, swalClasses.inputerror);
- }
- } // Hide block with validation message
- function resetValidationMessage$1() {
- var domCache = privateProps.domCache.get(this);
- if (domCache.validationMessage) {
- hide(domCache.validationMessage);
- }
- var input = this.getInput();
- if (input) {
- input.removeAttribute('aria-invalid');
- input.removeAttribute('aria-describedBy');
- removeClass(input, swalClasses.inputerror);
- }
- }
- function getProgressSteps$1() {
- var domCache = privateProps.domCache.get(this);
- return domCache.progressSteps;
- }
- var Timer =
- /*#__PURE__*/
- function () {
- function Timer(callback, delay) {
- _classCallCheck(this, Timer);
- this.callback = callback;
- this.remaining = delay;
- this.running = false;
- this.start();
- }
- _createClass(Timer, [{
- key: "start",
- value: function start() {
- if (!this.running) {
- this.running = true;
- this.started = new Date();
- this.id = setTimeout(this.callback, this.remaining);
- }
- return this.remaining;
- }
- }, {
- key: "stop",
- value: function stop() {
- if (this.running) {
- this.running = false;
- clearTimeout(this.id);
- this.remaining -= new Date() - this.started;
- }
- return this.remaining;
- }
- }, {
- key: "increase",
- value: function increase(n) {
- var running = this.running;
- if (running) {
- this.stop();
- }
- this.remaining += n;
- if (running) {
- this.start();
- }
- return this.remaining;
- }
- }, {
- key: "getTimerLeft",
- value: function getTimerLeft() {
- if (this.running) {
- this.stop();
- this.start();
- }
- return this.remaining;
- }
- }, {
- key: "isRunning",
- value: function isRunning() {
- return this.running;
- }
- }]);
- return Timer;
- }();
- var defaultInputValidators = {
- email: function email(string, validationMessage) {
- 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');
- },
- url: function url(string, validationMessage) {
- // taken from https://stackoverflow.com/a/3809435 with a small change from #1306
- 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');
- }
- };
- function setDefaultInputValidators(params) {
- // Use default `inputValidator` for supported input types if not provided
- if (!params.inputValidator) {
- Object.keys(defaultInputValidators).forEach(function (key) {
- if (params.input === key) {
- params.inputValidator = defaultInputValidators[key];
- }
- });
- }
- }
- function validateCustomTargetElement(params) {
- // Determine if the custom target element is valid
- if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
- warn('Target parameter is not valid, defaulting to "body"');
- params.target = 'body';
- }
- }
- /**
- * Set type, text and actions on popup
- *
- * @param params
- * @returns {boolean}
- */
- function setParameters(params) {
- setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm
- if (params.showLoaderOnConfirm && !params.preConfirm) {
- 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');
- } // params.animation will be actually used in renderPopup.js
- // but in case when params.animation is a function, we need to call that function
- // before popup (re)initialization, so it'll be possible to check Swal.isVisible()
- // inside the params.animation function
- params.animation = callIfFunction(params.animation);
- validateCustomTargetElement(params); // Replace newlines with <br> in title
- if (typeof params.title === 'string') {
- params.title = params.title.split('\n').join('<br />');
- }
- init(params);
- }
- /**
- * Open popup, add necessary classes and styles, fix scrollbar
- *
- * @param {Array} params
- */
- var openPopup = function openPopup(params) {
- var container = getContainer();
- var popup = getPopup();
- if (typeof params.onBeforeOpen === 'function') {
- params.onBeforeOpen(popup);
- }
- addClasses$1(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'
- setScrollingVisibility(container, popup);
- if (isModal()) {
- fixScrollContainer(container, params.scrollbarPadding);
- }
- if (!isToast() && !globalState.previousActiveElement) {
- globalState.previousActiveElement = document.activeElement;
- }
- if (typeof params.onOpen === 'function') {
- setTimeout(function () {
- return params.onOpen(popup);
- });
- }
- removeClass(container, swalClasses['no-transition']);
- };
- function swalOpenAnimationFinished(event) {
- var popup = getPopup();
- if (event.target !== popup) {
- return;
- }
- var container = getContainer();
- popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
- container.style.overflowY = 'auto';
- }
- var setScrollingVisibility = function setScrollingVisibility(container, popup) {
- if (animationEndEvent && hasCssAnimation(popup)) {
- container.style.overflowY = 'hidden';
- popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
- } else {
- container.style.overflowY = 'auto';
- }
- };
- var fixScrollContainer = function fixScrollContainer(container, scrollbarPadding) {
- iOSfix();
- IEfix();
- setAriaHidden();
- if (scrollbarPadding) {
- fixScrollbar();
- } // sweetalert2/issues/1247
- setTimeout(function () {
- container.scrollTop = 0;
- });
- };
- var addClasses$1 = function addClasses(container, popup, params) {
- addClass(container, params.showClass.backdrop);
- show(popup); // Animate popup right after showing it
- addClass(popup, params.showClass.popup);
- addClass([document.documentElement, document.body], swalClasses.shown);
- if (params.heightAuto && params.backdrop && !params.toast) {
- addClass([document.documentElement, document.body], swalClasses['height-auto']);
- }
- };
- var handleInputOptionsAndValue = function handleInputOptionsAndValue(instance, params) {
- if (params.input === 'select' || params.input === 'radio') {
- handleInputOptions(instance, params);
- } else if (['text', 'email', 'number', 'tel', 'textarea'].indexOf(params.input) !== -1 && isPromise(params.inputValue)) {
- handleInputValue(instance, params);
- }
- };
- var getInputValue = function getInputValue(instance, innerParams) {
- var input = instance.getInput();
- if (!input) {
- return null;
- }
- switch (innerParams.input) {
- case 'checkbox':
- return getCheckboxValue(input);
- case 'radio':
- return getRadioValue(input);
- case 'file':
- return getFileValue(input);
- default:
- return innerParams.inputAutoTrim ? input.value.trim() : input.value;
- }
- };
- var getCheckboxValue = function getCheckboxValue(input) {
- return input.checked ? 1 : 0;
- };
- var getRadioValue = function getRadioValue(input) {
- return input.checked ? input.value : null;
- };
- var getFileValue = function getFileValue(input) {
- return input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
- };
- var handleInputOptions = function handleInputOptions(instance, params) {
- var content = getContent();
- var processInputOptions = function processInputOptions(inputOptions) {
- return populateInputOptions[params.input](content, formatInputOptions(inputOptions), params);
- };
- if (isPromise(params.inputOptions)) {
- showLoading();
- params.inputOptions.then(function (inputOptions) {
- instance.hideLoading();
- processInputOptions(inputOptions);
- });
- } else if (_typeof(params.inputOptions) === 'object') {
- processInputOptions(params.inputOptions);
- } else {
- error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(_typeof(params.inputOptions)));
- }
- };
- var handleInputValue = function handleInputValue(instance, params) {
- var input = instance.getInput();
- hide(input);
- params.inputValue.then(function (inputValue) {
- input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : "".concat(inputValue);
- show(input);
- input.focus();
- instance.hideLoading();
- })["catch"](function (err) {
- error("Error in inputValue promise: ".concat(err));
- input.value = '';
- show(input);
- input.focus();
- instance.hideLoading();
- });
- };
- var populateInputOptions = {
- select: function select(content, inputOptions, params) {
- var select = getChildByClass(content, swalClasses.select);
- inputOptions.forEach(function (inputOption) {
- var optionValue = inputOption[0];
- var optionLabel = inputOption[1];
- var option = document.createElement('option');
- option.value = optionValue;
- option.innerHTML = optionLabel;
- if (params.inputValue.toString() === optionValue.toString()) {
- option.selected = true;
- }
- select.appendChild(option);
- });
- select.focus();
- },
- radio: function radio(content, inputOptions, params) {
- var radio = getChildByClass(content, swalClasses.radio);
- inputOptions.forEach(function (inputOption) {
- var radioValue = inputOption[0];
- var radioLabel = inputOption[1];
- var radioInput = document.createElement('input');
- var radioLabelElement = document.createElement('label');
- radioInput.type = 'radio';
- radioInput.name = swalClasses.radio;
- radioInput.value = radioValue;
- if (params.inputValue.toString() === radioValue.toString()) {
- radioInput.checked = true;
- }
- var label = document.createElement('span');
- label.innerHTML = radioLabel;
- label.className = swalClasses.label;
- radioLabelElement.appendChild(radioInput);
- radioLabelElement.appendChild(label);
- radio.appendChild(radioLabelElement);
- });
- var radios = radio.querySelectorAll('input');
- if (radios.length) {
- radios[0].focus();
- }
- }
- };
- /**
- * Converts `inputOptions` into an array of `[value, label]`s
- * @param inputOptions
- */
- var formatInputOptions = function formatInputOptions(inputOptions) {
- var result = [];
- if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
- inputOptions.forEach(function (value, key) {
- result.push([key, value]);
- });
- } else {
- Object.keys(inputOptions).forEach(function (key) {
- result.push([key, inputOptions[key]]);
- });
- }
- return result;
- };
- var handleConfirmButtonClick = function handleConfirmButtonClick(instance, innerParams) {
- instance.disableButtons();
- if (innerParams.input) {
- handleConfirmWithInput(instance, innerParams);
- } else {
- confirm(instance, innerParams, true);
- }
- };
- var handleCancelButtonClick = function handleCancelButtonClick(instance, dismissWith) {
- instance.disableButtons();
- dismissWith(DismissReason.cancel);
- };
- var handleConfirmWithInput = function handleConfirmWithInput(instance, innerParams) {
- var inputValue = getInputValue(instance, innerParams);
- if (innerParams.inputValidator) {
- instance.disableInput();
- var validationPromise = Promise.resolve().then(function () {
- return innerParams.inputValidator(inputValue, innerParams.validationMessage);
- });
- validationPromise.then(function (validationMessage) {
- instance.enableButtons();
- instance.enableInput();
- if (validationMessage) {
- instance.showValidationMessage(validationMessage);
- } else {
- confirm(instance, innerParams, inputValue);
- }
- });
- } else if (!instance.getInput().checkValidity()) {
- instance.enableButtons();
- instance.showValidationMessage(innerParams.validationMessage);
- } else {
- confirm(instance, innerParams, inputValue);
- }
- };
- var succeedWith = function succeedWith(instance, value) {
- instance.closePopup({
- value: value
- });
- };
- var confirm = function confirm(instance, innerParams, value) {
- if (innerParams.showLoaderOnConfirm) {
- showLoading(); // TODO: make showLoading an *instance* method
- }
- if (innerParams.preConfirm) {
- instance.resetValidationMessage();
- var preConfirmPromise = Promise.resolve().then(function () {
- return innerParams.preConfirm(value, innerParams.validationMessage);
- });
- preConfirmPromise.then(function (preConfirmValue) {
- if (isVisible(getValidationMessage()) || preConfirmValue === false) {
- instance.hideLoading();
- } else {
- succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
- }
- });
- } else {
- succeedWith(instance, value);
- }
- };
- var addKeydownHandler = function addKeydownHandler(instance, globalState, innerParams, dismissWith) {
- if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
- globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
- capture: globalState.keydownListenerCapture
- });
- globalState.keydownHandlerAdded = false;
- }
- if (!innerParams.toast) {
- globalState.keydownHandler = function (e) {
- return keydownHandler(instance, e, dismissWith);
- };
- globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
- globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
- globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
- capture: globalState.keydownListenerCapture
- });
- globalState.keydownHandlerAdded = true;
- }
- }; // Focus handling
- var setFocus = function setFocus(innerParams, index, increment) {
- var focusableElements = getFocusableElements(); // search for visible elements and select the next possible match
- for (var i = 0; i < focusableElements.length; i++) {
- index = index + increment; // rollover to first item
- if (index === focusableElements.length) {
- index = 0; // go to last item
- } else if (index === -1) {
- index = focusableElements.length - 1;
- }
- return focusableElements[index].focus();
- } // no visible focusable elements, focus the popup
- getPopup().focus();
- };
- var arrowKeys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Left', 'Right', 'Up', 'Down' // IE11
- ];
- var escKeys = ['Escape', 'Esc' // IE11
- ];
- var keydownHandler = function keydownHandler(instance, e, dismissWith) {
- var innerParams = privateProps.innerParams.get(instance);
- if (innerParams.stopKeydownPropagation) {
- e.stopPropagation();
- } // ENTER
- if (e.key === 'Enter') {
- handleEnter(instance, e, innerParams); // TAB
- } else if (e.key === 'Tab') {
- handleTab(e, innerParams); // ARROWS - switch focus between buttons
- } else if (arrowKeys.indexOf(e.key) !== -1) {
- handleArrows(); // ESC
- } else if (escKeys.indexOf(e.key) !== -1) {
- handleEsc(e, innerParams, dismissWith);
- }
- };
- var handleEnter = function handleEnter(instance, e, innerParams) {
- // #720 #721
- if (e.isComposing) {
- return;
- }
- if (e.target && instance.getInput() && e.target.outerHTML === instance.getInput().outerHTML) {
- if (['textarea', 'file'].indexOf(innerParams.input) !== -1) {
- return; // do not submit
- }
- clickConfirm();
- e.preventDefault();
- }
- };
- var handleTab = function handleTab(e, innerParams) {
- var targetElement = e.target;
- var focusableElements = getFocusableElements();
- var btnIndex = -1;
- for (var i = 0; i < focusableElements.length; i++) {
- if (targetElement === focusableElements[i]) {
- btnIndex = i;
- break;
- }
- }
- if (!e.shiftKey) {
- // Cycle to the next button
- setFocus(innerParams, btnIndex, 1);
- } else {
- // Cycle to the prev button
- setFocus(innerParams, btnIndex, -1);
- }
- e.stopPropagation();
- e.preventDefault();
- };
- var handleArrows = function handleArrows() {
- var confirmButton = getConfirmButton();
- var cancelButton = getCancelButton(); // focus Cancel button if Confirm button is currently focused
- if (document.activeElement === confirmButton && isVisible(cancelButton)) {
- cancelButton.focus(); // and vice versa
- } else if (document.activeElement === cancelButton && isVisible(confirmButton)) {
- confirmButton.focus();
- }
- };
- var handleEsc = function handleEsc(e, innerParams, dismissWith) {
- if (callIfFunction(innerParams.allowEscapeKey)) {
- e.preventDefault();
- dismissWith(DismissReason.esc);
- }
- };
- var handlePopupClick = function handlePopupClick(instance, domCache, dismissWith) {
- var innerParams = privateProps.innerParams.get(instance);
- if (innerParams.toast) {
- handleToastClick(instance, domCache, dismissWith);
- } else {
- // Ignore click events that had mousedown on the popup but mouseup on the container
- // This can happen when the user drags a slider
- handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup
- handleContainerMousedown(domCache);
- handleModalClick(instance, domCache, dismissWith);
- }
- };
- var handleToastClick = function handleToastClick(instance, domCache, dismissWith) {
- // Closing toast by internal click
- domCache.popup.onclick = function () {
- var innerParams = privateProps.innerParams.get(instance);
- if (innerParams.showConfirmButton || innerParams.showCancelButton || innerParams.showCloseButton || innerParams.input) {
- return;
- }
- dismissWith(DismissReason.close);
- };
- };
- var ignoreOutsideClick = false;
- var handleModalMousedown = function handleModalMousedown(domCache) {
- domCache.popup.onmousedown = function () {
- domCache.container.onmouseup = function (e) {
- domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't
- // have any other direct children aside of the popup
- if (e.target === domCache.container) {
- ignoreOutsideClick = true;
- }
- };
- };
- };
- var handleContainerMousedown = function handleContainerMousedown(domCache) {
- domCache.container.onmousedown = function () {
- domCache.popup.onmouseup = function (e) {
- domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup
- if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
- ignoreOutsideClick = true;
- }
- };
- };
- };
- var handleModalClick = function handleModalClick(instance, domCache, dismissWith) {
- domCache.container.onclick = function (e) {
- var innerParams = privateProps.innerParams.get(instance);
- if (ignoreOutsideClick) {
- ignoreOutsideClick = false;
- return;
- }
- if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
- dismissWith(DismissReason.backdrop);
- }
- };
- };
- function _main(userParams) {
- showWarningsForParams(userParams);
- if (globalState.currentInstance) {
- globalState.currentInstance._destroy();
- }
- globalState.currentInstance = this;
- var innerParams = prepareParams(userParams);
- setParameters(innerParams);
- Object.freeze(innerParams); // clear the previous timer
- if (globalState.timeout) {
- globalState.timeout.stop();
- delete globalState.timeout;
- } // clear the restore focus timeout
- clearTimeout(globalState.restoreFocusTimeout);
- var domCache = populateDomCache(this);
- render(this, innerParams);
- privateProps.innerParams.set(this, innerParams);
- return swalPromise(this, domCache, innerParams);
- }
- var prepareParams = function prepareParams(userParams) {
- var showClass = _extends({}, defaultParams.showClass, userParams.showClass);
- var hideClass = _extends({}, defaultParams.hideClass, userParams.hideClass);
- var params = _extends({}, defaultParams, userParams);
- params.showClass = showClass;
- params.hideClass = hideClass; // @deprecated
- if (userParams.animation === false) {
- params.showClass = {
- popup: '',
- backdrop: 'swal2-backdrop-show swal2-noanimation'
- };
- params.hideClass = {};
- }
- return params;
- };
- var swalPromise = function swalPromise(instance, domCache, innerParams) {
- return new Promise(function (resolve) {
- // functions to handle all closings/dismissals
- var dismissWith = function dismissWith(dismiss) {
- instance.closePopup({
- dismiss: dismiss
- });
- };
- privateMethods.swalPromiseResolve.set(instance, resolve);
- setupTimer(globalState, innerParams, dismissWith);
- domCache.confirmButton.onclick = function () {
- return handleConfirmButtonClick(instance, innerParams);
- };
- domCache.cancelButton.onclick = function () {
- return handleCancelButtonClick(instance, dismissWith);
- };
- domCache.closeButton.onclick = function () {
- return dismissWith(DismissReason.close);
- };
- handlePopupClick(instance, domCache, dismissWith);
- addKeydownHandler(instance, globalState, innerParams, dismissWith);
- if (innerParams.toast && (innerParams.input || innerParams.footer || innerParams.showCloseButton)) {
- addClass(document.body, swalClasses['toast-column']);
- } else {
- removeClass(document.body, swalClasses['toast-column']);
- }
- handleInputOptionsAndValue(instance, innerParams);
- openPopup(innerParams);
- initFocus(domCache, innerParams); // Scroll container to top on open (#1247)
- domCache.container.scrollTop = 0;
- });
- };
- var populateDomCache = function populateDomCache(instance) {
- var domCache = {
- popup: getPopup(),
- container: getContainer(),
- content: getContent(),
- actions: getActions(),
- confirmButton: getConfirmButton(),
- cancelButton: getCancelButton(),
- closeButton: getCloseButton(),
- validationMessage: getValidationMessage(),
- progressSteps: getProgressSteps()
- };
- privateProps.domCache.set(instance, domCache);
- return domCache;
- };
- var setupTimer = function setupTimer(globalState$$1, innerParams, dismissWith) {
- var timerProgressBar = getTimerProgressBar();
- hide(timerProgressBar);
- if (innerParams.timer) {
- globalState$$1.timeout = new Timer(function () {
- dismissWith('timer');
- delete globalState$$1.timeout;
- }, innerParams.timer);
- if (innerParams.timerProgressBar) {
- show(timerProgressBar);
- setTimeout(function () {
- if (globalState$$1.timeout.running) {
- // timer can be already stopped at this point
- animateTimerProgressBar(innerParams.timer);
- }
- });
- }
- }
- };
- var initFocus = function initFocus(domCache, innerParams) {
- if (innerParams.toast) {
- return;
- }
- if (!callIfFunction(innerParams.allowEnterKey)) {
- return blurActiveElement();
- }
- if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {
- return domCache.cancelButton.focus();
- }
- if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {
- return domCache.confirmButton.focus();
- }
- setFocus(innerParams, -1, 1);
- };
- var blurActiveElement = function blurActiveElement() {
- if (document.activeElement && typeof document.activeElement.blur === 'function') {
- document.activeElement.blur();
- }
- };
- /**
- * Updates popup parameters.
- */
- function update(params) {
- var popup = getPopup();
- var innerParams = privateProps.innerParams.get(this);
- if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
- 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.");
- }
- var validUpdatableParams = {}; // assign valid params from `params` to `defaults`
- Object.keys(params).forEach(function (param) {
- if (Swal.isUpdatableParameter(param)) {
- validUpdatableParams[param] = params[param];
- } else {
- warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js"));
- }
- });
- var updatedParams = _extends({}, innerParams, validUpdatableParams);
- render(this, updatedParams);
- privateProps.innerParams.set(this, updatedParams);
- Object.defineProperties(this, {
- params: {
- value: _extends({}, this.params, params),
- writable: false,
- enumerable: true
- }
- });
- }
- function _destroy() {
- var domCache = privateProps.domCache.get(this);
- var innerParams = privateProps.innerParams.get(this);
- if (!innerParams) {
- return; // This instance has already been destroyed
- } // Check if there is another Swal closing
- if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
- globalState.swalCloseEventFinishedCallback();
- delete globalState.swalCloseEventFinishedCallback;
- } // Check if there is a swal disposal defer timer
- if (globalState.deferDisposalTimer) {
- clearTimeout(globalState.deferDisposalTimer);
- delete globalState.deferDisposalTimer;
- }
- if (typeof innerParams.onDestroy === 'function') {
- innerParams.onDestroy();
- }
- disposeSwal(this);
- }
- var disposeSwal = function disposeSwal(instance) {
- // Unset this.params so GC will dispose it (#1569)
- delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)
- delete globalState.keydownHandler;
- delete globalState.keydownTarget; // Unset WeakMaps so GC will be able to dispose them (#1569)
- unsetWeakMaps(privateProps);
- unsetWeakMaps(privateMethods);
- };
- var unsetWeakMaps = function unsetWeakMaps(obj) {
- for (var i in obj) {
- obj[i] = new WeakMap();
- }
- };
- var instanceMethods = /*#__PURE__*/Object.freeze({
- hideLoading: hideLoading,
- disableLoading: hideLoading,
- getInput: getInput$1,
- close: close,
- closePopup: close,
- closeModal: close,
- closeToast: close,
- enableButtons: enableButtons,
- disableButtons: disableButtons,
- enableInput: enableInput,
- disableInput: disableInput,
- showValidationMessage: showValidationMessage,
- resetValidationMessage: resetValidationMessage$1,
- getProgressSteps: getProgressSteps$1,
- _main: _main,
- update: update,
- _destroy: _destroy
- });
- var currentInstance; // SweetAlert constructor
- function SweetAlert() {
- // Prevent run in Node env
- /* istanbul ignore if */
- if (typeof window === 'undefined') {
- return;
- } // Check for the existence of Promise
- /* istanbul ignore if */
- if (typeof Promise === 'undefined') {
- 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)');
- }
- currentInstance = this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- var outerParams = Object.freeze(this.constructor.argsToParams(args));
- Object.defineProperties(this, {
- params: {
- value: outerParams,
- writable: false,
- enumerable: true,
- configurable: true
- }
- });
- var promise = this._main(this.params);
- privateProps.promise.set(this, promise);
- } // `catch` cannot be the name of a module export, so we define our thenable methods here instead
- SweetAlert.prototype.then = function (onFulfilled) {
- var promise = privateProps.promise.get(this);
- return promise.then(onFulfilled);
- };
- SweetAlert.prototype["finally"] = function (onFinally) {
- var promise = privateProps.promise.get(this);
- return promise["finally"](onFinally);
- }; // Assign instance methods from src/instanceMethods/*.js to prototype
- _extends(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor
- _extends(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility
- Object.keys(instanceMethods).forEach(function (key) {
- SweetAlert[key] = function () {
- if (currentInstance) {
- var _currentInstance;
- return (_currentInstance = currentInstance)[key].apply(_currentInstance, arguments);
- }
- };
- });
- SweetAlert.DismissReason = DismissReason;
- SweetAlert.version = '9.8.2';
- var Swal = SweetAlert;
- Swal["default"] = Swal;
- return Swal;
- }));
- if (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}
|