sweetalert2 11.3.5 → 11.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +2272 -0
  2. package/README.md +4 -6
  3. package/package.json +8 -5
  4. package/src/SweetAlert.js +12 -11
  5. package/src/buttons-handlers.js +27 -27
  6. package/src/globalState.js +1 -1
  7. package/src/instanceMethods/_destroy.js +1 -1
  8. package/src/instanceMethods/close.js +25 -23
  9. package/src/instanceMethods/enable-disable-elements.js +7 -7
  10. package/src/instanceMethods/getInput.js +1 -1
  11. package/src/instanceMethods/hideLoading.js +2 -5
  12. package/src/instanceMethods/progress-steps.js +1 -1
  13. package/src/instanceMethods/update.js +20 -13
  14. package/src/instanceMethods/validation-message.js +2 -2
  15. package/src/keydown-handler.js +22 -16
  16. package/src/popup-click-handler.js +3 -1
  17. package/src/privateMethods.js +1 -1
  18. package/src/privateProps.js +1 -1
  19. package/src/staticMethods/argsToParams.js +1 -1
  20. package/src/staticMethods/bindClickHandler.js +1 -1
  21. package/src/staticMethods/dom.js +1 -1
  22. package/src/staticMethods/fire.js +2 -2
  23. package/src/staticMethods/mixin.js +2 -2
  24. package/src/staticMethods/showLoading.js +1 -4
  25. package/src/staticMethods.js +1 -5
  26. package/src/utils/DismissReason.js +1 -1
  27. package/src/utils/Timer.js +6 -6
  28. package/src/utils/aria.js +2 -2
  29. package/src/utils/classes.js +1 -7
  30. package/src/utils/defaultInputValidators.js +1 -1
  31. package/src/utils/dom/animationEndEvent.js +1 -1
  32. package/src/utils/dom/domUtils.js +16 -9
  33. package/src/utils/dom/getters.js +7 -7
  34. package/src/utils/dom/init.js +3 -7
  35. package/src/utils/dom/inputUtils.js +26 -19
  36. package/src/utils/dom/parseHtmlToContainer.js +14 -3
  37. package/src/utils/dom/renderers/renderActions.js +3 -3
  38. package/src/utils/dom/renderers/renderContainer.js +3 -3
  39. package/src/utils/dom/renderers/renderContent.js +4 -2
  40. package/src/utils/dom/renderers/renderIcon.js +24 -15
  41. package/src/utils/dom/renderers/renderInput.js +30 -21
  42. package/src/utils/dom/renderers/renderPopup.js +2 -1
  43. package/src/utils/dom/renderers/renderProgressSteps.js +1 -1
  44. package/src/utils/getTemplateParams.js +36 -5
  45. package/src/utils/iosFix.js +16 -5
  46. package/src/utils/isNodeEnv.js +5 -1
  47. package/src/utils/params.js +2 -2
  48. package/src/utils/setParameters.js +5 -5
  49. package/src/utils/utils.js +5 -3
  50. package/dist/sweetalert2.all.js +0 -3317
  51. package/dist/sweetalert2.all.min.js +0 -2
  52. package/dist/sweetalert2.css +0 -1400
  53. package/dist/sweetalert2.js +0 -3315
  54. package/dist/sweetalert2.min.css +0 -1
  55. package/dist/sweetalert2.min.js +0 -1
@@ -1,3315 +0,0 @@
1
- /*!
2
- * sweetalert2 v11.3.5
3
- * Released under the MIT License.
4
- */
5
- (function (global, factory) {
6
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
7
- typeof define === 'function' && define.amd ? define(factory) :
8
- (global = global || self, global.Sweetalert2 = factory());
9
- }(this, function () { 'use strict';
10
-
11
- const consolePrefix = 'SweetAlert2:';
12
- /**
13
- * Filter the unique values into a new array
14
- * @param arr
15
- */
16
-
17
- const uniqueArray = arr => {
18
- const result = [];
19
-
20
- for (let i = 0; i < arr.length; i++) {
21
- if (result.indexOf(arr[i]) === -1) {
22
- result.push(arr[i]);
23
- }
24
- }
25
-
26
- return result;
27
- };
28
- /**
29
- * Capitalize the first letter of a string
30
- * @param {string} str
31
- * @returns {string}
32
- */
33
-
34
- const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
35
- /**
36
- * @param {NodeList | HTMLCollection | NamedNodeMap} nodeList
37
- * @returns {array}
38
- */
39
-
40
- const toArray = nodeList => Array.prototype.slice.call(nodeList);
41
- /**
42
- * Standardize console warnings
43
- * @param {string | array} message
44
- */
45
-
46
- const warn = message => {
47
- console.warn("".concat(consolePrefix, " ").concat(typeof message === 'object' ? message.join(' ') : message));
48
- };
49
- /**
50
- * Standardize console errors
51
- * @param {string} message
52
- */
53
-
54
- const error = message => {
55
- console.error("".concat(consolePrefix, " ").concat(message));
56
- };
57
- /**
58
- * Private global state for `warnOnce`
59
- * @type {Array}
60
- * @private
61
- */
62
-
63
- const previousWarnOnceMessages = [];
64
- /**
65
- * Show a console warning, but only if it hasn't already been shown
66
- * @param {string} message
67
- */
68
-
69
- const warnOnce = message => {
70
- if (!previousWarnOnceMessages.includes(message)) {
71
- previousWarnOnceMessages.push(message);
72
- warn(message);
73
- }
74
- };
75
- /**
76
- * Show a one-time console warning about deprecated params/methods
77
- */
78
-
79
- const warnAboutDeprecation = (deprecatedParam, useInstead) => {
80
- warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead."));
81
- };
82
- /**
83
- * If `arg` is a function, call it (with no arguments or context) and return the result.
84
- * Otherwise, just pass the value through
85
- * @param arg
86
- */
87
-
88
- const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
89
- const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
90
- const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
91
- const isPromise = arg => arg && Promise.resolve(arg) === arg;
92
-
93
- const defaultParams = {
94
- title: '',
95
- titleText: '',
96
- text: '',
97
- html: '',
98
- footer: '',
99
- icon: undefined,
100
- iconColor: undefined,
101
- iconHtml: undefined,
102
- template: undefined,
103
- toast: false,
104
- showClass: {
105
- popup: 'swal2-show',
106
- backdrop: 'swal2-backdrop-show',
107
- icon: 'swal2-icon-show'
108
- },
109
- hideClass: {
110
- popup: 'swal2-hide',
111
- backdrop: 'swal2-backdrop-hide',
112
- icon: 'swal2-icon-hide'
113
- },
114
- customClass: {},
115
- target: 'body',
116
- color: undefined,
117
- backdrop: true,
118
- heightAuto: true,
119
- allowOutsideClick: true,
120
- allowEscapeKey: true,
121
- allowEnterKey: true,
122
- stopKeydownPropagation: true,
123
- keydownListenerCapture: false,
124
- showConfirmButton: true,
125
- showDenyButton: false,
126
- showCancelButton: false,
127
- preConfirm: undefined,
128
- preDeny: undefined,
129
- confirmButtonText: 'OK',
130
- confirmButtonAriaLabel: '',
131
- confirmButtonColor: undefined,
132
- denyButtonText: 'No',
133
- denyButtonAriaLabel: '',
134
- denyButtonColor: undefined,
135
- cancelButtonText: 'Cancel',
136
- cancelButtonAriaLabel: '',
137
- cancelButtonColor: undefined,
138
- buttonsStyling: true,
139
- reverseButtons: false,
140
- focusConfirm: true,
141
- focusDeny: false,
142
- focusCancel: false,
143
- returnFocus: true,
144
- showCloseButton: false,
145
- closeButtonHtml: '&times;',
146
- closeButtonAriaLabel: 'Close this dialog',
147
- loaderHtml: '',
148
- showLoaderOnConfirm: false,
149
- showLoaderOnDeny: false,
150
- imageUrl: undefined,
151
- imageWidth: undefined,
152
- imageHeight: undefined,
153
- imageAlt: '',
154
- timer: undefined,
155
- timerProgressBar: false,
156
- width: undefined,
157
- padding: undefined,
158
- background: undefined,
159
- input: undefined,
160
- inputPlaceholder: '',
161
- inputLabel: '',
162
- inputValue: '',
163
- inputOptions: {},
164
- inputAutoTrim: true,
165
- inputAttributes: {},
166
- inputValidator: undefined,
167
- returnInputValueOnDeny: false,
168
- validationMessage: undefined,
169
- grow: false,
170
- position: 'center',
171
- progressSteps: [],
172
- currentProgressStep: undefined,
173
- progressStepsDistance: undefined,
174
- willOpen: undefined,
175
- didOpen: undefined,
176
- didRender: undefined,
177
- willClose: undefined,
178
- didClose: undefined,
179
- didDestroy: undefined,
180
- scrollbarPadding: true
181
- };
182
- const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];
183
- const deprecatedParams = {};
184
- const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
185
- /**
186
- * Is valid parameter
187
- * @param {string} paramName
188
- */
189
-
190
- const isValidParameter = paramName => {
191
- return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
192
- };
193
- /**
194
- * Is valid parameter for Swal.update() method
195
- * @param {string} paramName
196
- */
197
-
198
- const isUpdatableParameter = paramName => {
199
- return updatableParams.indexOf(paramName) !== -1;
200
- };
201
- /**
202
- * Is deprecated parameter
203
- * @param {string} paramName
204
- */
205
-
206
- const isDeprecatedParameter = paramName => {
207
- return deprecatedParams[paramName];
208
- };
209
-
210
- const checkIfParamIsValid = param => {
211
- if (!isValidParameter(param)) {
212
- warn("Unknown parameter \"".concat(param, "\""));
213
- }
214
- };
215
-
216
- const checkIfToastParamIsValid = param => {
217
- if (toastIncompatibleParams.includes(param)) {
218
- warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
219
- }
220
- };
221
-
222
- const checkIfParamIsDeprecated = param => {
223
- if (isDeprecatedParameter(param)) {
224
- warnAboutDeprecation(param, isDeprecatedParameter(param));
225
- }
226
- };
227
- /**
228
- * Show relevant warnings for given params
229
- *
230
- * @param params
231
- */
232
-
233
-
234
- const showWarningsForParams = params => {
235
- if (!params.backdrop && params.allowOutsideClick) {
236
- warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
237
- }
238
-
239
- for (const param in params) {
240
- checkIfParamIsValid(param);
241
-
242
- if (params.toast) {
243
- checkIfToastParamIsValid(param);
244
- }
245
-
246
- checkIfParamIsDeprecated(param);
247
- }
248
- };
249
-
250
- const swalPrefix = 'swal2-';
251
- const prefix = items => {
252
- const result = {};
253
-
254
- for (const i in items) {
255
- result[items[i]] = swalPrefix + items[i];
256
- }
257
-
258
- return result;
259
- };
260
- const swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']);
261
- const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
262
-
263
- /**
264
- * Gets the popup container which contains the backdrop and the popup itself.
265
- *
266
- * @returns {HTMLElement | null}
267
- */
268
-
269
- const getContainer = () => document.body.querySelector(".".concat(swalClasses.container));
270
- const elementBySelector = selectorString => {
271
- const container = getContainer();
272
- return container ? container.querySelector(selectorString) : null;
273
- };
274
-
275
- const elementByClass = className => {
276
- return elementBySelector(".".concat(className));
277
- };
278
-
279
- const getPopup = () => elementByClass(swalClasses.popup);
280
- const getIcon = () => elementByClass(swalClasses.icon);
281
- const getTitle = () => elementByClass(swalClasses.title);
282
- const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
283
- const getImage = () => elementByClass(swalClasses.image);
284
- const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
285
- const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
286
- const getConfirmButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm));
287
- const getDenyButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny));
288
- const getInputLabel = () => elementByClass(swalClasses['input-label']);
289
- const getLoader = () => elementBySelector(".".concat(swalClasses.loader));
290
- const getCancelButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel));
291
- const getActions = () => elementByClass(swalClasses.actions);
292
- const getFooter = () => elementByClass(swalClasses.footer);
293
- const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
294
- const getCloseButton = () => elementByClass(swalClasses.close); // https://github.com/jkup/focusable/blob/master/index.js
295
-
296
- const 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";
297
- const getFocusableElements = () => {
298
- const focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex
299
- .sort((a, b) => {
300
- const tabindexA = parseInt(a.getAttribute('tabindex'));
301
- const tabindexB = parseInt(b.getAttribute('tabindex'));
302
-
303
- if (tabindexA > tabindexB) {
304
- return 1;
305
- } else if (tabindexA < tabindexB) {
306
- return -1;
307
- }
308
-
309
- return 0;
310
- });
311
- const otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1');
312
- return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible(el));
313
- };
314
- const isModal = () => {
315
- return !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
316
- };
317
- const isToast = () => {
318
- return getPopup() && hasClass(getPopup(), swalClasses.toast);
319
- };
320
- const isLoading = () => {
321
- return getPopup().hasAttribute('data-loading');
322
- };
323
-
324
- const states = {
325
- previousBodyPadding: null
326
- };
327
- /**
328
- * Securely set innerHTML of an element
329
- * https://github.com/sweetalert2/sweetalert2/issues/1926
330
- *
331
- * @param {HTMLElement} elem
332
- * @param {string} html
333
- */
334
-
335
- const setInnerHtml = (elem, html) => {
336
- elem.textContent = '';
337
-
338
- if (html) {
339
- const parser = new DOMParser();
340
- const parsed = parser.parseFromString(html, "text/html");
341
- toArray(parsed.querySelector('head').childNodes).forEach(child => {
342
- elem.appendChild(child);
343
- });
344
- toArray(parsed.querySelector('body').childNodes).forEach(child => {
345
- elem.appendChild(child);
346
- });
347
- }
348
- };
349
- /**
350
- * @param {HTMLElement} elem
351
- * @param {string} className
352
- * @returns {boolean}
353
- */
354
-
355
- const hasClass = (elem, className) => {
356
- if (!className) {
357
- return false;
358
- }
359
-
360
- const classList = className.split(/\s+/);
361
-
362
- for (let i = 0; i < classList.length; i++) {
363
- if (!elem.classList.contains(classList[i])) {
364
- return false;
365
- }
366
- }
367
-
368
- return true;
369
- };
370
-
371
- const removeCustomClasses = (elem, params) => {
372
- toArray(elem.classList).forEach(className => {
373
- if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) {
374
- elem.classList.remove(className);
375
- }
376
- });
377
- };
378
-
379
- const applyCustomClass = (elem, params, className) => {
380
- removeCustomClasses(elem, params);
381
-
382
- if (params.customClass && params.customClass[className]) {
383
- if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
384
- return warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(typeof params.customClass[className], "\""));
385
- }
386
-
387
- addClass(elem, params.customClass[className]);
388
- }
389
- };
390
- /**
391
- * @param {HTMLElement} popup
392
- * @param {string} inputType
393
- * @returns {HTMLInputElement | null}
394
- */
395
-
396
- const getInput = (popup, inputType) => {
397
- if (!inputType) {
398
- return null;
399
- }
400
-
401
- switch (inputType) {
402
- case 'select':
403
- case 'textarea':
404
- case 'file':
405
- return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses[inputType]));
406
-
407
- case 'checkbox':
408
- return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.checkbox, " input"));
409
-
410
- case 'radio':
411
- return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:checked")) || popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:first-child"));
412
-
413
- case 'range':
414
- return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.range, " input"));
415
-
416
- default:
417
- return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.input));
418
- }
419
- };
420
- /**
421
- * @param {HTMLInputElement} input
422
- */
423
-
424
- const focusInput = input => {
425
- input.focus(); // place cursor at end of text in text input
426
-
427
- if (input.type !== 'file') {
428
- // http://stackoverflow.com/a/2345915
429
- const val = input.value;
430
- input.value = '';
431
- input.value = val;
432
- }
433
- };
434
- /**
435
- * @param {HTMLElement | HTMLElement[] | null} target
436
- * @param {string | string[]} classList
437
- * @param {boolean} condition
438
- */
439
-
440
- const toggleClass = (target, classList, condition) => {
441
- if (!target || !classList) {
442
- return;
443
- }
444
-
445
- if (typeof classList === 'string') {
446
- classList = classList.split(/\s+/).filter(Boolean);
447
- }
448
-
449
- classList.forEach(className => {
450
- if (Array.isArray(target)) {
451
- target.forEach(elem => {
452
- condition ? elem.classList.add(className) : elem.classList.remove(className);
453
- });
454
- } else {
455
- condition ? target.classList.add(className) : target.classList.remove(className);
456
- }
457
- });
458
- };
459
- /**
460
- * @param {HTMLElement | HTMLElement[] | null} target
461
- * @param {string | string[]} classList
462
- */
463
-
464
- const addClass = (target, classList) => {
465
- toggleClass(target, classList, true);
466
- };
467
- /**
468
- * @param {HTMLElement | HTMLElement[] | null} target
469
- * @param {string | string[]} classList
470
- */
471
-
472
- const removeClass = (target, classList) => {
473
- toggleClass(target, classList, false);
474
- };
475
- /**
476
- * Get direct child of an element by class name
477
- *
478
- * @param {HTMLElement} elem
479
- * @param {string} className
480
- * @returns {HTMLElement | null}
481
- */
482
-
483
- const getDirectChildByClass = (elem, className) => {
484
- const childNodes = toArray(elem.childNodes);
485
-
486
- for (let i = 0; i < childNodes.length; i++) {
487
- if (hasClass(childNodes[i], className)) {
488
- return childNodes[i];
489
- }
490
- }
491
- };
492
- /**
493
- * @param {HTMLElement} elem
494
- * @param {string} property
495
- * @param {*} value
496
- */
497
-
498
- const applyNumericalStyle = (elem, property, value) => {
499
- if (value === "".concat(parseInt(value))) {
500
- value = parseInt(value);
501
- }
502
-
503
- if (value || parseInt(value) === 0) {
504
- elem.style[property] = typeof value === 'number' ? "".concat(value, "px") : value;
505
- } else {
506
- elem.style.removeProperty(property);
507
- }
508
- };
509
- /**
510
- * @param {HTMLElement} elem
511
- * @param {string} display
512
- */
513
-
514
- const show = function (elem) {
515
- let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
516
- elem.style.display = display;
517
- };
518
- /**
519
- * @param {HTMLElement} elem
520
- */
521
-
522
- const hide = elem => {
523
- elem.style.display = 'none';
524
- };
525
- const setStyle = (parent, selector, property, value) => {
526
- const el = parent.querySelector(selector);
527
-
528
- if (el) {
529
- el.style[property] = value;
530
- }
531
- };
532
- const toggle = (elem, condition, display) => {
533
- condition ? show(elem, display) : hide(elem);
534
- }; // borrowed from jquery $(elem).is(':visible') implementation
535
-
536
- const isVisible = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
537
- const allButtonsAreHidden = () => !isVisible(getConfirmButton()) && !isVisible(getDenyButton()) && !isVisible(getCancelButton());
538
- const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight); // borrowed from https://stackoverflow.com/a/46352119
539
-
540
- const hasCssAnimation = elem => {
541
- const style = window.getComputedStyle(elem);
542
- const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
543
- const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
544
- return animDuration > 0 || transDuration > 0;
545
- };
546
- const animateTimerProgressBar = function (timer) {
547
- let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
548
- const timerProgressBar = getTimerProgressBar();
549
-
550
- if (isVisible(timerProgressBar)) {
551
- if (reset) {
552
- timerProgressBar.style.transition = 'none';
553
- timerProgressBar.style.width = '100%';
554
- }
555
-
556
- setTimeout(() => {
557
- timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear");
558
- timerProgressBar.style.width = '0%';
559
- }, 10);
560
- }
561
- };
562
- const stopTimerProgressBar = () => {
563
- const timerProgressBar = getTimerProgressBar();
564
- const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
565
- timerProgressBar.style.removeProperty('transition');
566
- timerProgressBar.style.width = '100%';
567
- const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
568
- const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
569
- timerProgressBar.style.removeProperty('transition');
570
- timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%");
571
- };
572
-
573
- // Detect Node env
574
- const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
575
-
576
- const RESTORE_FOCUS_TIMEOUT = 100;
577
-
578
- const globalState = {};
579
-
580
- const focusPreviousActiveElement = () => {
581
- if (globalState.previousActiveElement && globalState.previousActiveElement.focus) {
582
- globalState.previousActiveElement.focus();
583
- globalState.previousActiveElement = null;
584
- } else if (document.body) {
585
- document.body.focus();
586
- }
587
- }; // Restore previous active (focused) element
588
-
589
-
590
- const restoreActiveElement = returnFocus => {
591
- return new Promise(resolve => {
592
- if (!returnFocus) {
593
- return resolve();
594
- }
595
-
596
- const x = window.scrollX;
597
- const y = window.scrollY;
598
- globalState.restoreFocusTimeout = setTimeout(() => {
599
- focusPreviousActiveElement();
600
- resolve();
601
- }, RESTORE_FOCUS_TIMEOUT); // issues/900
602
-
603
- window.scrollTo(x, y);
604
- });
605
- };
606
-
607
- const sweetHTML = "\n <div aria-labelledby=\"".concat(swalClasses.title, "\" aria-describedby=\"").concat(swalClasses['html-container'], "\" class=\"").concat(swalClasses.popup, "\" tabindex=\"-1\">\n <button type=\"button\" class=\"").concat(swalClasses.close, "\"></button>\n <ul class=\"").concat(swalClasses['progress-steps'], "\"></ul>\n <div class=\"").concat(swalClasses.icon, "\"></div>\n <img class=\"").concat(swalClasses.image, "\" />\n <h2 class=\"").concat(swalClasses.title, "\" id=\"").concat(swalClasses.title, "\"></h2>\n <div class=\"").concat(swalClasses['html-container'], "\" id=\"").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 class=\"").concat(swalClasses.actions, "\">\n <div class=\"").concat(swalClasses.loader, "\"></div>\n <button type=\"button\" class=\"").concat(swalClasses.confirm, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.deny, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.cancel, "\"></button>\n </div>\n <div class=\"").concat(swalClasses.footer, "\"></div>\n <div class=\"").concat(swalClasses['timer-progress-bar-container'], "\">\n <div class=\"").concat(swalClasses['timer-progress-bar'], "\"></div>\n </div>\n </div>\n").replace(/(^|\n)\s*/g, '');
608
-
609
- const resetOldContainer = () => {
610
- const oldContainer = getContainer();
611
-
612
- if (!oldContainer) {
613
- return false;
614
- }
615
-
616
- oldContainer.remove();
617
- removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
618
- return true;
619
- };
620
-
621
- const resetValidationMessage = () => {
622
- globalState.currentInstance.resetValidationMessage();
623
- };
624
-
625
- const addInputChangeListeners = () => {
626
- const popup = getPopup();
627
- const input = getDirectChildByClass(popup, swalClasses.input);
628
- const file = getDirectChildByClass(popup, swalClasses.file);
629
- const range = popup.querySelector(".".concat(swalClasses.range, " input"));
630
- const rangeOutput = popup.querySelector(".".concat(swalClasses.range, " output"));
631
- const select = getDirectChildByClass(popup, swalClasses.select);
632
- const checkbox = popup.querySelector(".".concat(swalClasses.checkbox, " input"));
633
- const textarea = getDirectChildByClass(popup, swalClasses.textarea);
634
- input.oninput = resetValidationMessage;
635
- file.onchange = resetValidationMessage;
636
- select.onchange = resetValidationMessage;
637
- checkbox.onchange = resetValidationMessage;
638
- textarea.oninput = resetValidationMessage;
639
-
640
- range.oninput = () => {
641
- resetValidationMessage();
642
- rangeOutput.value = range.value;
643
- };
644
-
645
- range.onchange = () => {
646
- resetValidationMessage();
647
- range.nextSibling.value = range.value;
648
- };
649
- };
650
-
651
- const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;
652
-
653
- const setupAccessibility = params => {
654
- const popup = getPopup();
655
- popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
656
- popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
657
-
658
- if (!params.toast) {
659
- popup.setAttribute('aria-modal', 'true');
660
- }
661
- };
662
-
663
- const setupRTL = targetElement => {
664
- if (window.getComputedStyle(targetElement).direction === 'rtl') {
665
- addClass(getContainer(), swalClasses.rtl);
666
- }
667
- };
668
- /*
669
- * Add modal + backdrop to DOM
670
- */
671
-
672
-
673
- const init = params => {
674
- // Clean up the old popup container if it exists
675
- const oldContainerExisted = resetOldContainer();
676
- /* istanbul ignore if */
677
-
678
- if (isNodeEnv()) {
679
- error('SweetAlert2 requires document to initialize');
680
- return;
681
- }
682
-
683
- const container = document.createElement('div');
684
- container.className = swalClasses.container;
685
-
686
- if (oldContainerExisted) {
687
- addClass(container, swalClasses['no-transition']);
688
- }
689
-
690
- setInnerHtml(container, sweetHTML);
691
- const targetElement = getTarget(params.target);
692
- targetElement.appendChild(container);
693
- setupAccessibility(params);
694
- setupRTL(targetElement);
695
- addInputChangeListeners();
696
- };
697
-
698
- const parseHtmlToContainer = (param, target) => {
699
- // DOM element
700
- if (param instanceof HTMLElement) {
701
- target.appendChild(param); // Object
702
- } else if (typeof param === 'object') {
703
- handleObject(param, target); // Plain string
704
- } else if (param) {
705
- setInnerHtml(target, param);
706
- }
707
- };
708
-
709
- const handleObject = (param, target) => {
710
- // JQuery element(s)
711
- if (param.jquery) {
712
- handleJqueryElem(target, param); // For other objects use their string representation
713
- } else {
714
- setInnerHtml(target, param.toString());
715
- }
716
- };
717
-
718
- const handleJqueryElem = (target, elem) => {
719
- target.textContent = '';
720
-
721
- if (0 in elem) {
722
- for (let i = 0; (i in elem); i++) {
723
- target.appendChild(elem[i].cloneNode(true));
724
- }
725
- } else {
726
- target.appendChild(elem.cloneNode(true));
727
- }
728
- };
729
-
730
- const animationEndEvent = (() => {
731
- // Prevent run in Node env
732
-
733
- /* istanbul ignore if */
734
- if (isNodeEnv()) {
735
- return false;
736
- }
737
-
738
- const testEl = document.createElement('div');
739
- const transEndEventNames = {
740
- WebkitAnimation: 'webkitAnimationEnd',
741
- // Chrome, Safari and Opera
742
- animation: 'animationend' // Standard syntax
743
-
744
- };
745
-
746
- for (const i in transEndEventNames) {
747
- if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
748
- return transEndEventNames[i];
749
- }
750
- }
751
-
752
- return false;
753
- })();
754
-
755
- // https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
756
-
757
- const measureScrollbar = () => {
758
- const scrollDiv = document.createElement('div');
759
- scrollDiv.className = swalClasses['scrollbar-measure'];
760
- document.body.appendChild(scrollDiv);
761
- const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
762
- document.body.removeChild(scrollDiv);
763
- return scrollbarWidth;
764
- };
765
-
766
- const renderActions = (instance, params) => {
767
- const actions = getActions();
768
- const loader = getLoader(); // Actions (buttons) wrapper
769
-
770
- if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
771
- hide(actions);
772
- } else {
773
- show(actions);
774
- } // Custom class
775
-
776
-
777
- applyCustomClass(actions, params, 'actions'); // Render all the buttons
778
-
779
- renderButtons(actions, loader, params); // Loader
780
-
781
- setInnerHtml(loader, params.loaderHtml);
782
- applyCustomClass(loader, params, 'loader');
783
- };
784
-
785
- function renderButtons(actions, loader, params) {
786
- const confirmButton = getConfirmButton();
787
- const denyButton = getDenyButton();
788
- const cancelButton = getCancelButton(); // Render buttons
789
-
790
- renderButton(confirmButton, 'confirm', params);
791
- renderButton(denyButton, 'deny', params);
792
- renderButton(cancelButton, 'cancel', params);
793
- handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
794
-
795
- if (params.reverseButtons) {
796
- if (params.toast) {
797
- actions.insertBefore(cancelButton, confirmButton);
798
- actions.insertBefore(denyButton, confirmButton);
799
- } else {
800
- actions.insertBefore(cancelButton, loader);
801
- actions.insertBefore(denyButton, loader);
802
- actions.insertBefore(confirmButton, loader);
803
- }
804
- }
805
- }
806
-
807
- function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
808
- if (!params.buttonsStyling) {
809
- return removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
810
- }
811
-
812
- addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors
813
-
814
- if (params.confirmButtonColor) {
815
- confirmButton.style.backgroundColor = params.confirmButtonColor;
816
- addClass(confirmButton, swalClasses['default-outline']);
817
- }
818
-
819
- if (params.denyButtonColor) {
820
- denyButton.style.backgroundColor = params.denyButtonColor;
821
- addClass(denyButton, swalClasses['default-outline']);
822
- }
823
-
824
- if (params.cancelButtonColor) {
825
- cancelButton.style.backgroundColor = params.cancelButtonColor;
826
- addClass(cancelButton, swalClasses['default-outline']);
827
- }
828
- }
829
-
830
- function renderButton(button, buttonType, params) {
831
- toggle(button, params["show".concat(capitalizeFirstLetter(buttonType), "Button")], 'inline-block');
832
- setInnerHtml(button, params["".concat(buttonType, "ButtonText")]); // Set caption text
833
-
834
- button.setAttribute('aria-label', params["".concat(buttonType, "ButtonAriaLabel")]); // ARIA label
835
- // Add buttons custom classes
836
-
837
- button.className = swalClasses[buttonType];
838
- applyCustomClass(button, params, "".concat(buttonType, "Button"));
839
- addClass(button, params["".concat(buttonType, "ButtonClass")]);
840
- }
841
-
842
- function handleBackdropParam(container, backdrop) {
843
- if (typeof backdrop === 'string') {
844
- container.style.background = backdrop;
845
- } else if (!backdrop) {
846
- addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
847
- }
848
- }
849
-
850
- function handlePositionParam(container, position) {
851
- if (position in swalClasses) {
852
- addClass(container, swalClasses[position]);
853
- } else {
854
- warn('The "position" parameter is not valid, defaulting to "center"');
855
- addClass(container, swalClasses.center);
856
- }
857
- }
858
-
859
- function handleGrowParam(container, grow) {
860
- if (grow && typeof grow === 'string') {
861
- const growClass = "grow-".concat(grow);
862
-
863
- if (growClass in swalClasses) {
864
- addClass(container, swalClasses[growClass]);
865
- }
866
- }
867
- }
868
-
869
- const renderContainer = (instance, params) => {
870
- const container = getContainer();
871
-
872
- if (!container) {
873
- return;
874
- }
875
-
876
- handleBackdropParam(container, params.backdrop);
877
- handlePositionParam(container, params.position);
878
- handleGrowParam(container, params.grow); // Custom class
879
-
880
- applyCustomClass(container, params, 'container');
881
- };
882
-
883
- /**
884
- * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
885
- * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
886
- * This is the approach that Babel will probably take to implement private methods/fields
887
- * https://github.com/tc39/proposal-private-methods
888
- * https://github.com/babel/babel/pull/7555
889
- * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
890
- * then we can use that language feature.
891
- */
892
- var privateProps = {
893
- awaitingPromise: new WeakMap(),
894
- promise: new WeakMap(),
895
- innerParams: new WeakMap(),
896
- domCache: new WeakMap()
897
- };
898
-
899
- const inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
900
- const renderInput = (instance, params) => {
901
- const popup = getPopup();
902
- const innerParams = privateProps.innerParams.get(instance);
903
- const rerender = !innerParams || params.input !== innerParams.input;
904
- inputTypes.forEach(inputType => {
905
- const inputClass = swalClasses[inputType];
906
- const inputContainer = getDirectChildByClass(popup, inputClass); // set attributes
907
-
908
- setAttributes(inputType, params.inputAttributes); // set class
909
-
910
- inputContainer.className = inputClass;
911
-
912
- if (rerender) {
913
- hide(inputContainer);
914
- }
915
- });
916
-
917
- if (params.input) {
918
- if (rerender) {
919
- showInput(params);
920
- } // set custom class
921
-
922
-
923
- setCustomClass(params);
924
- }
925
- };
926
-
927
- const showInput = params => {
928
- if (!renderInputType[params.input]) {
929
- return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\""));
930
- }
931
-
932
- const inputContainer = getInputContainer(params.input);
933
- const input = renderInputType[params.input](inputContainer, params);
934
- show(input); // input autofocus
935
-
936
- setTimeout(() => {
937
- focusInput(input);
938
- });
939
- };
940
-
941
- const removeAttributes = input => {
942
- for (let i = 0; i < input.attributes.length; i++) {
943
- const attrName = input.attributes[i].name;
944
-
945
- if (!['type', 'value', 'style'].includes(attrName)) {
946
- input.removeAttribute(attrName);
947
- }
948
- }
949
- };
950
-
951
- const setAttributes = (inputType, inputAttributes) => {
952
- const input = getInput(getPopup(), inputType);
953
-
954
- if (!input) {
955
- return;
956
- }
957
-
958
- removeAttributes(input);
959
-
960
- for (const attr in inputAttributes) {
961
- input.setAttribute(attr, inputAttributes[attr]);
962
- }
963
- };
964
-
965
- const setCustomClass = params => {
966
- const inputContainer = getInputContainer(params.input);
967
-
968
- if (params.customClass) {
969
- addClass(inputContainer, params.customClass.input);
970
- }
971
- };
972
-
973
- const setInputPlaceholder = (input, params) => {
974
- if (!input.placeholder || params.inputPlaceholder) {
975
- input.placeholder = params.inputPlaceholder;
976
- }
977
- };
978
-
979
- const setInputLabel = (input, prependTo, params) => {
980
- if (params.inputLabel) {
981
- input.id = swalClasses.input;
982
- const label = document.createElement('label');
983
- const labelClass = swalClasses['input-label'];
984
- label.setAttribute('for', input.id);
985
- label.className = labelClass;
986
- addClass(label, params.customClass.inputLabel);
987
- label.innerText = params.inputLabel;
988
- prependTo.insertAdjacentElement('beforebegin', label);
989
- }
990
- };
991
-
992
- const getInputContainer = inputType => {
993
- const inputClass = swalClasses[inputType] ? swalClasses[inputType] : swalClasses.input;
994
- return getDirectChildByClass(getPopup(), inputClass);
995
- };
996
-
997
- const renderInputType = {};
998
-
999
- renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => {
1000
- if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') {
1001
- input.value = params.inputValue;
1002
- } else if (!isPromise(params.inputValue)) {
1003
- warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(typeof params.inputValue, "\""));
1004
- }
1005
-
1006
- setInputLabel(input, input, params);
1007
- setInputPlaceholder(input, params);
1008
- input.type = params.input;
1009
- return input;
1010
- };
1011
-
1012
- renderInputType.file = (input, params) => {
1013
- setInputLabel(input, input, params);
1014
- setInputPlaceholder(input, params);
1015
- return input;
1016
- };
1017
-
1018
- renderInputType.range = (range, params) => {
1019
- const rangeInput = range.querySelector('input');
1020
- const rangeOutput = range.querySelector('output');
1021
- rangeInput.value = params.inputValue;
1022
- rangeInput.type = params.input;
1023
- rangeOutput.value = params.inputValue;
1024
- setInputLabel(rangeInput, range, params);
1025
- return range;
1026
- };
1027
-
1028
- renderInputType.select = (select, params) => {
1029
- select.textContent = '';
1030
-
1031
- if (params.inputPlaceholder) {
1032
- const placeholder = document.createElement('option');
1033
- setInnerHtml(placeholder, params.inputPlaceholder);
1034
- placeholder.value = '';
1035
- placeholder.disabled = true;
1036
- placeholder.selected = true;
1037
- select.appendChild(placeholder);
1038
- }
1039
-
1040
- setInputLabel(select, select, params);
1041
- return select;
1042
- };
1043
-
1044
- renderInputType.radio = radio => {
1045
- radio.textContent = '';
1046
- return radio;
1047
- };
1048
-
1049
- renderInputType.checkbox = (checkboxContainer, params) => {
1050
- /** @type {HTMLInputElement} */
1051
- const checkbox = getInput(getPopup(), 'checkbox');
1052
- checkbox.value = '1';
1053
- checkbox.id = swalClasses.checkbox;
1054
- checkbox.checked = Boolean(params.inputValue);
1055
- const label = checkboxContainer.querySelector('span');
1056
- setInnerHtml(label, params.inputPlaceholder);
1057
- return checkboxContainer;
1058
- };
1059
-
1060
- renderInputType.textarea = (textarea, params) => {
1061
- textarea.value = params.inputValue;
1062
- setInputPlaceholder(textarea, params);
1063
- setInputLabel(textarea, textarea, params);
1064
-
1065
- const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);
1066
-
1067
- setTimeout(() => {
1068
- // #2291
1069
- if ('MutationObserver' in window) {
1070
- // #1699
1071
- const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
1072
-
1073
- const textareaResizeHandler = () => {
1074
- const textareaWidth = textarea.offsetWidth + getMargin(textarea);
1075
-
1076
- if (textareaWidth > initialPopupWidth) {
1077
- getPopup().style.width = "".concat(textareaWidth, "px");
1078
- } else {
1079
- getPopup().style.width = null;
1080
- }
1081
- };
1082
-
1083
- new MutationObserver(textareaResizeHandler).observe(textarea, {
1084
- attributes: true,
1085
- attributeFilter: ['style']
1086
- });
1087
- }
1088
- });
1089
- return textarea;
1090
- };
1091
-
1092
- const renderContent = (instance, params) => {
1093
- const htmlContainer = getHtmlContainer();
1094
- applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML
1095
-
1096
- if (params.html) {
1097
- parseHtmlToContainer(params.html, htmlContainer);
1098
- show(htmlContainer, 'block'); // Content as plain text
1099
- } else if (params.text) {
1100
- htmlContainer.textContent = params.text;
1101
- show(htmlContainer, 'block'); // No content
1102
- } else {
1103
- hide(htmlContainer);
1104
- }
1105
-
1106
- renderInput(instance, params);
1107
- };
1108
-
1109
- const renderFooter = (instance, params) => {
1110
- const footer = getFooter();
1111
- toggle(footer, params.footer);
1112
-
1113
- if (params.footer) {
1114
- parseHtmlToContainer(params.footer, footer);
1115
- } // Custom class
1116
-
1117
-
1118
- applyCustomClass(footer, params, 'footer');
1119
- };
1120
-
1121
- const renderCloseButton = (instance, params) => {
1122
- const closeButton = getCloseButton();
1123
- setInnerHtml(closeButton, params.closeButtonHtml); // Custom class
1124
-
1125
- applyCustomClass(closeButton, params, 'closeButton');
1126
- toggle(closeButton, params.showCloseButton);
1127
- closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
1128
- };
1129
-
1130
- const renderIcon = (instance, params) => {
1131
- const innerParams = privateProps.innerParams.get(instance);
1132
- const icon = getIcon(); // if the given icon already rendered, apply the styling without re-rendering the icon
1133
-
1134
- if (innerParams && params.icon === innerParams.icon) {
1135
- // Custom or default content
1136
- setContent(icon, params);
1137
- applyStyles(icon, params);
1138
- return;
1139
- }
1140
-
1141
- if (!params.icon && !params.iconHtml) {
1142
- return hide(icon);
1143
- }
1144
-
1145
- if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
1146
- error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\""));
1147
- return hide(icon);
1148
- }
1149
-
1150
- show(icon); // Custom or default content
1151
-
1152
- setContent(icon, params);
1153
- applyStyles(icon, params); // Animate icon
1154
-
1155
- addClass(icon, params.showClass.icon);
1156
- };
1157
-
1158
- const applyStyles = (icon, params) => {
1159
- for (const iconType in iconTypes) {
1160
- if (params.icon !== iconType) {
1161
- removeClass(icon, iconTypes[iconType]);
1162
- }
1163
- }
1164
-
1165
- addClass(icon, iconTypes[params.icon]); // Icon color
1166
-
1167
- setColor(icon, params); // Success icon background color
1168
-
1169
- adjustSuccessIconBackgroundColor(); // Custom class
1170
-
1171
- applyCustomClass(icon, params, 'icon');
1172
- }; // Adjust success icon background color to match the popup background color
1173
-
1174
-
1175
- const adjustSuccessIconBackgroundColor = () => {
1176
- const popup = getPopup();
1177
- const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
1178
- const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
1179
-
1180
- for (let i = 0; i < successIconParts.length; i++) {
1181
- successIconParts[i].style.backgroundColor = popupBackgroundColor;
1182
- }
1183
- };
1184
-
1185
- const setContent = (icon, params) => {
1186
- icon.textContent = '';
1187
-
1188
- if (params.iconHtml) {
1189
- setInnerHtml(icon, iconContent(params.iconHtml));
1190
- } else if (params.icon === 'success') {
1191
- setInnerHtml(icon, "\n <div class=\"swal2-success-circular-line-left\"></div>\n <span class=\"swal2-success-line-tip\"></span> <span class=\"swal2-success-line-long\"></span>\n <div class=\"swal2-success-ring\"></div> <div class=\"swal2-success-fix\"></div>\n <div class=\"swal2-success-circular-line-right\"></div>\n ");
1192
- } else if (params.icon === 'error') {
1193
- setInnerHtml(icon, "\n <span class=\"swal2-x-mark\">\n <span class=\"swal2-x-mark-line-left\"></span>\n <span class=\"swal2-x-mark-line-right\"></span>\n </span>\n ");
1194
- } else {
1195
- const defaultIconHtml = {
1196
- question: '?',
1197
- warning: '!',
1198
- info: 'i'
1199
- };
1200
- setInnerHtml(icon, iconContent(defaultIconHtml[params.icon]));
1201
- }
1202
- };
1203
-
1204
- const setColor = (icon, params) => {
1205
- if (!params.iconColor) {
1206
- return;
1207
- }
1208
-
1209
- icon.style.color = params.iconColor;
1210
- icon.style.borderColor = params.iconColor;
1211
-
1212
- for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
1213
- setStyle(icon, sel, 'backgroundColor', params.iconColor);
1214
- }
1215
-
1216
- setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);
1217
- };
1218
-
1219
- const iconContent = content => "<div class=\"".concat(swalClasses['icon-content'], "\">").concat(content, "</div>");
1220
-
1221
- const renderImage = (instance, params) => {
1222
- const image = getImage();
1223
-
1224
- if (!params.imageUrl) {
1225
- return hide(image);
1226
- }
1227
-
1228
- show(image, ''); // Src, alt
1229
-
1230
- image.setAttribute('src', params.imageUrl);
1231
- image.setAttribute('alt', params.imageAlt); // Width, height
1232
-
1233
- applyNumericalStyle(image, 'width', params.imageWidth);
1234
- applyNumericalStyle(image, 'height', params.imageHeight); // Class
1235
-
1236
- image.className = swalClasses.image;
1237
- applyCustomClass(image, params, 'image');
1238
- };
1239
-
1240
- const createStepElement = step => {
1241
- const stepEl = document.createElement('li');
1242
- addClass(stepEl, swalClasses['progress-step']);
1243
- setInnerHtml(stepEl, step);
1244
- return stepEl;
1245
- };
1246
-
1247
- const createLineElement = params => {
1248
- const lineEl = document.createElement('li');
1249
- addClass(lineEl, swalClasses['progress-step-line']);
1250
-
1251
- if (params.progressStepsDistance) {
1252
- lineEl.style.width = params.progressStepsDistance;
1253
- }
1254
-
1255
- return lineEl;
1256
- };
1257
-
1258
- const renderProgressSteps = (instance, params) => {
1259
- const progressStepsContainer = getProgressSteps();
1260
-
1261
- if (!params.progressSteps || params.progressSteps.length === 0) {
1262
- return hide(progressStepsContainer);
1263
- }
1264
-
1265
- show(progressStepsContainer);
1266
- progressStepsContainer.textContent = '';
1267
-
1268
- if (params.currentProgressStep >= params.progressSteps.length) {
1269
- warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
1270
- }
1271
-
1272
- params.progressSteps.forEach((step, index) => {
1273
- const stepEl = createStepElement(step);
1274
- progressStepsContainer.appendChild(stepEl);
1275
-
1276
- if (index === params.currentProgressStep) {
1277
- addClass(stepEl, swalClasses['active-progress-step']);
1278
- }
1279
-
1280
- if (index !== params.progressSteps.length - 1) {
1281
- const lineEl = createLineElement(params);
1282
- progressStepsContainer.appendChild(lineEl);
1283
- }
1284
- });
1285
- };
1286
-
1287
- const renderTitle = (instance, params) => {
1288
- const title = getTitle();
1289
- toggle(title, params.title || params.titleText, 'block');
1290
-
1291
- if (params.title) {
1292
- parseHtmlToContainer(params.title, title);
1293
- }
1294
-
1295
- if (params.titleText) {
1296
- title.innerText = params.titleText;
1297
- } // Custom class
1298
-
1299
-
1300
- applyCustomClass(title, params, 'title');
1301
- };
1302
-
1303
- const renderPopup = (instance, params) => {
1304
- const container = getContainer();
1305
- const popup = getPopup(); // Width
1306
-
1307
- if (params.toast) {
1308
- // #2170
1309
- applyNumericalStyle(container, 'width', params.width);
1310
- popup.style.width = '100%';
1311
- popup.insertBefore(getLoader(), getIcon());
1312
- } else {
1313
- applyNumericalStyle(popup, 'width', params.width);
1314
- } // Padding
1315
-
1316
-
1317
- applyNumericalStyle(popup, 'padding', params.padding); // Color
1318
-
1319
- if (params.color) {
1320
- popup.style.color = params.color;
1321
- } // Background
1322
-
1323
-
1324
- if (params.background) {
1325
- popup.style.background = params.background;
1326
- }
1327
-
1328
- hide(getValidationMessage()); // Classes
1329
-
1330
- addClasses(popup, params);
1331
- };
1332
-
1333
- const addClasses = (popup, params) => {
1334
- // Default Class + showClass when updating Swal.update({})
1335
- popup.className = "".concat(swalClasses.popup, " ").concat(isVisible(popup) ? params.showClass.popup : '');
1336
-
1337
- if (params.toast) {
1338
- addClass([document.documentElement, document.body], swalClasses['toast-shown']);
1339
- addClass(popup, swalClasses.toast);
1340
- } else {
1341
- addClass(popup, swalClasses.modal);
1342
- } // Custom class
1343
-
1344
-
1345
- applyCustomClass(popup, params, 'popup');
1346
-
1347
- if (typeof params.customClass === 'string') {
1348
- addClass(popup, params.customClass);
1349
- } // Icon class (#1842)
1350
-
1351
-
1352
- if (params.icon) {
1353
- addClass(popup, swalClasses["icon-".concat(params.icon)]);
1354
- }
1355
- };
1356
-
1357
- const render = (instance, params) => {
1358
- renderPopup(instance, params);
1359
- renderContainer(instance, params);
1360
- renderProgressSteps(instance, params);
1361
- renderIcon(instance, params);
1362
- renderImage(instance, params);
1363
- renderTitle(instance, params);
1364
- renderCloseButton(instance, params);
1365
- renderContent(instance, params);
1366
- renderActions(instance, params);
1367
- renderFooter(instance, params);
1368
-
1369
- if (typeof params.didRender === 'function') {
1370
- params.didRender(getPopup());
1371
- }
1372
- };
1373
-
1374
- const DismissReason = Object.freeze({
1375
- cancel: 'cancel',
1376
- backdrop: 'backdrop',
1377
- close: 'close',
1378
- esc: 'esc',
1379
- timer: 'timer'
1380
- });
1381
-
1382
- // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
1383
- // elements not within the active modal dialog will not be surfaced if a user opens a screen
1384
- // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
1385
-
1386
- const setAriaHidden = () => {
1387
- const bodyChildren = toArray(document.body.children);
1388
- bodyChildren.forEach(el => {
1389
- if (el === getContainer() || el.contains(getContainer())) {
1390
- return;
1391
- }
1392
-
1393
- if (el.hasAttribute('aria-hidden')) {
1394
- el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
1395
- }
1396
-
1397
- el.setAttribute('aria-hidden', 'true');
1398
- });
1399
- };
1400
- const unsetAriaHidden = () => {
1401
- const bodyChildren = toArray(document.body.children);
1402
- bodyChildren.forEach(el => {
1403
- if (el.hasAttribute('data-previous-aria-hidden')) {
1404
- el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
1405
- el.removeAttribute('data-previous-aria-hidden');
1406
- } else {
1407
- el.removeAttribute('aria-hidden');
1408
- }
1409
- });
1410
- };
1411
-
1412
- const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
1413
- const getTemplateParams = params => {
1414
- const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;
1415
-
1416
- if (!template) {
1417
- return {};
1418
- }
1419
-
1420
- const templateContent = template.content;
1421
- showWarningsForElements(templateContent);
1422
- const result = Object.assign(getSwalParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
1423
- return result;
1424
- };
1425
-
1426
- const getSwalParams = templateContent => {
1427
- const result = {};
1428
- toArray(templateContent.querySelectorAll('swal-param')).forEach(param => {
1429
- showWarningsForAttributes(param, ['name', 'value']);
1430
- const paramName = param.getAttribute('name');
1431
- const value = param.getAttribute('value');
1432
-
1433
- if (typeof defaultParams[paramName] === 'boolean' && value === 'false') {
1434
- result[paramName] = false;
1435
- }
1436
-
1437
- if (typeof defaultParams[paramName] === 'object') {
1438
- result[paramName] = JSON.parse(value);
1439
- }
1440
- });
1441
- return result;
1442
- };
1443
-
1444
- const getSwalButtons = templateContent => {
1445
- const result = {};
1446
- toArray(templateContent.querySelectorAll('swal-button')).forEach(button => {
1447
- showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
1448
- const type = button.getAttribute('type');
1449
- result["".concat(type, "ButtonText")] = button.innerHTML;
1450
- result["show".concat(capitalizeFirstLetter(type), "Button")] = true;
1451
-
1452
- if (button.hasAttribute('color')) {
1453
- result["".concat(type, "ButtonColor")] = button.getAttribute('color');
1454
- }
1455
-
1456
- if (button.hasAttribute('aria-label')) {
1457
- result["".concat(type, "ButtonAriaLabel")] = button.getAttribute('aria-label');
1458
- }
1459
- });
1460
- return result;
1461
- };
1462
-
1463
- const getSwalImage = templateContent => {
1464
- const result = {};
1465
- const image = templateContent.querySelector('swal-image');
1466
-
1467
- if (image) {
1468
- showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
1469
-
1470
- if (image.hasAttribute('src')) {
1471
- result.imageUrl = image.getAttribute('src');
1472
- }
1473
-
1474
- if (image.hasAttribute('width')) {
1475
- result.imageWidth = image.getAttribute('width');
1476
- }
1477
-
1478
- if (image.hasAttribute('height')) {
1479
- result.imageHeight = image.getAttribute('height');
1480
- }
1481
-
1482
- if (image.hasAttribute('alt')) {
1483
- result.imageAlt = image.getAttribute('alt');
1484
- }
1485
- }
1486
-
1487
- return result;
1488
- };
1489
-
1490
- const getSwalIcon = templateContent => {
1491
- const result = {};
1492
- const icon = templateContent.querySelector('swal-icon');
1493
-
1494
- if (icon) {
1495
- showWarningsForAttributes(icon, ['type', 'color']);
1496
-
1497
- if (icon.hasAttribute('type')) {
1498
- result.icon = icon.getAttribute('type');
1499
- }
1500
-
1501
- if (icon.hasAttribute('color')) {
1502
- result.iconColor = icon.getAttribute('color');
1503
- }
1504
-
1505
- result.iconHtml = icon.innerHTML;
1506
- }
1507
-
1508
- return result;
1509
- };
1510
-
1511
- const getSwalInput = templateContent => {
1512
- const result = {};
1513
- const input = templateContent.querySelector('swal-input');
1514
-
1515
- if (input) {
1516
- showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
1517
- result.input = input.getAttribute('type') || 'text';
1518
-
1519
- if (input.hasAttribute('label')) {
1520
- result.inputLabel = input.getAttribute('label');
1521
- }
1522
-
1523
- if (input.hasAttribute('placeholder')) {
1524
- result.inputPlaceholder = input.getAttribute('placeholder');
1525
- }
1526
-
1527
- if (input.hasAttribute('value')) {
1528
- result.inputValue = input.getAttribute('value');
1529
- }
1530
- }
1531
-
1532
- const inputOptions = templateContent.querySelectorAll('swal-input-option');
1533
-
1534
- if (inputOptions.length) {
1535
- result.inputOptions = {};
1536
- toArray(inputOptions).forEach(option => {
1537
- showWarningsForAttributes(option, ['value']);
1538
- const optionValue = option.getAttribute('value');
1539
- const optionName = option.innerHTML;
1540
- result.inputOptions[optionValue] = optionName;
1541
- });
1542
- }
1543
-
1544
- return result;
1545
- };
1546
-
1547
- const getSwalStringParams = (templateContent, paramNames) => {
1548
- const result = {};
1549
-
1550
- for (const i in paramNames) {
1551
- const paramName = paramNames[i];
1552
- const tag = templateContent.querySelector(paramName);
1553
-
1554
- if (tag) {
1555
- showWarningsForAttributes(tag, []);
1556
- result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
1557
- }
1558
- }
1559
-
1560
- return result;
1561
- };
1562
-
1563
- const showWarningsForElements = template => {
1564
- const allowedElements = swalStringParams.concat(['swal-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
1565
- toArray(template.children).forEach(el => {
1566
- const tagName = el.tagName.toLowerCase();
1567
-
1568
- if (allowedElements.indexOf(tagName) === -1) {
1569
- warn("Unrecognized element <".concat(tagName, ">"));
1570
- }
1571
- });
1572
- };
1573
- /**
1574
- * @param {HTMLElement} el
1575
- * @param {string[]} allowedAttributes
1576
- */
1577
-
1578
-
1579
- const showWarningsForAttributes = (el, allowedAttributes) => {
1580
- toArray(el.attributes).forEach(attribute => {
1581
- if (allowedAttributes.indexOf(attribute.name) === -1) {
1582
- warn(["Unrecognized attribute \"".concat(attribute.name, "\" on <").concat(el.tagName.toLowerCase(), ">."), "".concat(allowedAttributes.length ? "Allowed attributes are: ".concat(allowedAttributes.join(', ')) : 'To set the value, use HTML within the element.')]);
1583
- }
1584
- });
1585
- };
1586
-
1587
- var defaultInputValidators = {
1588
- email: (string, validationMessage) => {
1589
- 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');
1590
- },
1591
- url: (string, validationMessage) => {
1592
- // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
1593
- return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
1594
- }
1595
- };
1596
-
1597
- function setDefaultInputValidators(params) {
1598
- // Use default `inputValidator` for supported input types if not provided
1599
- if (!params.inputValidator) {
1600
- Object.keys(defaultInputValidators).forEach(key => {
1601
- if (params.input === key) {
1602
- params.inputValidator = defaultInputValidators[key];
1603
- }
1604
- });
1605
- }
1606
- }
1607
-
1608
- function validateCustomTargetElement(params) {
1609
- // Determine if the custom target element is valid
1610
- if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
1611
- warn('Target parameter is not valid, defaulting to "body"');
1612
- params.target = 'body';
1613
- }
1614
- }
1615
- /**
1616
- * Set type, text and actions on popup
1617
- *
1618
- * @param params
1619
- */
1620
-
1621
-
1622
- function setParameters(params) {
1623
- setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm
1624
-
1625
- if (params.showLoaderOnConfirm && !params.preConfirm) {
1626
- 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');
1627
- }
1628
-
1629
- validateCustomTargetElement(params); // Replace newlines with <br> in title
1630
-
1631
- if (typeof params.title === 'string') {
1632
- params.title = params.title.split('\n').join('<br />');
1633
- }
1634
-
1635
- init(params);
1636
- }
1637
-
1638
- class Timer {
1639
- constructor(callback, delay) {
1640
- this.callback = callback;
1641
- this.remaining = delay;
1642
- this.running = false;
1643
- this.start();
1644
- }
1645
-
1646
- start() {
1647
- if (!this.running) {
1648
- this.running = true;
1649
- this.started = new Date();
1650
- this.id = setTimeout(this.callback, this.remaining);
1651
- }
1652
-
1653
- return this.remaining;
1654
- }
1655
-
1656
- stop() {
1657
- if (this.running) {
1658
- this.running = false;
1659
- clearTimeout(this.id);
1660
- this.remaining -= new Date().getTime() - this.started.getTime();
1661
- }
1662
-
1663
- return this.remaining;
1664
- }
1665
-
1666
- increase(n) {
1667
- const running = this.running;
1668
-
1669
- if (running) {
1670
- this.stop();
1671
- }
1672
-
1673
- this.remaining += n;
1674
-
1675
- if (running) {
1676
- this.start();
1677
- }
1678
-
1679
- return this.remaining;
1680
- }
1681
-
1682
- getTimerLeft() {
1683
- if (this.running) {
1684
- this.stop();
1685
- this.start();
1686
- }
1687
-
1688
- return this.remaining;
1689
- }
1690
-
1691
- isRunning() {
1692
- return this.running;
1693
- }
1694
-
1695
- }
1696
-
1697
- const fixScrollbar = () => {
1698
- // for queues, do not do this more than once
1699
- if (states.previousBodyPadding !== null) {
1700
- return;
1701
- } // if the body has overflow
1702
-
1703
-
1704
- if (document.body.scrollHeight > window.innerHeight) {
1705
- // add padding so the content doesn't shift after removal of scrollbar
1706
- states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
1707
- document.body.style.paddingRight = "".concat(states.previousBodyPadding + measureScrollbar(), "px");
1708
- }
1709
- };
1710
- const undoScrollbar = () => {
1711
- if (states.previousBodyPadding !== null) {
1712
- document.body.style.paddingRight = "".concat(states.previousBodyPadding, "px");
1713
- states.previousBodyPadding = null;
1714
- }
1715
- };
1716
-
1717
- /* istanbul ignore file */
1718
-
1719
- const iOSfix = () => {
1720
- // @ts-ignore
1721
- const iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
1722
-
1723
- if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
1724
- const offset = document.body.scrollTop;
1725
- document.body.style.top = "".concat(offset * -1, "px");
1726
- addClass(document.body, swalClasses.iosfix);
1727
- lockBodyScroll();
1728
- addBottomPaddingForTallPopups();
1729
- }
1730
- };
1731
- /**
1732
- * https://github.com/sweetalert2/sweetalert2/issues/1948
1733
- */
1734
-
1735
- const addBottomPaddingForTallPopups = () => {
1736
- const ua = navigator.userAgent;
1737
- const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
1738
- const webkit = !!ua.match(/WebKit/i);
1739
- const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
1740
-
1741
- if (iOSSafari) {
1742
- const bottomPanelHeight = 44;
1743
-
1744
- if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {
1745
- getContainer().style.paddingBottom = "".concat(bottomPanelHeight, "px");
1746
- }
1747
- }
1748
- };
1749
-
1750
- const lockBodyScroll = () => {
1751
- // #1246
1752
- const container = getContainer();
1753
- let preventTouchMove;
1754
-
1755
- container.ontouchstart = e => {
1756
- preventTouchMove = shouldPreventTouchMove(e);
1757
- };
1758
-
1759
- container.ontouchmove = e => {
1760
- if (preventTouchMove) {
1761
- e.preventDefault();
1762
- e.stopPropagation();
1763
- }
1764
- };
1765
- };
1766
-
1767
- const shouldPreventTouchMove = event => {
1768
- const target = event.target;
1769
- const container = getContainer();
1770
-
1771
- if (isStylus(event) || isZoom(event)) {
1772
- return false;
1773
- }
1774
-
1775
- if (target === container) {
1776
- return true;
1777
- }
1778
-
1779
- if (!isScrollable(container) && target.tagName !== 'INPUT' && // #1603
1780
- target.tagName !== 'TEXTAREA' && // #2266
1781
- !(isScrollable(getHtmlContainer()) && // #1944
1782
- getHtmlContainer().contains(target))) {
1783
- return true;
1784
- }
1785
-
1786
- return false;
1787
- };
1788
- /**
1789
- * https://github.com/sweetalert2/sweetalert2/issues/1786
1790
- *
1791
- * @param {*} event
1792
- * @returns {boolean}
1793
- */
1794
-
1795
-
1796
- const isStylus = event => {
1797
- return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
1798
- };
1799
-
1800
- const isZoom = event => {
1801
- // #1891
1802
- return event.touches && event.touches.length > 1;
1803
- };
1804
-
1805
- const undoIOSfix = () => {
1806
- if (hasClass(document.body, swalClasses.iosfix)) {
1807
- const offset = parseInt(document.body.style.top, 10);
1808
- removeClass(document.body, swalClasses.iosfix);
1809
- document.body.style.top = '';
1810
- document.body.scrollTop = offset * -1;
1811
- }
1812
- };
1813
-
1814
- const SHOW_CLASS_TIMEOUT = 10;
1815
- /**
1816
- * Open popup, add necessary classes and styles, fix scrollbar
1817
- *
1818
- * @param params
1819
- */
1820
-
1821
- const openPopup = params => {
1822
- const container = getContainer();
1823
- const popup = getPopup();
1824
-
1825
- if (typeof params.willOpen === 'function') {
1826
- params.willOpen(popup);
1827
- }
1828
-
1829
- const bodyStyles = window.getComputedStyle(document.body);
1830
- const initialBodyOverflow = bodyStyles.overflowY;
1831
- addClasses$1(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'
1832
-
1833
- setTimeout(() => {
1834
- setScrollingVisibility(container, popup);
1835
- }, SHOW_CLASS_TIMEOUT);
1836
-
1837
- if (isModal()) {
1838
- fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
1839
- setAriaHidden();
1840
- }
1841
-
1842
- if (!isToast() && !globalState.previousActiveElement) {
1843
- globalState.previousActiveElement = document.activeElement;
1844
- }
1845
-
1846
- if (typeof params.didOpen === 'function') {
1847
- setTimeout(() => params.didOpen(popup));
1848
- }
1849
-
1850
- removeClass(container, swalClasses['no-transition']);
1851
- };
1852
-
1853
- const swalOpenAnimationFinished = event => {
1854
- const popup = getPopup();
1855
-
1856
- if (event.target !== popup) {
1857
- return;
1858
- }
1859
-
1860
- const container = getContainer();
1861
- popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
1862
- container.style.overflowY = 'auto';
1863
- };
1864
-
1865
- const setScrollingVisibility = (container, popup) => {
1866
- if (animationEndEvent && hasCssAnimation(popup)) {
1867
- container.style.overflowY = 'hidden';
1868
- popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
1869
- } else {
1870
- container.style.overflowY = 'auto';
1871
- }
1872
- };
1873
-
1874
- const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
1875
- iOSfix();
1876
-
1877
- if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
1878
- fixScrollbar();
1879
- } // sweetalert2/issues/1247
1880
-
1881
-
1882
- setTimeout(() => {
1883
- container.scrollTop = 0;
1884
- });
1885
- };
1886
-
1887
- const addClasses$1 = (container, popup, params) => {
1888
- addClass(container, params.showClass.backdrop); // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
1889
-
1890
- popup.style.setProperty('opacity', '0', 'important');
1891
- show(popup, 'grid');
1892
- setTimeout(() => {
1893
- // Animate popup right after showing it
1894
- addClass(popup, params.showClass.popup); // and remove the opacity workaround
1895
-
1896
- popup.style.removeProperty('opacity');
1897
- }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
1898
-
1899
- addClass([document.documentElement, document.body], swalClasses.shown);
1900
-
1901
- if (params.heightAuto && params.backdrop && !params.toast) {
1902
- addClass([document.documentElement, document.body], swalClasses['height-auto']);
1903
- }
1904
- };
1905
-
1906
- /**
1907
- * Shows loader (spinner), this is useful with AJAX requests.
1908
- * By default the loader be shown instead of the "Confirm" button.
1909
- */
1910
-
1911
- const showLoading = buttonToReplace => {
1912
- let popup = getPopup();
1913
-
1914
- if (!popup) {
1915
- new Swal(); // eslint-disable-line no-new
1916
- }
1917
-
1918
- popup = getPopup();
1919
- const loader = getLoader();
1920
-
1921
- if (isToast()) {
1922
- hide(getIcon());
1923
- } else {
1924
- replaceButton(popup, buttonToReplace);
1925
- }
1926
-
1927
- show(loader);
1928
- popup.setAttribute('data-loading', true);
1929
- popup.setAttribute('aria-busy', true);
1930
- popup.focus();
1931
- };
1932
-
1933
- const replaceButton = (popup, buttonToReplace) => {
1934
- const actions = getActions();
1935
- const loader = getLoader();
1936
-
1937
- if (!buttonToReplace && isVisible(getConfirmButton())) {
1938
- buttonToReplace = getConfirmButton();
1939
- }
1940
-
1941
- show(actions);
1942
-
1943
- if (buttonToReplace) {
1944
- hide(buttonToReplace);
1945
- loader.setAttribute('data-button-to-replace', buttonToReplace.className);
1946
- }
1947
-
1948
- loader.parentNode.insertBefore(loader, buttonToReplace);
1949
- addClass([popup, actions], swalClasses.loading);
1950
- };
1951
-
1952
- const handleInputOptionsAndValue = (instance, params) => {
1953
- if (params.input === 'select' || params.input === 'radio') {
1954
- handleInputOptions(instance, params);
1955
- } else if (['text', 'email', 'number', 'tel', 'textarea'].includes(params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
1956
- showLoading(getConfirmButton());
1957
- handleInputValue(instance, params);
1958
- }
1959
- };
1960
- const getInputValue = (instance, innerParams) => {
1961
- const input = instance.getInput();
1962
-
1963
- if (!input) {
1964
- return null;
1965
- }
1966
-
1967
- switch (innerParams.input) {
1968
- case 'checkbox':
1969
- return getCheckboxValue(input);
1970
-
1971
- case 'radio':
1972
- return getRadioValue(input);
1973
-
1974
- case 'file':
1975
- return getFileValue(input);
1976
-
1977
- default:
1978
- return innerParams.inputAutoTrim ? input.value.trim() : input.value;
1979
- }
1980
- };
1981
-
1982
- const getCheckboxValue = input => input.checked ? 1 : 0;
1983
-
1984
- const getRadioValue = input => input.checked ? input.value : null;
1985
-
1986
- const getFileValue = input => input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
1987
-
1988
- const handleInputOptions = (instance, params) => {
1989
- const popup = getPopup();
1990
-
1991
- const processInputOptions = inputOptions => populateInputOptions[params.input](popup, formatInputOptions(inputOptions), params);
1992
-
1993
- if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
1994
- showLoading(getConfirmButton());
1995
- asPromise(params.inputOptions).then(inputOptions => {
1996
- instance.hideLoading();
1997
- processInputOptions(inputOptions);
1998
- });
1999
- } else if (typeof params.inputOptions === 'object') {
2000
- processInputOptions(params.inputOptions);
2001
- } else {
2002
- error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(typeof params.inputOptions));
2003
- }
2004
- };
2005
-
2006
- const handleInputValue = (instance, params) => {
2007
- const input = instance.getInput();
2008
- hide(input);
2009
- asPromise(params.inputValue).then(inputValue => {
2010
- input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : "".concat(inputValue);
2011
- show(input);
2012
- input.focus();
2013
- instance.hideLoading();
2014
- }).catch(err => {
2015
- error("Error in inputValue promise: ".concat(err));
2016
- input.value = '';
2017
- show(input);
2018
- input.focus();
2019
- instance.hideLoading();
2020
- });
2021
- };
2022
-
2023
- const populateInputOptions = {
2024
- select: (popup, inputOptions, params) => {
2025
- const select = getDirectChildByClass(popup, swalClasses.select);
2026
-
2027
- const renderOption = (parent, optionLabel, optionValue) => {
2028
- const option = document.createElement('option');
2029
- option.value = optionValue;
2030
- setInnerHtml(option, optionLabel);
2031
- option.selected = isSelected(optionValue, params.inputValue);
2032
- parent.appendChild(option);
2033
- };
2034
-
2035
- inputOptions.forEach(inputOption => {
2036
- const optionValue = inputOption[0];
2037
- const optionLabel = inputOption[1]; // <optgroup> spec:
2038
- // https://www.w3.org/TR/html401/interact/forms.html#h-17.6
2039
- // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
2040
- // check whether this is a <optgroup>
2041
-
2042
- if (Array.isArray(optionLabel)) {
2043
- // if it is an array, then it is an <optgroup>
2044
- const optgroup = document.createElement('optgroup');
2045
- optgroup.label = optionValue;
2046
- optgroup.disabled = false; // not configurable for now
2047
-
2048
- select.appendChild(optgroup);
2049
- optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
2050
- } else {
2051
- // case of <option>
2052
- renderOption(select, optionLabel, optionValue);
2053
- }
2054
- });
2055
- select.focus();
2056
- },
2057
- radio: (popup, inputOptions, params) => {
2058
- const radio = getDirectChildByClass(popup, swalClasses.radio);
2059
- inputOptions.forEach(inputOption => {
2060
- const radioValue = inputOption[0];
2061
- const radioLabel = inputOption[1];
2062
- const radioInput = document.createElement('input');
2063
- const radioLabelElement = document.createElement('label');
2064
- radioInput.type = 'radio';
2065
- radioInput.name = swalClasses.radio;
2066
- radioInput.value = radioValue;
2067
-
2068
- if (isSelected(radioValue, params.inputValue)) {
2069
- radioInput.checked = true;
2070
- }
2071
-
2072
- const label = document.createElement('span');
2073
- setInnerHtml(label, radioLabel);
2074
- label.className = swalClasses.label;
2075
- radioLabelElement.appendChild(radioInput);
2076
- radioLabelElement.appendChild(label);
2077
- radio.appendChild(radioLabelElement);
2078
- });
2079
- const radios = radio.querySelectorAll('input');
2080
-
2081
- if (radios.length) {
2082
- radios[0].focus();
2083
- }
2084
- }
2085
- };
2086
- /**
2087
- * Converts `inputOptions` into an array of `[value, label]`s
2088
- * @param inputOptions
2089
- */
2090
-
2091
- const formatInputOptions = inputOptions => {
2092
- const result = [];
2093
-
2094
- if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
2095
- inputOptions.forEach((value, key) => {
2096
- let valueFormatted = value;
2097
-
2098
- if (typeof valueFormatted === 'object') {
2099
- // case of <optgroup>
2100
- valueFormatted = formatInputOptions(valueFormatted);
2101
- }
2102
-
2103
- result.push([key, valueFormatted]);
2104
- });
2105
- } else {
2106
- Object.keys(inputOptions).forEach(key => {
2107
- let valueFormatted = inputOptions[key];
2108
-
2109
- if (typeof valueFormatted === 'object') {
2110
- // case of <optgroup>
2111
- valueFormatted = formatInputOptions(valueFormatted);
2112
- }
2113
-
2114
- result.push([key, valueFormatted]);
2115
- });
2116
- }
2117
-
2118
- return result;
2119
- };
2120
-
2121
- const isSelected = (optionValue, inputValue) => {
2122
- return inputValue && inputValue.toString() === optionValue.toString();
2123
- };
2124
-
2125
- const handleConfirmButtonClick = instance => {
2126
- const innerParams = privateProps.innerParams.get(instance);
2127
- instance.disableButtons();
2128
-
2129
- if (innerParams.input) {
2130
- handleConfirmOrDenyWithInput(instance, 'confirm');
2131
- } else {
2132
- confirm(instance, true);
2133
- }
2134
- };
2135
- const handleDenyButtonClick = instance => {
2136
- const innerParams = privateProps.innerParams.get(instance);
2137
- instance.disableButtons();
2138
-
2139
- if (innerParams.returnInputValueOnDeny) {
2140
- handleConfirmOrDenyWithInput(instance, 'deny');
2141
- } else {
2142
- deny(instance, false);
2143
- }
2144
- };
2145
- const handleCancelButtonClick = (instance, dismissWith) => {
2146
- instance.disableButtons();
2147
- dismissWith(DismissReason.cancel);
2148
- };
2149
-
2150
- const handleConfirmOrDenyWithInput = (instance, type
2151
- /* 'confirm' | 'deny' */
2152
- ) => {
2153
- const innerParams = privateProps.innerParams.get(instance);
2154
-
2155
- if (!innerParams.input) {
2156
- return error("The \"input\" parameter is needed to be set when using returnInputValueOn".concat(capitalizeFirstLetter(type)));
2157
- }
2158
-
2159
- const inputValue = getInputValue(instance, innerParams);
2160
-
2161
- if (innerParams.inputValidator) {
2162
- handleInputValidator(instance, inputValue, type);
2163
- } else if (!instance.getInput().checkValidity()) {
2164
- instance.enableButtons();
2165
- instance.showValidationMessage(innerParams.validationMessage);
2166
- } else if (type === 'deny') {
2167
- deny(instance, inputValue);
2168
- } else {
2169
- confirm(instance, inputValue);
2170
- }
2171
- };
2172
-
2173
- const handleInputValidator = (instance, inputValue, type
2174
- /* 'confirm' | 'deny' */
2175
- ) => {
2176
- const innerParams = privateProps.innerParams.get(instance);
2177
- instance.disableInput();
2178
- const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
2179
- validationPromise.then(validationMessage => {
2180
- instance.enableButtons();
2181
- instance.enableInput();
2182
-
2183
- if (validationMessage) {
2184
- instance.showValidationMessage(validationMessage);
2185
- } else if (type === 'deny') {
2186
- deny(instance, inputValue);
2187
- } else {
2188
- confirm(instance, inputValue);
2189
- }
2190
- });
2191
- };
2192
-
2193
- const deny = (instance, value) => {
2194
- const innerParams = privateProps.innerParams.get(instance || undefined);
2195
-
2196
- if (innerParams.showLoaderOnDeny) {
2197
- showLoading(getDenyButton());
2198
- }
2199
-
2200
- if (innerParams.preDeny) {
2201
- privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received
2202
-
2203
- const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
2204
- preDenyPromise.then(preDenyValue => {
2205
- if (preDenyValue === false) {
2206
- instance.hideLoading();
2207
- } else {
2208
- instance.closePopup({
2209
- isDenied: true,
2210
- value: typeof preDenyValue === 'undefined' ? value : preDenyValue
2211
- });
2212
- }
2213
- }).catch(error$$1 => rejectWith(instance || undefined, error$$1));
2214
- } else {
2215
- instance.closePopup({
2216
- isDenied: true,
2217
- value
2218
- });
2219
- }
2220
- };
2221
-
2222
- const succeedWith = (instance, value) => {
2223
- instance.closePopup({
2224
- isConfirmed: true,
2225
- value
2226
- });
2227
- };
2228
-
2229
- const rejectWith = (instance, error$$1) => {
2230
- instance.rejectPromise(error$$1);
2231
- };
2232
-
2233
- const confirm = (instance, value) => {
2234
- const innerParams = privateProps.innerParams.get(instance || undefined);
2235
-
2236
- if (innerParams.showLoaderOnConfirm) {
2237
- showLoading();
2238
- }
2239
-
2240
- if (innerParams.preConfirm) {
2241
- instance.resetValidationMessage();
2242
- privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received
2243
-
2244
- const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
2245
- preConfirmPromise.then(preConfirmValue => {
2246
- if (isVisible(getValidationMessage()) || preConfirmValue === false) {
2247
- instance.hideLoading();
2248
- } else {
2249
- succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
2250
- }
2251
- }).catch(error$$1 => rejectWith(instance || undefined, error$$1));
2252
- } else {
2253
- succeedWith(instance, value);
2254
- }
2255
- };
2256
-
2257
- const handlePopupClick = (instance, domCache, dismissWith) => {
2258
- const innerParams = privateProps.innerParams.get(instance);
2259
-
2260
- if (innerParams.toast) {
2261
- handleToastClick(instance, domCache, dismissWith);
2262
- } else {
2263
- // Ignore click events that had mousedown on the popup but mouseup on the container
2264
- // This can happen when the user drags a slider
2265
- handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup
2266
-
2267
- handleContainerMousedown(domCache);
2268
- handleModalClick(instance, domCache, dismissWith);
2269
- }
2270
- };
2271
-
2272
- const handleToastClick = (instance, domCache, dismissWith) => {
2273
- // Closing toast by internal click
2274
- domCache.popup.onclick = () => {
2275
- const innerParams = privateProps.innerParams.get(instance);
2276
-
2277
- if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
2278
- return;
2279
- }
2280
-
2281
- dismissWith(DismissReason.close);
2282
- };
2283
- };
2284
- /**
2285
- * @param {*} innerParams
2286
- * @returns {boolean}
2287
- */
2288
-
2289
-
2290
- const isAnyButtonShown = innerParams => {
2291
- return innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton;
2292
- };
2293
-
2294
- let ignoreOutsideClick = false;
2295
-
2296
- const handleModalMousedown = domCache => {
2297
- domCache.popup.onmousedown = () => {
2298
- domCache.container.onmouseup = function (e) {
2299
- domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't
2300
- // have any other direct children aside of the popup
2301
-
2302
- if (e.target === domCache.container) {
2303
- ignoreOutsideClick = true;
2304
- }
2305
- };
2306
- };
2307
- };
2308
-
2309
- const handleContainerMousedown = domCache => {
2310
- domCache.container.onmousedown = () => {
2311
- domCache.popup.onmouseup = function (e) {
2312
- domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup
2313
-
2314
- if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
2315
- ignoreOutsideClick = true;
2316
- }
2317
- };
2318
- };
2319
- };
2320
-
2321
- const handleModalClick = (instance, domCache, dismissWith) => {
2322
- domCache.container.onclick = e => {
2323
- const innerParams = privateProps.innerParams.get(instance);
2324
-
2325
- if (ignoreOutsideClick) {
2326
- ignoreOutsideClick = false;
2327
- return;
2328
- }
2329
-
2330
- if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
2331
- dismissWith(DismissReason.backdrop);
2332
- }
2333
- };
2334
- };
2335
-
2336
- /*
2337
- * Global function to determine if SweetAlert2 popup is shown
2338
- */
2339
-
2340
- const isVisible$1 = () => {
2341
- return isVisible(getPopup());
2342
- };
2343
- /*
2344
- * Global function to click 'Confirm' button
2345
- */
2346
-
2347
- const clickConfirm = () => getConfirmButton() && getConfirmButton().click();
2348
- /*
2349
- * Global function to click 'Deny' button
2350
- */
2351
-
2352
- const clickDeny = () => getDenyButton() && getDenyButton().click();
2353
- /*
2354
- * Global function to click 'Cancel' button
2355
- */
2356
-
2357
- const clickCancel = () => getCancelButton() && getCancelButton().click();
2358
-
2359
- const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => {
2360
- if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
2361
- globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
2362
- capture: globalState.keydownListenerCapture
2363
- });
2364
- globalState.keydownHandlerAdded = false;
2365
- }
2366
-
2367
- if (!innerParams.toast) {
2368
- globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith);
2369
-
2370
- globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
2371
- globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
2372
- globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
2373
- capture: globalState.keydownListenerCapture
2374
- });
2375
- globalState.keydownHandlerAdded = true;
2376
- }
2377
- }; // Focus handling
2378
-
2379
- const setFocus = (innerParams, index, increment) => {
2380
- const focusableElements = getFocusableElements(); // search for visible elements and select the next possible match
2381
-
2382
- if (focusableElements.length) {
2383
- index = index + increment; // rollover to first item
2384
-
2385
- if (index === focusableElements.length) {
2386
- index = 0; // go to last item
2387
- } else if (index === -1) {
2388
- index = focusableElements.length - 1;
2389
- }
2390
-
2391
- return focusableElements[index].focus();
2392
- } // no visible focusable elements, focus the popup
2393
-
2394
-
2395
- getPopup().focus();
2396
- };
2397
- const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
2398
- const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
2399
-
2400
- const keydownHandler = (instance, e, dismissWith) => {
2401
- const innerParams = privateProps.innerParams.get(instance);
2402
-
2403
- if (!innerParams) {
2404
- return; // This instance has already been destroyed
2405
- }
2406
-
2407
- if (innerParams.stopKeydownPropagation) {
2408
- e.stopPropagation();
2409
- } // ENTER
2410
-
2411
-
2412
- if (e.key === 'Enter') {
2413
- handleEnter(instance, e, innerParams); // TAB
2414
- } else if (e.key === 'Tab') {
2415
- handleTab(e, innerParams); // ARROWS - switch focus between buttons
2416
- } else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(e.key)) {
2417
- handleArrows(e.key); // ESC
2418
- } else if (e.key === 'Escape') {
2419
- handleEsc(e, innerParams, dismissWith);
2420
- }
2421
- };
2422
-
2423
- const handleEnter = (instance, e, innerParams) => {
2424
- // #720 #721
2425
- if (e.isComposing) {
2426
- return;
2427
- }
2428
-
2429
- if (e.target && instance.getInput() && e.target.outerHTML === instance.getInput().outerHTML) {
2430
- if (['textarea', 'file'].includes(innerParams.input)) {
2431
- return; // do not submit
2432
- }
2433
-
2434
- clickConfirm();
2435
- e.preventDefault();
2436
- }
2437
- };
2438
-
2439
- const handleTab = (e, innerParams) => {
2440
- const targetElement = e.target;
2441
- const focusableElements = getFocusableElements();
2442
- let btnIndex = -1;
2443
-
2444
- for (let i = 0; i < focusableElements.length; i++) {
2445
- if (targetElement === focusableElements[i]) {
2446
- btnIndex = i;
2447
- break;
2448
- }
2449
- }
2450
-
2451
- if (!e.shiftKey) {
2452
- // Cycle to the next button
2453
- setFocus(innerParams, btnIndex, 1);
2454
- } else {
2455
- // Cycle to the prev button
2456
- setFocus(innerParams, btnIndex, -1);
2457
- }
2458
-
2459
- e.stopPropagation();
2460
- e.preventDefault();
2461
- };
2462
-
2463
- const handleArrows = key => {
2464
- const confirmButton = getConfirmButton();
2465
- const denyButton = getDenyButton();
2466
- const cancelButton = getCancelButton();
2467
-
2468
- if (![confirmButton, denyButton, cancelButton].includes(document.activeElement)) {
2469
- return;
2470
- }
2471
-
2472
- const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
2473
- const buttonToFocus = document.activeElement[sibling];
2474
-
2475
- if (buttonToFocus instanceof HTMLElement) {
2476
- buttonToFocus.focus();
2477
- }
2478
- };
2479
-
2480
- const handleEsc = (e, innerParams, dismissWith) => {
2481
- if (callIfFunction(innerParams.allowEscapeKey)) {
2482
- e.preventDefault();
2483
- dismissWith(DismissReason.esc);
2484
- }
2485
- };
2486
-
2487
- const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
2488
-
2489
- const isElement = elem => elem instanceof Element || isJqueryElement(elem);
2490
-
2491
- const argsToParams = args => {
2492
- const params = {};
2493
-
2494
- if (typeof args[0] === 'object' && !isElement(args[0])) {
2495
- Object.assign(params, args[0]);
2496
- } else {
2497
- ['title', 'html', 'icon'].forEach((name, index) => {
2498
- const arg = args[index];
2499
-
2500
- if (typeof arg === 'string' || isElement(arg)) {
2501
- params[name] = arg;
2502
- } else if (arg !== undefined) {
2503
- error("Unexpected type of ".concat(name, "! Expected \"string\" or \"Element\", got ").concat(typeof arg));
2504
- }
2505
- });
2506
- }
2507
-
2508
- return params;
2509
- };
2510
-
2511
- function fire() {
2512
- const Swal = this;
2513
-
2514
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2515
- args[_key] = arguments[_key];
2516
- }
2517
-
2518
- return new Swal(...args);
2519
- }
2520
-
2521
- /**
2522
- * Returns an extended version of `Swal` containing `params` as defaults.
2523
- * Useful for reusing Swal configuration.
2524
- *
2525
- * For example:
2526
- *
2527
- * Before:
2528
- * const textPromptOptions = { input: 'text', showCancelButton: true }
2529
- * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
2530
- * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
2531
- *
2532
- * After:
2533
- * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
2534
- * const {value: firstName} = await TextPrompt('What is your first name?')
2535
- * const {value: lastName} = await TextPrompt('What is your last name?')
2536
- *
2537
- * @param mixinParams
2538
- */
2539
- function mixin(mixinParams) {
2540
- class MixinSwal extends this {
2541
- _main(params, priorityMixinParams) {
2542
- return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
2543
- }
2544
-
2545
- }
2546
-
2547
- return MixinSwal;
2548
- }
2549
-
2550
- /**
2551
- * If `timer` parameter is set, returns number of milliseconds of timer remained.
2552
- * Otherwise, returns undefined.
2553
- */
2554
-
2555
- const getTimerLeft = () => {
2556
- return globalState.timeout && globalState.timeout.getTimerLeft();
2557
- };
2558
- /**
2559
- * Stop timer. Returns number of milliseconds of timer remained.
2560
- * If `timer` parameter isn't set, returns undefined.
2561
- */
2562
-
2563
- const stopTimer = () => {
2564
- if (globalState.timeout) {
2565
- stopTimerProgressBar();
2566
- return globalState.timeout.stop();
2567
- }
2568
- };
2569
- /**
2570
- * Resume timer. Returns number of milliseconds of timer remained.
2571
- * If `timer` parameter isn't set, returns undefined.
2572
- */
2573
-
2574
- const resumeTimer = () => {
2575
- if (globalState.timeout) {
2576
- const remaining = globalState.timeout.start();
2577
- animateTimerProgressBar(remaining);
2578
- return remaining;
2579
- }
2580
- };
2581
- /**
2582
- * Resume timer. Returns number of milliseconds of timer remained.
2583
- * If `timer` parameter isn't set, returns undefined.
2584
- */
2585
-
2586
- const toggleTimer = () => {
2587
- const timer = globalState.timeout;
2588
- return timer && (timer.running ? stopTimer() : resumeTimer());
2589
- };
2590
- /**
2591
- * Increase timer. Returns number of milliseconds of an updated timer.
2592
- * If `timer` parameter isn't set, returns undefined.
2593
- */
2594
-
2595
- const increaseTimer = n => {
2596
- if (globalState.timeout) {
2597
- const remaining = globalState.timeout.increase(n);
2598
- animateTimerProgressBar(remaining, true);
2599
- return remaining;
2600
- }
2601
- };
2602
- /**
2603
- * Check if timer is running. Returns true if timer is running
2604
- * or false if timer is paused or stopped.
2605
- * If `timer` parameter isn't set, returns undefined
2606
- */
2607
-
2608
- const isTimerRunning = () => {
2609
- return globalState.timeout && globalState.timeout.isRunning();
2610
- };
2611
-
2612
- let bodyClickListenerAdded = false;
2613
- const clickHandlers = {};
2614
- function bindClickHandler() {
2615
- let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
2616
- clickHandlers[attr] = this;
2617
-
2618
- if (!bodyClickListenerAdded) {
2619
- document.body.addEventListener('click', bodyClickListener);
2620
- bodyClickListenerAdded = true;
2621
- }
2622
- }
2623
-
2624
- const bodyClickListener = event => {
2625
- for (let el = event.target; el && el !== document; el = el.parentNode) {
2626
- for (const attr in clickHandlers) {
2627
- const template = el.getAttribute(attr);
2628
-
2629
- if (template) {
2630
- clickHandlers[attr].fire({
2631
- template
2632
- });
2633
- return;
2634
- }
2635
- }
2636
- }
2637
- };
2638
-
2639
-
2640
-
2641
- var staticMethods = /*#__PURE__*/Object.freeze({
2642
- isValidParameter: isValidParameter,
2643
- isUpdatableParameter: isUpdatableParameter,
2644
- isDeprecatedParameter: isDeprecatedParameter,
2645
- argsToParams: argsToParams,
2646
- isVisible: isVisible$1,
2647
- clickConfirm: clickConfirm,
2648
- clickDeny: clickDeny,
2649
- clickCancel: clickCancel,
2650
- getContainer: getContainer,
2651
- getPopup: getPopup,
2652
- getTitle: getTitle,
2653
- getHtmlContainer: getHtmlContainer,
2654
- getImage: getImage,
2655
- getIcon: getIcon,
2656
- getInputLabel: getInputLabel,
2657
- getCloseButton: getCloseButton,
2658
- getActions: getActions,
2659
- getConfirmButton: getConfirmButton,
2660
- getDenyButton: getDenyButton,
2661
- getCancelButton: getCancelButton,
2662
- getLoader: getLoader,
2663
- getFooter: getFooter,
2664
- getTimerProgressBar: getTimerProgressBar,
2665
- getFocusableElements: getFocusableElements,
2666
- getValidationMessage: getValidationMessage,
2667
- isLoading: isLoading,
2668
- fire: fire,
2669
- mixin: mixin,
2670
- showLoading: showLoading,
2671
- enableLoading: showLoading,
2672
- getTimerLeft: getTimerLeft,
2673
- stopTimer: stopTimer,
2674
- resumeTimer: resumeTimer,
2675
- toggleTimer: toggleTimer,
2676
- increaseTimer: increaseTimer,
2677
- isTimerRunning: isTimerRunning,
2678
- bindClickHandler: bindClickHandler
2679
- });
2680
-
2681
- /**
2682
- * Hides loader and shows back the button which was hidden by .showLoading()
2683
- */
2684
-
2685
- function hideLoading() {
2686
- // do nothing if popup is closed
2687
- const innerParams = privateProps.innerParams.get(this);
2688
-
2689
- if (!innerParams) {
2690
- return;
2691
- }
2692
-
2693
- const domCache = privateProps.domCache.get(this);
2694
- hide(domCache.loader);
2695
-
2696
- if (isToast()) {
2697
- if (innerParams.icon) {
2698
- show(getIcon());
2699
- }
2700
- } else {
2701
- showRelatedButton(domCache);
2702
- }
2703
-
2704
- removeClass([domCache.popup, domCache.actions], swalClasses.loading);
2705
- domCache.popup.removeAttribute('aria-busy');
2706
- domCache.popup.removeAttribute('data-loading');
2707
- domCache.confirmButton.disabled = false;
2708
- domCache.denyButton.disabled = false;
2709
- domCache.cancelButton.disabled = false;
2710
- }
2711
-
2712
- const showRelatedButton = domCache => {
2713
- const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
2714
-
2715
- if (buttonToReplace.length) {
2716
- show(buttonToReplace[0], 'inline-block');
2717
- } else if (allButtonsAreHidden()) {
2718
- hide(domCache.actions);
2719
- }
2720
- };
2721
-
2722
- /**
2723
- * Gets the input DOM node, this method works with input parameter.
2724
- * @returns {HTMLElement | null}
2725
- */
2726
-
2727
- function getInput$1(instance) {
2728
- const innerParams = privateProps.innerParams.get(instance || this);
2729
- const domCache = privateProps.domCache.get(instance || this);
2730
-
2731
- if (!domCache) {
2732
- return null;
2733
- }
2734
-
2735
- return getInput(domCache.popup, innerParams.input);
2736
- }
2737
-
2738
- /**
2739
- * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
2740
- * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
2741
- * This is the approach that Babel will probably take to implement private methods/fields
2742
- * https://github.com/tc39/proposal-private-methods
2743
- * https://github.com/babel/babel/pull/7555
2744
- * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
2745
- * then we can use that language feature.
2746
- */
2747
- var privateMethods = {
2748
- swalPromiseResolve: new WeakMap(),
2749
- swalPromiseReject: new WeakMap()
2750
- };
2751
-
2752
- /*
2753
- * Instance method to close sweetAlert
2754
- */
2755
-
2756
- function removePopupAndResetState(instance, container, returnFocus, didClose) {
2757
- if (isToast()) {
2758
- triggerDidCloseAndDispose(instance, didClose);
2759
- } else {
2760
- restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
2761
- globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
2762
- capture: globalState.keydownListenerCapture
2763
- });
2764
- globalState.keydownHandlerAdded = false;
2765
- }
2766
-
2767
- const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); // workaround for #2088
2768
- // for some reason removing the container in Safari will scroll the document to bottom
2769
-
2770
- if (isSafari) {
2771
- container.setAttribute('style', 'display:none !important');
2772
- container.removeAttribute('class');
2773
- container.innerHTML = '';
2774
- } else {
2775
- container.remove();
2776
- }
2777
-
2778
- if (isModal()) {
2779
- undoScrollbar();
2780
- undoIOSfix();
2781
- unsetAriaHidden();
2782
- }
2783
-
2784
- removeBodyClasses();
2785
- }
2786
-
2787
- function removeBodyClasses() {
2788
- removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
2789
- }
2790
-
2791
- function close(resolveValue) {
2792
- resolveValue = prepareResolveValue(resolveValue);
2793
- const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
2794
- const didClose = triggerClosePopup(this);
2795
-
2796
- if (this.isAwaitingPromise()) {
2797
- // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
2798
- if (!resolveValue.isDismissed) {
2799
- handleAwaitingPromise(this);
2800
- swalPromiseResolve(resolveValue);
2801
- }
2802
- } else if (didClose) {
2803
- // Resolve Swal promise
2804
- swalPromiseResolve(resolveValue);
2805
- }
2806
- }
2807
- function isAwaitingPromise() {
2808
- return !!privateProps.awaitingPromise.get(this);
2809
- }
2810
-
2811
- const triggerClosePopup = instance => {
2812
- const popup = getPopup();
2813
-
2814
- if (!popup) {
2815
- return false;
2816
- }
2817
-
2818
- const innerParams = privateProps.innerParams.get(instance);
2819
-
2820
- if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
2821
- return false;
2822
- }
2823
-
2824
- removeClass(popup, innerParams.showClass.popup);
2825
- addClass(popup, innerParams.hideClass.popup);
2826
- const backdrop = getContainer();
2827
- removeClass(backdrop, innerParams.showClass.backdrop);
2828
- addClass(backdrop, innerParams.hideClass.backdrop);
2829
- handlePopupAnimation(instance, popup, innerParams);
2830
- return true;
2831
- };
2832
-
2833
- function rejectPromise(error) {
2834
- const rejectPromise = privateMethods.swalPromiseReject.get(this);
2835
- handleAwaitingPromise(this);
2836
-
2837
- if (rejectPromise) {
2838
- // Reject Swal promise
2839
- rejectPromise(error);
2840
- }
2841
- }
2842
-
2843
- const handleAwaitingPromise = instance => {
2844
- if (instance.isAwaitingPromise()) {
2845
- privateProps.awaitingPromise.delete(instance); // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
2846
-
2847
- if (!privateProps.innerParams.get(instance)) {
2848
- instance._destroy();
2849
- }
2850
- }
2851
- };
2852
-
2853
- const prepareResolveValue = resolveValue => {
2854
- // When user calls Swal.close()
2855
- if (typeof resolveValue === 'undefined') {
2856
- return {
2857
- isConfirmed: false,
2858
- isDenied: false,
2859
- isDismissed: true
2860
- };
2861
- }
2862
-
2863
- return Object.assign({
2864
- isConfirmed: false,
2865
- isDenied: false,
2866
- isDismissed: false
2867
- }, resolveValue);
2868
- };
2869
-
2870
- const handlePopupAnimation = (instance, popup, innerParams) => {
2871
- const container = getContainer(); // If animation is supported, animate
2872
-
2873
- const animationIsSupported = animationEndEvent && hasCssAnimation(popup);
2874
-
2875
- if (typeof innerParams.willClose === 'function') {
2876
- innerParams.willClose(popup);
2877
- }
2878
-
2879
- if (animationIsSupported) {
2880
- animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
2881
- } else {
2882
- // Otherwise, remove immediately
2883
- removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
2884
- }
2885
- };
2886
-
2887
- const animatePopup = (instance, popup, container, returnFocus, didClose) => {
2888
- globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
2889
- popup.addEventListener(animationEndEvent, function (e) {
2890
- if (e.target === popup) {
2891
- globalState.swalCloseEventFinishedCallback();
2892
- delete globalState.swalCloseEventFinishedCallback;
2893
- }
2894
- });
2895
- };
2896
-
2897
- const triggerDidCloseAndDispose = (instance, didClose) => {
2898
- setTimeout(() => {
2899
- if (typeof didClose === 'function') {
2900
- didClose.bind(instance.params)();
2901
- }
2902
-
2903
- instance._destroy();
2904
- });
2905
- };
2906
-
2907
- function setButtonsDisabled(instance, buttons, disabled) {
2908
- const domCache = privateProps.domCache.get(instance);
2909
- buttons.forEach(button => {
2910
- domCache[button].disabled = disabled;
2911
- });
2912
- }
2913
-
2914
- function setInputDisabled(input, disabled) {
2915
- if (!input) {
2916
- return false;
2917
- }
2918
-
2919
- if (input.type === 'radio') {
2920
- const radiosContainer = input.parentNode.parentNode;
2921
- const radios = radiosContainer.querySelectorAll('input');
2922
-
2923
- for (let i = 0; i < radios.length; i++) {
2924
- radios[i].disabled = disabled;
2925
- }
2926
- } else {
2927
- input.disabled = disabled;
2928
- }
2929
- }
2930
-
2931
- function enableButtons() {
2932
- setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
2933
- }
2934
- function disableButtons() {
2935
- setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
2936
- }
2937
- function enableInput() {
2938
- return setInputDisabled(this.getInput(), false);
2939
- }
2940
- function disableInput() {
2941
- return setInputDisabled(this.getInput(), true);
2942
- }
2943
-
2944
- function showValidationMessage(error) {
2945
- const domCache = privateProps.domCache.get(this);
2946
- const params = privateProps.innerParams.get(this);
2947
- setInnerHtml(domCache.validationMessage, error);
2948
- domCache.validationMessage.className = swalClasses['validation-message'];
2949
-
2950
- if (params.customClass && params.customClass.validationMessage) {
2951
- addClass(domCache.validationMessage, params.customClass.validationMessage);
2952
- }
2953
-
2954
- show(domCache.validationMessage);
2955
- const input = this.getInput();
2956
-
2957
- if (input) {
2958
- input.setAttribute('aria-invalid', true);
2959
- input.setAttribute('aria-describedby', swalClasses['validation-message']);
2960
- focusInput(input);
2961
- addClass(input, swalClasses.inputerror);
2962
- }
2963
- } // Hide block with validation message
2964
-
2965
- function resetValidationMessage$1() {
2966
- const domCache = privateProps.domCache.get(this);
2967
-
2968
- if (domCache.validationMessage) {
2969
- hide(domCache.validationMessage);
2970
- }
2971
-
2972
- const input = this.getInput();
2973
-
2974
- if (input) {
2975
- input.removeAttribute('aria-invalid');
2976
- input.removeAttribute('aria-describedby');
2977
- removeClass(input, swalClasses.inputerror);
2978
- }
2979
- }
2980
-
2981
- function getProgressSteps$1() {
2982
- const domCache = privateProps.domCache.get(this);
2983
- return domCache.progressSteps;
2984
- }
2985
-
2986
- /**
2987
- * Updates popup parameters.
2988
- */
2989
-
2990
- function update(params) {
2991
- const popup = getPopup();
2992
- const innerParams = privateProps.innerParams.get(this);
2993
-
2994
- if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
2995
- 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.");
2996
- }
2997
-
2998
- const validUpdatableParams = {}; // assign valid params from `params` to `defaults`
2999
-
3000
- Object.keys(params).forEach(param => {
3001
- if (isUpdatableParameter(param)) {
3002
- validUpdatableParams[param] = params[param];
3003
- } else {
3004
- warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md"));
3005
- }
3006
- });
3007
- const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
3008
- render(this, updatedParams);
3009
- privateProps.innerParams.set(this, updatedParams);
3010
- Object.defineProperties(this, {
3011
- params: {
3012
- value: Object.assign({}, this.params, params),
3013
- writable: false,
3014
- enumerable: true
3015
- }
3016
- });
3017
- }
3018
-
3019
- function _destroy() {
3020
- const domCache = privateProps.domCache.get(this);
3021
- const innerParams = privateProps.innerParams.get(this);
3022
-
3023
- if (!innerParams) {
3024
- disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
3025
-
3026
- return; // This instance has already been destroyed
3027
- } // Check if there is another Swal closing
3028
-
3029
-
3030
- if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
3031
- globalState.swalCloseEventFinishedCallback();
3032
- delete globalState.swalCloseEventFinishedCallback;
3033
- } // Check if there is a swal disposal defer timer
3034
-
3035
-
3036
- if (globalState.deferDisposalTimer) {
3037
- clearTimeout(globalState.deferDisposalTimer);
3038
- delete globalState.deferDisposalTimer;
3039
- }
3040
-
3041
- if (typeof innerParams.didDestroy === 'function') {
3042
- innerParams.didDestroy();
3043
- }
3044
-
3045
- disposeSwal(this);
3046
- }
3047
-
3048
- const disposeSwal = instance => {
3049
- disposeWeakMaps(instance); // Unset this.params so GC will dispose it (#1569)
3050
-
3051
- delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)
3052
-
3053
- delete globalState.keydownHandler;
3054
- delete globalState.keydownTarget; // Unset currentInstance
3055
-
3056
- delete globalState.currentInstance;
3057
- };
3058
-
3059
- const disposeWeakMaps = instance => {
3060
- // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
3061
- if (instance.isAwaitingPromise()) {
3062
- unsetWeakMaps(privateProps, instance);
3063
- privateProps.awaitingPromise.set(instance, true);
3064
- } else {
3065
- unsetWeakMaps(privateMethods, instance);
3066
- unsetWeakMaps(privateProps, instance);
3067
- }
3068
- };
3069
-
3070
- const unsetWeakMaps = (obj, instance) => {
3071
- for (const i in obj) {
3072
- obj[i].delete(instance);
3073
- }
3074
- };
3075
-
3076
-
3077
-
3078
- var instanceMethods = /*#__PURE__*/Object.freeze({
3079
- hideLoading: hideLoading,
3080
- disableLoading: hideLoading,
3081
- getInput: getInput$1,
3082
- close: close,
3083
- isAwaitingPromise: isAwaitingPromise,
3084
- rejectPromise: rejectPromise,
3085
- closePopup: close,
3086
- closeModal: close,
3087
- closeToast: close,
3088
- enableButtons: enableButtons,
3089
- disableButtons: disableButtons,
3090
- enableInput: enableInput,
3091
- disableInput: disableInput,
3092
- showValidationMessage: showValidationMessage,
3093
- resetValidationMessage: resetValidationMessage$1,
3094
- getProgressSteps: getProgressSteps$1,
3095
- update: update,
3096
- _destroy: _destroy
3097
- });
3098
-
3099
- let currentInstance;
3100
-
3101
- class SweetAlert {
3102
- constructor() {
3103
- // Prevent run in Node env
3104
- if (typeof window === 'undefined') {
3105
- return;
3106
- }
3107
-
3108
- currentInstance = this; // @ts-ignore
3109
-
3110
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3111
- args[_key] = arguments[_key];
3112
- }
3113
-
3114
- const outerParams = Object.freeze(this.constructor.argsToParams(args));
3115
- Object.defineProperties(this, {
3116
- params: {
3117
- value: outerParams,
3118
- writable: false,
3119
- enumerable: true,
3120
- configurable: true
3121
- }
3122
- }); // @ts-ignore
3123
-
3124
- const promise = this._main(this.params);
3125
-
3126
- privateProps.promise.set(this, promise);
3127
- }
3128
-
3129
- _main(userParams) {
3130
- let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3131
- showWarningsForParams(Object.assign({}, mixinParams, userParams));
3132
-
3133
- if (globalState.currentInstance) {
3134
- globalState.currentInstance._destroy();
3135
-
3136
- if (isModal()) {
3137
- unsetAriaHidden();
3138
- }
3139
- }
3140
-
3141
- globalState.currentInstance = this;
3142
- const innerParams = prepareParams(userParams, mixinParams);
3143
- setParameters(innerParams);
3144
- Object.freeze(innerParams); // clear the previous timer
3145
-
3146
- if (globalState.timeout) {
3147
- globalState.timeout.stop();
3148
- delete globalState.timeout;
3149
- } // clear the restore focus timeout
3150
-
3151
-
3152
- clearTimeout(globalState.restoreFocusTimeout);
3153
- const domCache = populateDomCache(this);
3154
- render(this, innerParams);
3155
- privateProps.innerParams.set(this, innerParams);
3156
- return swalPromise(this, domCache, innerParams);
3157
- } // `catch` cannot be the name of a module export, so we define our thenable methods here instead
3158
-
3159
-
3160
- then(onFulfilled) {
3161
- const promise = privateProps.promise.get(this);
3162
- return promise.then(onFulfilled);
3163
- }
3164
-
3165
- finally(onFinally) {
3166
- const promise = privateProps.promise.get(this);
3167
- return promise.finally(onFinally);
3168
- }
3169
-
3170
- }
3171
-
3172
- const swalPromise = (instance, domCache, innerParams) => {
3173
- return new Promise((resolve, reject) => {
3174
- // functions to handle all closings/dismissals
3175
- const dismissWith = dismiss => {
3176
- instance.closePopup({
3177
- isDismissed: true,
3178
- dismiss
3179
- });
3180
- };
3181
-
3182
- privateMethods.swalPromiseResolve.set(instance, resolve);
3183
- privateMethods.swalPromiseReject.set(instance, reject);
3184
-
3185
- domCache.confirmButton.onclick = () => handleConfirmButtonClick(instance);
3186
-
3187
- domCache.denyButton.onclick = () => handleDenyButtonClick(instance);
3188
-
3189
- domCache.cancelButton.onclick = () => handleCancelButtonClick(instance, dismissWith);
3190
-
3191
- domCache.closeButton.onclick = () => dismissWith(DismissReason.close);
3192
-
3193
- handlePopupClick(instance, domCache, dismissWith);
3194
- addKeydownHandler(instance, globalState, innerParams, dismissWith);
3195
- handleInputOptionsAndValue(instance, innerParams);
3196
- openPopup(innerParams);
3197
- setupTimer(globalState, innerParams, dismissWith);
3198
- initFocus(domCache, innerParams); // Scroll container to top on open (#1247, #1946)
3199
-
3200
- setTimeout(() => {
3201
- domCache.container.scrollTop = 0;
3202
- });
3203
- });
3204
- };
3205
-
3206
- const prepareParams = (userParams, mixinParams) => {
3207
- const templateParams = getTemplateParams(userParams);
3208
- const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
3209
-
3210
- params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
3211
- params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
3212
- return params;
3213
- };
3214
-
3215
- const populateDomCache = instance => {
3216
- const domCache = {
3217
- popup: getPopup(),
3218
- container: getContainer(),
3219
- actions: getActions(),
3220
- confirmButton: getConfirmButton(),
3221
- denyButton: getDenyButton(),
3222
- cancelButton: getCancelButton(),
3223
- loader: getLoader(),
3224
- closeButton: getCloseButton(),
3225
- validationMessage: getValidationMessage(),
3226
- progressSteps: getProgressSteps()
3227
- };
3228
- privateProps.domCache.set(instance, domCache);
3229
- return domCache;
3230
- };
3231
-
3232
- const setupTimer = (globalState$$1, innerParams, dismissWith) => {
3233
- const timerProgressBar = getTimerProgressBar();
3234
- hide(timerProgressBar);
3235
-
3236
- if (innerParams.timer) {
3237
- globalState$$1.timeout = new Timer(() => {
3238
- dismissWith('timer');
3239
- delete globalState$$1.timeout;
3240
- }, innerParams.timer);
3241
-
3242
- if (innerParams.timerProgressBar) {
3243
- show(timerProgressBar);
3244
- setTimeout(() => {
3245
- if (globalState$$1.timeout && globalState$$1.timeout.running) {
3246
- // timer can be already stopped or unset at this point
3247
- animateTimerProgressBar(innerParams.timer);
3248
- }
3249
- });
3250
- }
3251
- }
3252
- };
3253
-
3254
- const initFocus = (domCache, innerParams) => {
3255
- if (innerParams.toast) {
3256
- return;
3257
- }
3258
-
3259
- if (!callIfFunction(innerParams.allowEnterKey)) {
3260
- return blurActiveElement();
3261
- }
3262
-
3263
- if (!focusButton(domCache, innerParams)) {
3264
- setFocus(innerParams, -1, 1);
3265
- }
3266
- };
3267
-
3268
- const focusButton = (domCache, innerParams) => {
3269
- if (innerParams.focusDeny && isVisible(domCache.denyButton)) {
3270
- domCache.denyButton.focus();
3271
- return true;
3272
- }
3273
-
3274
- if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {
3275
- domCache.cancelButton.focus();
3276
- return true;
3277
- }
3278
-
3279
- if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {
3280
- domCache.confirmButton.focus();
3281
- return true;
3282
- }
3283
-
3284
- return false;
3285
- };
3286
-
3287
- const blurActiveElement = () => {
3288
- if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
3289
- document.activeElement.blur();
3290
- }
3291
- }; // Assign instance methods from src/instanceMethods/*.js to prototype
3292
-
3293
-
3294
- Object.assign(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor
3295
-
3296
- Object.assign(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility
3297
-
3298
- Object.keys(instanceMethods).forEach(key => {
3299
- SweetAlert[key] = function () {
3300
- if (currentInstance) {
3301
- return currentInstance[key](...arguments);
3302
- }
3303
- };
3304
- });
3305
- SweetAlert.DismissReason = DismissReason;
3306
- SweetAlert.version = '11.3.5';
3307
-
3308
- const Swal = SweetAlert; // @ts-ignore
3309
-
3310
- Swal.default = Swal;
3311
-
3312
- return Swal;
3313
-
3314
- }));
3315
- if (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}