PluginProbe
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses / 4.4.2
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses v4.4.2
4.4.8 4.4.7 4.4.6 4.4.5 4.4.4 4.4.3 4.4.2 4.4.1 4.4.0 4.3.9.1 4.3.9 4.3.8 4.3.7 4.1.6.9 4.1.6.9.1 4.1.6.9.2 4.1.6.9.3 4.1.6.9.4 4.1.7 4.1.7.1 4.1.7.2 4.1.7.3 4.1.7.3.1 4.1.7.3.2 4.2.0 All 139 releases
learnpress / assets / js / dist / frontend / profile.js

profile.js in LearnPress – WordPress LMS Plugin for Create and Sell Online Courses 4.4.2, at assets/js/dist/frontend/profile.js

11,467 lines 412.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (() => { // webpackBootstrap
2 /******/ var __webpack_modules__ = ({
3
4 /***/ "./assets/src/js/admin/courses/view-students-modal.js"
5 /*!************************************************************!*\
6 !*** ./assets/src/js/admin/courses/view-students-modal.js ***!
7 \************************************************************/
8 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
9
10 "use strict";
11 __webpack_require__.r(__webpack_exports__);
12 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
13 /* harmony export */ ViewStudentsModal: () => (/* binding */ ViewStudentsModal)
14 /* harmony export */ });
15 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sweetalert2 */ "./node_modules/sweetalert2/dist/sweetalert2.all.js");
16 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sweetalert2__WEBPACK_IMPORTED_MODULE_0__);
17 /* harmony import */ var lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lpAssetsJsPath/utils.js */ "./assets/src/js/utils.js");
18
19
20 class ViewStudentsModal {
21 constructor() {
22 this.isRequesting = false;
23 this.activeCourseId = 0;
24 this.init();
25 }
26 static selectors = {
27 wrap: '#lp-modal-enrolled-wrap',
28 form: '#lp-modal-enrolled-form',
29 toolbarTemplate: '#lp-tmpl-enrolled-students-toolbar-modal',
30 targetTemplate: '#lp-tmpl-enrolled-students-target-modal',
31 toolbar: '.lp-enrolled-students-table-toolbar--modal',
32 courseTrigger: '.lp-btn-view-students',
33 searchInput: '#lp-modal-enrolled-search-input',
34 startDateInput: '#lp-modal-enrolled-filter-start-date',
35 endDateInput: '#lp-modal-enrolled-filter-end-date',
36 searchBtn: '.lp-enrolled-btn-search-modal',
37 clearBtn: '.lp-enrolled-btn-clear-modal',
38 modalSearchFields: '#lp-modal-enrolled-search-input, #lp-modal-enrolled-filter-start-date, #lp-modal-enrolled-filter-end-date'
39 };
40 setButtonLoadingState(btn, isLoading) {
41 if (!btn) {
42 return;
43 }
44 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_1__.lpSetLoadingEl(btn, isLoading ? 1 : 0);
45 btn.disabled = !!isLoading;
46 }
47 init() {
48 if (ViewStudentsModal._loadedEvents) {
49 return;
50 }
51 ViewStudentsModal._loadedEvents = true;
52 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_1__.eventHandlers('click', [{
53 selector: ViewStudentsModal.selectors.courseTrigger,
54 class: this,
55 callBack: this.handleOpenModal.name
56 }, {
57 selector: ViewStudentsModal.selectors.searchBtn,
58 class: this,
59 callBack: this.handleModalSearch.name
60 }, {
61 selector: ViewStudentsModal.selectors.clearBtn,
62 class: this,
63 callBack: this.handleModalClear.name
64 }]);
65 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_1__.eventHandlers('keydown', [{
66 selector: ViewStudentsModal.selectors.modalSearchFields,
67 class: this,
68 callBack: this.handleModalSearchOnEnter.name,
69 checkIsEventEnter: true
70 }]);
71 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_1__.eventHandlers('change', [{
72 selector: ViewStudentsModal.selectors.startDateInput,
73 class: this,
74 callBack: this.checkDatesRange.name
75 }, {
76 selector: ViewStudentsModal.selectors.endDateInput,
77 class: this,
78 callBack: this.checkDatesRange.name
79 }]);
80 }
81 handleOpenModal(args) {
82 const btn = args?.target?.closest(ViewStudentsModal.selectors.courseTrigger);
83 if (!btn || this.isRequesting || btn.classList.contains('loading') || btn.disabled) {
84 return;
85 }
86 const courseId = parseInt(btn.dataset.courseId, 10) || 0;
87 if (!courseId) {
88 return;
89 }
90 const courseTitle = btn.dataset.courseTitle || '';
91 this.activeCourseId = courseId;
92 this.setButtonLoadingState(btn, true);
93 this.openModal(courseId, courseTitle, btn);
94 }
95 handleModalSearch(args) {
96 const btn = args?.target?.closest(ViewStudentsModal.selectors.searchBtn);
97 if (!btn || !this.activeCourseId) {
98 return;
99 }
100 if (args?.e) {
101 args.e.preventDefault();
102 }
103 if (this.isRequesting || btn.classList.contains('loading') || btn.disabled) {
104 return;
105 }
106 this.setButtonLoadingState(btn, true);
107 this.loadEnrolledStudents(this.activeCourseId, 1, btn);
108 }
109 handleModalSearchOnEnter(args) {
110 if (args?.e) {
111 args.e.preventDefault();
112 }
113 const form = this.getModalForm();
114 if (!form) {
115 return;
116 }
117 const btn = form.querySelector(ViewStudentsModal.selectors.searchBtn);
118 if (!btn) {
119 return;
120 }
121 this.handleModalSearch({
122 ...args,
123 target: btn
124 });
125 }
126 handleModalClear(args) {
127 const btn = args?.target?.closest(ViewStudentsModal.selectors.clearBtn);
128 const form = this.getModalForm();
129 if (!btn || !form || !this.activeCourseId) {
130 return;
131 }
132 if (args?.e) {
133 args.e.preventDefault();
134 }
135 if (this.isRequesting || btn.classList.contains('loading') || btn.disabled) {
136 return;
137 }
138 form.reset();
139 this.setButtonLoadingState(btn, true);
140 this.loadEnrolledStudents(this.activeCourseId, 1, btn);
141 }
142 getModalPopup() {
143 return (sweetalert2__WEBPACK_IMPORTED_MODULE_0___default().getPopup) ? sweetalert2__WEBPACK_IMPORTED_MODULE_0___default().getPopup() : null;
144 }
145 getModalToolbarHtml() {
146 const template = document.querySelector(ViewStudentsModal.selectors.toolbarTemplate);
147 return template ? template.innerHTML : '';
148 }
149 getModalTargetHtml() {
150 const template = document.querySelector(ViewStudentsModal.selectors.targetTemplate);
151 return template ? template.innerHTML : '';
152 }
153 getAjaxHandle() {
154 const ajaxHandle = window.lpAJAXG;
155 if (!ajaxHandle || typeof ajaxHandle.getDataSetCurrent !== 'function' || typeof ajaxHandle.setDataSetCurrent !== 'function' || typeof ajaxHandle.showHideLoading !== 'function' || typeof ajaxHandle.fetchAJAX !== 'function') {
156 return null;
157 }
158 return ajaxHandle;
159 }
160 getModalForm() {
161 const popup = this.getModalPopup();
162 if (!popup) {
163 return null;
164 }
165 return popup.querySelector(ViewStudentsModal.selectors.form);
166 }
167 getModalFilterArgs(dataArgs = {}) {
168 const form = this.getModalForm();
169 if (!form) {
170 return dataArgs;
171 }
172 return lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_1__.mergeDataWithDatForm(form, dataArgs);
173 }
174 loadEnrolledStudents(courseId, paged, elLoading = null) {
175 const wrap = document.querySelector(ViewStudentsModal.selectors.wrap);
176 const elTarget = wrap?.querySelector('.lp-target');
177 const ajaxHandle = this.getAjaxHandle();
178 if (!wrap || !elTarget || !ajaxHandle || this.isRequesting) {
179 return;
180 }
181 this.isRequesting = true;
182 if (elLoading) {
183 this.setButtonLoadingState(elLoading, true);
184 }
185 const dataSend = ajaxHandle.getDataSetCurrent(elTarget);
186 dataSend.args = this.getModalFilterArgs(dataSend.args || {});
187 dataSend.args.course_id = parseInt(courseId, 10) || 0;
188 dataSend.args.paged = paged;
189 ajaxHandle.setDataSetCurrent(elTarget, dataSend);
190 ajaxHandle.showHideLoading(elTarget, 1);
191 const callBack = {
192 success: response => {
193 elTarget.innerHTML = response.data.content;
194 },
195 error: err => {
196 console.error(err);
197 },
198 completed: () => {
199 this.isRequesting = false;
200 ajaxHandle.showHideLoading(elTarget, 0);
201 if (elLoading) {
202 this.setButtonLoadingState(elLoading, false);
203 }
204 }
205 };
206 ajaxHandle.fetchAJAX(dataSend, callBack);
207 }
208 openModal(courseId, courseTitle, elTrigger = null) {
209 const modalToolbarHtml = this.getModalToolbarHtml();
210 const modalTargetHtml = this.getModalTargetHtml();
211 if (!modalToolbarHtml || !modalTargetHtml) {
212 if (elTrigger) {
213 this.setButtonLoadingState(elTrigger, false);
214 }
215 return;
216 }
217 this.activeCourseId = parseInt(courseId, 10) || 0;
218 sweetalert2__WEBPACK_IMPORTED_MODULE_0___default().fire({
219 title: `${courseTitle}`,
220 html: modalToolbarHtml + modalTargetHtml,
221 width: '80%',
222 showConfirmButton: false,
223 showCloseButton: true,
224 didOpen: () => {
225 this.loadEnrolledStudents(this.activeCourseId, 1, elTrigger);
226 },
227 didClose: () => {
228 this.activeCourseId = 0;
229 if (elTrigger) {
230 this.setButtonLoadingState(elTrigger, false);
231 }
232 }
233 });
234 }
235
236 // Ensure start date is not after end date and vice versa. If invalid, adjust the other date to match.
237 checkDatesRange(args) {
238 const {
239 e
240 } = args;
241 const elInput = e?.target;
242 if (!elInput) {
243 return;
244 }
245 const elForm = elInput.closest(ViewStudentsModal.selectors.form);
246 if (!elForm) {
247 return;
248 }
249 const startDateInput = elForm.querySelector(ViewStudentsModal.selectors.startDateInput);
250 const endDateInput = elForm.querySelector(ViewStudentsModal.selectors.endDateInput);
251 if (elInput === startDateInput) {
252 if (startDateInput.value) {
253 endDateInput.min = startDateInput.value;
254 if (endDateInput.value && endDateInput.value < startDateInput.value) {
255 endDateInput.value = startDateInput.value;
256 }
257 } else {
258 endDateInput.min = '';
259 }
260 } else if (elInput === endDateInput) {
261 if (endDateInput.value) {
262 startDateInput.max = endDateInput.value;
263 if (startDateInput.value && startDateInput.value > endDateInput.value) {
264 startDateInput.value = endDateInput.value;
265 }
266 } else {
267 startDateInput.max = '';
268 }
269 }
270 }
271 }
272
273 /***/ },
274
275 /***/ "./assets/src/js/api.js"
276 /*!******************************!*\
277 !*** ./assets/src/js/api.js ***!
278 \******************************/
279 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
280
281 "use strict";
282 __webpack_require__.r(__webpack_exports__);
283 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
284 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
285 /* harmony export */ });
286 /**
287 * List API on backend
288 *
289 * @since 4.2.6
290 * @version 1.0.2
291 */
292
293 const lplistAPI = {};
294 let lp_rest_url;
295 if ('undefined' !== typeof lpDataAdmin) {
296 lp_rest_url = lpDataAdmin.lp_rest_url;
297 lplistAPI.admin = {
298 apiAdminNotice: lp_rest_url + 'lp/v1/admin/tools/admin-notices',
299 apiAddons: lp_rest_url + 'lp/v1/addon/all',
300 apiAddonAction: lp_rest_url + 'lp/v1/addon/action-n',
301 apiAddonsPurchase: lp_rest_url + 'lp/v1/addon/info-addons-purchase',
302 apiSearchCourses: lp_rest_url + 'lp/v1/admin/tools/search-course',
303 apiSearchUsers: lp_rest_url + 'lp/v1/admin/tools/search-user',
304 apiAssignUserCourse: lp_rest_url + 'lp/v1/admin/tools/assign-user-course',
305 apiUnAssignUserCourse: lp_rest_url + 'lp/v1/admin/tools/unassign-user-course'
306 };
307 }
308 if ('undefined' !== typeof lpData) {
309 lp_rest_url = lpData.lp_rest_url;
310 lplistAPI.frontend = {
311 apiWidgets: lp_rest_url + 'lp/v1/widgets/api',
312 apiCourses: lp_rest_url + 'lp/v1/courses/archive-course',
313 // Deprecated API, don't load from v4.3.7
314 apiAJAX: lp_rest_url + 'lp/v1/load_content_via_ajax/',
315 // Deprecated since 4.3.0
316 apiProfileCoverImage: lp_rest_url + 'lp/v1/profile/cover-image'
317 };
318 }
319 if (lp_rest_url) {
320 lplistAPI.apiCourses = lp_rest_url + 'lp/v1/courses/';
321 lplistAPI.apiEditCoursesArchiveBlock = lp_rest_url + 'lp/v1/courses/edit-archive-block';
322 lplistAPI.apiCoursesSuggest = lp_rest_url + 'lp/v1/courses/courses-suggest';
323 }
324 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (lplistAPI);
325
326 /***/ },
327
328 /***/ "./assets/src/js/frontend/profile/avatar.js"
329 /*!**************************************************!*\
330 !*** ./assets/src/js/frontend/profile/avatar.js ***!
331 \**************************************************/
332 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
333
334 "use strict";
335 __webpack_require__.r(__webpack_exports__);
336 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
337 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
338 /* harmony export */ });
339 /* harmony import */ var cropperjs_dist_cropper_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cropperjs/dist/cropper.css */ "./node_modules/cropperjs/dist/cropper.css");
340 /* harmony import */ var cropperjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cropperjs */ "./node_modules/cropperjs/dist/cropper.js");
341 /* harmony import */ var cropperjs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(cropperjs__WEBPACK_IMPORTED_MODULE_1__);
342 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils.js */ "./assets/src/js/utils.js");
343 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! toastify-js */ "./node_modules/toastify-js/src/toastify.js");
344 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(toastify_js__WEBPACK_IMPORTED_MODULE_3__);
345 /* harmony import */ var toastify_js_src_toastify_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! toastify-js/src/toastify.css */ "./node_modules/toastify-js/src/toastify.css");
346
347
348
349 // import API from '../../api.js';
350
351
352 const profileAvatarImage = () => {
353 const lpAvatarWrapper = document.querySelector('#learnpress-avatar-upload');
354 if (!lpAvatarWrapper) {
355 return;
356 }
357 let cropper, avatarPreviewSrc, imgUrlOriginal;
358 let avatarForm = lpAvatarWrapper.querySelector('.lp_avatar__form');
359 const btnRemove = lpAvatarWrapper.querySelector('.lp-btn-remove-avatar'),
360 btnReplace = lpAvatarWrapper.querySelector('.lp-btn-choose-avatar'),
361 btnSave = lpAvatarWrapper.querySelector('.lp-btn-save-avatar'),
362 btnCancel = lpAvatarWrapper.querySelector('.lp-btn-cancel-avatar'),
363 avatarPreviewImage = lpAvatarWrapper.querySelector('.lp-avatar-image'),
364 avatarInputFile = lpAvatarWrapper.querySelector('#avatar-file'),
365 profileAvatar = document.querySelector('.wrapper-profile-header .user-avatar img');
366 const avatarRatio = parseFloat((lpProfileSettings.avatar_dimensions.width / lpProfileSettings.avatar_dimensions.height).toFixed(2));
367 lpAvatarWrapper.addEventListener('click', e => {
368 const target = e.target;
369 if (target === btnReplace) {
370 e.preventDefault();
371 avatarInputFile.click();
372 } else if (target === btnSave) {
373 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(btnSave, 1);
374 btnSave.disabled = true;
375 if (undefined !== cropper) {
376 const canvas = cropper.getCroppedCanvas({
377 width: lpProfileSettings.avatar_dimensions.width,
378 height: lpProfileSettings.avatar_dimensions.height
379 });
380 const newCropSrc = canvas.toDataURL('image/png');
381 if (profileAvatar) {
382 profileAvatar.src = newCropSrc;
383 }
384 avatarPreviewImage.src = newCropSrc;
385 const formData = new FormData();
386 formData.append('file', newCropSrc);
387 uploadAvatar(formData);
388 }
389 } else if (target === btnCancel) {
390 e.preventDefault();
391 cropper.destroy();
392 avatarPreviewImage.src = imgUrlOriginal;
393 if (imgUrlOriginal === window.location.href) {
394 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(avatarForm, 1);
395 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnReplace, 0);
396 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(avatarPreviewImage, 0);
397 } else {
398 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnRemove, 1);
399 }
400 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnSave, 0);
401 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnCancel, 0);
402 } else if (target === btnRemove) {
403 btnRemove.disabled = true;
404 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(btnRemove, 1);
405 removeAvatar();
406 }
407 });
408 lpAvatarWrapper.addEventListener('change', e => {
409 const target = e.target;
410 if (target === avatarInputFile) {
411 const file = avatarInputFile.files[0];
412 if (!file) {
413 return;
414 }
415 const allowType = ['image/png', 'image/jpeg', 'image/webp'];
416 if (allowType.indexOf(file.type) < 0) {
417 return;
418 }
419 const reader = new FileReader();
420 reader.onload = function (e) {
421 avatarPreviewImage.src = e.target.result;
422 // Destroy previous cropper instance if any
423 if (cropper) {
424 cropper.destroy();
425 }
426 // Initialize cropper
427 cropper = new (cropperjs__WEBPACK_IMPORTED_MODULE_1___default())(avatarPreviewImage, {
428 aspectRatio: avatarRatio,
429 viewMode: 1,
430 zoomOnWheel: false
431 });
432 };
433 reader.readAsDataURL(file);
434 if (!avatarPreviewImage.classList.contains('lp-hidden')) {
435 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(avatarPreviewImage, 1);
436 }
437 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(avatarForm, 0);
438 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnSave, 1);
439 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnReplace, 1);
440 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnCancel, 1);
441 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnRemove, 0);
442 }
443 });
444 const uploadAvatar = formData => {
445 fetch(`${lpData.lp_rest_url}lp/v1/profile/upload-avatar`, {
446 method: 'POST',
447 headers: {
448 'X-WP-Nonce': lpData.nonce
449 },
450 body: formData
451 }) // wrapped
452 .then(res => res.json()).then(res => {
453 if (res.status === 'error') {
454 throw new Error(res.message);
455 }
456 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(avatarPreviewImage, 1);
457 showMessage('success', res.message);
458 if (undefined !== cropper) {
459 cropper.destroy();
460 }
461 imgUrlOriginal = avatarPreviewImage.src;
462 }).finally(() => {
463 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnSave, 0);
464 btnSave.disabled = false;
465 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(btnSave, 0);
466 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnCancel, 0);
467 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnRemove, 1);
468 }).catch(err => console.log(err));
469 };
470 const removeAvatar = () => {
471 fetch(`${lpData.lp_rest_url}lp/v1/profile/remove-avatar`, {
472 method: 'POST',
473 headers: {
474 'X-WP-Nonce': lpData.nonce
475 }
476 }) // wrapped
477 .then(res => res.json()).then(res => {
478 if (res.status === 'error') {
479 throw new Error(res.message);
480 }
481 showMessage('success', res.message);
482 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(avatarPreviewImage, 0);
483 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(avatarForm, 1);
484 imgUrlOriginal = avatarPreviewSrc = '';
485 profileAvatar.src = lpProfileSettings.default_avatar;
486 // window.location.href = window.location.href;
487 }).finally(() => {
488 btnRemove.disabled = false;
489 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnRemove, 0);
490 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(btnRemove, 0);
491 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(btnReplace, 0);
492 }).catch(err => console.log(err));
493 };
494 const showMessage = (status, message) => {
495 toastify_js__WEBPACK_IMPORTED_MODULE_3___default()({
496 text: message,
497 gravity: lpData.toast.gravity,
498 // `top` or `bottom`
499 position: lpData.toast.position,
500 // `left`, `center` or `right`
501 className: `${lpData.toast.classPrefix} ${status}`,
502 close: lpData.toast.close == 1,
503 stopOnFocus: lpData.toast.stopOnFocus == 1,
504 duration: lpData.toast.duration
505 }).showToast();
506 };
507 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpOnElementReady('.lp-avatar-image', () => {
508 imgUrlOriginal = avatarPreviewImage.src;
509 });
510 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpOnElementReady('#learnpress-avatar-upload', e => {
511 e.scrollIntoView({
512 behavior: 'smooth',
513 block: 'center'
514 });
515 });
516 };
517 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (profileAvatarImage);
518
519 /***/ },
520
521 /***/ "./assets/src/js/frontend/profile/course-tab.js"
522 /*!******************************************************!*\
523 !*** ./assets/src/js/frontend/profile/course-tab.js ***!
524 \******************************************************/
525 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
526
527 "use strict";
528 __webpack_require__.r(__webpack_exports__);
529 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
530 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
531 /* harmony export */ });
532 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils.js */ "./assets/src/js/utils.js");
533
534
535 // Rest API load content course enrolled, created - Nhamdv.
536 const courseTab = () => {
537 const elements = document.querySelectorAll('.learn-press-course-tab__filter__content');
538 const getResponse = (ele, dataset, append = false, viewMoreEle = false) => {
539 let url = lpData.lp_rest_url + 'lp/v1/profile/course-tab';
540 url = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpAddQueryArgs)(url, dataset);
541 const callBack = {
542 success: response => {
543 const skeleton = ele.querySelector('.lp-skeleton-animation');
544 skeleton && skeleton.remove();
545 if (response.status === 'success' && response.data) {
546 if (append) {
547 ele.innerHTML += response.data;
548 } else {
549 ele.innerHTML = response.data;
550 }
551 } else if (append) {
552 ele.innerHTML += `<div class="lp-ajax-message" style="display:block">${response.message && response.message}</div>`;
553 } else {
554 ele.innerHTML = `<div class="lp-ajax-message" style="display:block">${response.message && response.message}</div>`;
555 }
556 if (viewMoreEle) {
557 viewMoreEle.classList.remove('loading');
558 const paged = parseInt(viewMoreEle.dataset.paged);
559 const numberPage = parseInt(viewMoreEle.dataset.number);
560 if (numberPage <= paged) {
561 viewMoreEle.remove();
562 }
563 viewMoreEle.dataset.paged = paged + 1;
564 }
565 viewMore(ele, dataset);
566 },
567 error: error => {
568 console.log(error);
569 },
570 completed: () => {}
571 };
572 let paramsFetch = {};
573 if (0 !== parseInt(lpData.user_id)) {
574 paramsFetch = {
575 headers: {
576 'X-WP-Nonce': lpData.nonce
577 }
578 };
579 }
580 (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpFetchAPI)(url, paramsFetch, callBack);
581 };
582 if ('IntersectionObserver' in window) {
583 const eleObserver = new IntersectionObserver((entries, observer) => {
584 entries.forEach(entry => {
585 if (entry.isIntersecting) {
586 const ele = entry.target;
587 const params = ele.parentNode.querySelector('.lp_profile_tab_input_param');
588 const data = {
589 ...JSON.parse(params.value),
590 status: ele.dataset.tab || ''
591 };
592 getResponse(ele, data);
593 eleObserver.unobserve(ele);
594 }
595 });
596 });
597 [...elements].map(ele => {
598 if (ele.dataset.tab !== 'all') {
599 eleObserver.observe(ele);
600 } else {
601 const params = ele.parentNode.querySelector('.lp_profile_tab_input_param');
602 const data = {
603 ...JSON.parse(params.value),
604 status: ele.dataset.tab === 'all' ? '' : ele.dataset.tab || ''
605 };
606 getResponse(ele, data);
607 }
608 });
609 }
610 const changeFilter = () => {
611 const tabs = document.querySelectorAll('.learn-press-course-tab-filters');
612 tabs.forEach(tab => {
613 const filters = tab.querySelectorAll('.learn-press-filters a');
614 filters.forEach(filter => {
615 filter.addEventListener('click', e => {
616 e.preventDefault();
617 const tabName = filter.dataset.tab;
618 [...filters].map(ele => {
619 ele.classList.remove('active');
620 });
621 filter.classList.add('active');
622 [...tab.querySelectorAll('.learn-press-course-tab__filter__content')].map(ele => {
623 ele.style.display = 'none';
624 if (ele.dataset.tab === tabName) {
625 ele.style.display = '';
626 }
627 });
628 });
629 });
630 });
631 };
632 changeFilter();
633 const viewMore = (ele, dataset) => {
634 const viewMoreEle = ele.querySelector('button[data-paged]');
635 if (viewMoreEle) {
636 viewMoreEle.addEventListener('click', e => {
637 e.preventDefault();
638 const paged = viewMoreEle && viewMoreEle.dataset.paged;
639 viewMoreEle.classList.add('loading');
640 const element = dataset.layout === 'list' ? '.lp_profile_course_progress' : '.learn-press-courses';
641 getResponse(ele.querySelector(element), {
642 ...dataset,
643 ...{
644 paged
645 }
646 }, true, viewMoreEle);
647 });
648 }
649 };
650 };
651 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (courseTab);
652
653 /***/ },
654
655 /***/ "./assets/src/js/frontend/profile/cover-image.js"
656 /*!*******************************************************!*\
657 !*** ./assets/src/js/frontend/profile/cover-image.js ***!
658 \*******************************************************/
659 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
660
661 "use strict";
662 __webpack_require__.r(__webpack_exports__);
663 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
664 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
665 /* harmony export */ });
666 /* harmony import */ var cropperjs_dist_cropper_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cropperjs/dist/cropper.css */ "./node_modules/cropperjs/dist/cropper.css");
667 /* harmony import */ var cropperjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cropperjs */ "./node_modules/cropperjs/dist/cropper.js");
668 /* harmony import */ var cropperjs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(cropperjs__WEBPACK_IMPORTED_MODULE_1__);
669 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils.js */ "./assets/src/js/utils.js");
670 /* harmony import */ var _api_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../api.js */ "./assets/src/js/api.js");
671 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! toastify-js */ "./node_modules/toastify-js/src/toastify.js");
672 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(toastify_js__WEBPACK_IMPORTED_MODULE_4__);
673 /* harmony import */ var toastify_js_src_toastify_css__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! toastify-js/src/toastify.css */ "./node_modules/toastify-js/src/toastify.css");
674
675
676
677
678
679
680 const profileCoverImage = () => {
681 const lpSet = new Set();
682 let cropper;
683 let elBtnSave, elBtnRemove, elBtnChoose, elBtnCancel, elImagePreview, elCoverImageBackground, elImgCoverImageBackground, elImageEmpty, formCoverImage, elInputFile, elAction, imgUrlOriginal;
684 const className = {
685 formCoverImage: 'lp-user-cover-image',
686 BtnChooseCoverImage: 'lp-btn-choose-cover-image',
687 BtnSaveCoverImage: 'lp-btn-save-cover-image',
688 BtnRemoveCoverImage: 'lp-btn-remove-cover-image',
689 BtnCancelCoverImage: 'lp-btn-cancel-cover-image',
690 BtnToEditCoverImage: 'lp-btn-to-edit-cover-image',
691 CoverImagePreview: 'lp-cover-image-preview',
692 CoverImageEmpty: 'lp-cover-image-empty',
693 CoverImageBackground: 'lp-user-cover-image_background',
694 InputFile: 'lp-cover-image-file',
695 loading: 'loading',
696 hidden: 'lp-hidden'
697 };
698
699 /**
700 * Get elements to use.
701 */
702 const getElements = () => {
703 elBtnSave = formCoverImage.querySelector(`.${className.BtnSaveCoverImage}`);
704 elBtnChoose = formCoverImage.querySelector(`.${className.BtnChooseCoverImage}`);
705 elBtnRemove = formCoverImage.querySelector(`.${className.BtnRemoveCoverImage}`);
706 elBtnCancel = formCoverImage.querySelector(`.${className.BtnCancelCoverImage}`);
707 elImagePreview = formCoverImage.querySelector(`.${className.CoverImagePreview}`);
708 elCoverImageBackground = document.querySelector(`.${className.CoverImageBackground}`);
709 elImgCoverImageBackground = elCoverImageBackground.querySelector(`img`);
710 elImageEmpty = formCoverImage.querySelector(`.${className.CoverImageEmpty}`);
711 elAction = formCoverImage.querySelector('input[name=action]');
712 elInputFile = formCoverImage.querySelector('input[name=lp-cover-image-file]');
713 if (!lpSet.has('everClick')) {
714 imgUrlOriginal = elImagePreview.src;
715 lpSet.add('everClick');
716 }
717 };
718 const fetchAPI = formData => {
719 const callBack = {
720 success: response => {
721 const {
722 status,
723 message,
724 data
725 } = response;
726 toastify_js__WEBPACK_IMPORTED_MODULE_4___default()({
727 text: message,
728 gravity: lpData.toast.gravity,
729 // `top` or `bottom`
730 position: lpData.toast.position,
731 // `left`, `center` or `right`
732 className: `${lpData.toast.classPrefix} ${status}`,
733 close: lpData.toast.close == 1,
734 stopOnFocus: lpData.toast.stopOnFocus == 1,
735 duration: lpData.toast.duration
736 }).showToast();
737 if ('remove' === data.action) {
738 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnRemove, 0);
739 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnChoose, 0);
740 elImagePreview.src = '';
741 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elImagePreview, 0);
742 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elImageEmpty, 1);
743 if (elCoverImageBackground) {
744 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elCoverImageBackground, 0);
745 }
746 } else if ('upload' === data.action) {
747 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elImagePreview, 1);
748 elImagePreview.src = data.url;
749 imgUrlOriginal = data.url;
750 cropper.destroy();
751 }
752 imgUrlOriginal = elImagePreview.src;
753 },
754 error: error => {
755 console.log(error);
756 },
757 completed: () => {
758 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnSave, 0);
759 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(elBtnSave, 0);
760 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(elBtnRemove, 0);
761 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnCancel, 0);
762 if (!elImagePreview.src || elImagePreview.src === window.location.href) {
763 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnRemove, 0);
764 } else {
765 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnRemove, 1);
766 }
767 }
768 };
769 const url = _api_js__WEBPACK_IMPORTED_MODULE_3__["default"].frontend.apiProfileCoverImage;
770 const option = {
771 headers: {}
772 };
773 if (0 !== parseInt(lpData.user_id)) {
774 option.headers['X-WP-Nonce'] = lpData.nonce;
775 }
776 option.method = 'POST';
777 option.body = formData;
778 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpFetchAPI(url, option, callBack);
779 };
780
781 // Events
782 document.addEventListener('click', e => {
783 const target = e.target;
784 if (target.classList.contains(className.BtnToEditCoverImage)) {
785 formCoverImage = document.querySelector(`.${className.formCoverImage}`);
786 if (!formCoverImage) {
787 return;
788 }
789 const isCorrectSection = target.dataset.sectionCorrect == 1;
790 if (isCorrectSection) {
791 e.preventDefault();
792 formCoverImage.scrollIntoView({
793 behavior: 'smooth',
794 block: 'center'
795 });
796 }
797 }
798 formCoverImage = target.closest(`.${className.formCoverImage}`);
799 if (!formCoverImage) {
800 return;
801 }
802 getElements();
803 if (target.classList.contains(className.BtnChooseCoverImage)) {
804 e.preventDefault();
805 elInputFile.click();
806 }
807 if (target.classList.contains(className.BtnSaveCoverImage)) {
808 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(elBtnSave, 1);
809 }
810 if (target.classList.contains(className.BtnCancelCoverImage)) {
811 e.preventDefault();
812 cropper.destroy();
813 elImagePreview.src = imgUrlOriginal;
814 if (imgUrlOriginal === window.location.href) {
815 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elImageEmpty, 1);
816 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnChoose, 0);
817 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elImagePreview, 0);
818 } else {
819 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnRemove, 1);
820 }
821 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnSave, 0);
822 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnCancel, 0);
823 }
824 if (target.classList.contains(className.BtnRemoveCoverImage)) {
825 e.preventDefault();
826 target.classList.add('loading');
827 if (cropper) {
828 cropper.destroy();
829 cropper = undefined;
830 }
831 elAction.value = 'remove';
832 elBtnSave.click();
833 }
834 if (target.classList.contains(className.CoverImageEmpty)) {
835 e.preventDefault();
836 elInputFile.click();
837 }
838 });
839 document.addEventListener('change', e => {
840 const target = e.target;
841 formCoverImage = target.closest(`.${className.formCoverImage}`);
842 if (!formCoverImage) {
843 return;
844 }
845 getElements();
846 if (target.classList.contains(className.InputFile)) {
847 e.preventDefault();
848 const file = target.files[0];
849 if (!file) {
850 return;
851 }
852 const allowType = ['image/png', 'image/jpeg', 'image/webp'];
853 if (allowType.indexOf(file.type) < 0) {
854 return;
855 }
856 elAction.value = 'upload';
857 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elImagePreview, 1);
858 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elImageEmpty, 0);
859 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnRemove, 0);
860 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnSave, 1);
861 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnChoose, 1);
862 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elBtnCancel, 1);
863 const reader = new FileReader();
864 reader.onload = function (e) {
865 elImagePreview.src = e.target.result;
866 // Destroy previous cropper instance if any
867 if (cropper) {
868 cropper.destroy();
869 }
870 // Initialize cropper
871 cropper = new (cropperjs__WEBPACK_IMPORTED_MODULE_1___default())(elImagePreview, {
872 aspectRatio: lpData.coverImageRatio,
873 viewMode: 1,
874 zoomOnWheel: false
875 });
876 };
877 reader.readAsDataURL(file);
878 }
879 });
880 document.addEventListener('submit', e => {
881 const target = e.target;
882 if (target.classList.contains(className.formCoverImage)) {
883 e.preventDefault();
884 const formData = new FormData(target);
885 if (undefined !== cropper) {
886 const canvas = cropper.getCroppedCanvas({});
887 if (elCoverImageBackground) {
888 const dataUrl = canvas.toDataURL('image/png');
889 elCoverImageBackground.style.backgroundImage = `url(${dataUrl})`;
890 elImgCoverImageBackground.src = dataUrl;
891 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpShowHideEl(elCoverImageBackground, 1);
892 }
893 canvas.toBlob(blob => {
894 formData.append('image', blob, 'cover.png');
895 fetchAPI(formData);
896 }, 'image/png');
897 } else {
898 fetchAPI(formData);
899 }
900 }
901 });
902 document.addEventListener('DOMContentLoaded', e => {
903 const elBtnToEditCoverImage = document.querySelector(`.${className.BtnToEditCoverImage}`);
904 const formCoverImage = document.querySelector(`.${className.formCoverImage}`);
905 if (elBtnToEditCoverImage && formCoverImage) {
906 const isCorrectSection = elBtnToEditCoverImage.dataset.sectionCorrect == 1;
907 if (isCorrectSection) {
908 formCoverImage.scrollIntoView({
909 behavior: 'smooth',
910 block: 'center'
911 });
912 }
913 }
914 });
915 };
916 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (profileCoverImage);
917
918 /***/ },
919
920 /***/ "./assets/src/js/frontend/profile/order-recover.js"
921 /*!*********************************************************!*\
922 !*** ./assets/src/js/frontend/profile/order-recover.js ***!
923 \*********************************************************/
924 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
925
926 "use strict";
927 __webpack_require__.r(__webpack_exports__);
928 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
929 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
930 /* harmony export */ });
931 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils.js */ "./assets/src/js/utils.js");
932 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! toastify-js */ "./node_modules/toastify-js/src/toastify.js");
933 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(toastify_js__WEBPACK_IMPORTED_MODULE_1__);
934
935
936
937 /**
938 * JS Recover order
939 *
940 * @since 4.0.0
941 * @version 1.0.1
942 */
943 const recoverOrder = () => {
944 const toastify = toastify_js__WEBPACK_IMPORTED_MODULE_1___default()({
945 gravity: lpData.toast.gravity,
946 // `top` or `bottom`
947 position: lpData.toast.position,
948 // `left`, `center` or `right`
949 close: lpData.toast.close == 1,
950 className: `${lpData.toast.classPrefix}`,
951 stopOnFocus: lpData.toast.stopOnFocus == 1,
952 duration: lpData.toast.duration
953 });
954
955 // Events
956 document.addEventListener('submit', e => {
957 const target = e.target;
958 if (target.classList.contains('lp-order-recover')) {
959 e.preventDefault();
960 ajaxRecover(target);
961 }
962 });
963 const ajaxRecover = form => {
964 const status = 'error';
965 const btnSubmit = form.querySelector('.button-recover-order');
966 if (!btnSubmit) {
967 return;
968 }
969 (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl)(btnSubmit, 1);
970 const url = new URL(window.location.href);
971 fetch(url, {
972 method: 'POST',
973 body: new FormData(form)
974 }).then(response => {
975 return response.json();
976 }).then(res => {
977 const {
978 status,
979 data: {
980 redirect
981 },
982 message
983 } = res;
984 if (status === 'success') {
985 toastify.options.text = message;
986 toastify.options.className += ` ${status}`;
987 toastify.showToast();
988 if (redirect) {
989 window.location.href = redirect;
990 }
991 btnSubmit.remove();
992 } else {
993 (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl)(btnSubmit, 0);
994 throw new Error(message);
995 }
996 }).finally(() => {}).catch(err => {
997 toastify.options.text = err.message;
998 toastify.options.className += ` ${status}`;
999 toastify.showToast();
1000 });
1001 };
1002 };
1003 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (recoverOrder);
1004
1005 /***/ },
1006
1007 /***/ "./assets/src/js/frontend/profile/order-refund.js"
1008 /*!********************************************************!*\
1009 !*** ./assets/src/js/frontend/profile/order-refund.js ***!
1010 \********************************************************/
1011 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1012
1013 "use strict";
1014 __webpack_require__.r(__webpack_exports__);
1015 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1016 /* harmony export */ OrderRefund: () => (/* binding */ OrderRefund),
1017 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
1018 /* harmony export */ });
1019 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sweetalert2 */ "./node_modules/sweetalert2/dist/sweetalert2.all.js");
1020 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sweetalert2__WEBPACK_IMPORTED_MODULE_0__);
1021 /* harmony import */ var _lpToastify__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../lpToastify */ "./assets/src/js/lpToastify.js");
1022 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils.js */ "./assets/src/js/utils.js");
1023
1024
1025
1026
1027 /**
1028 * Order Refund Script
1029 *
1030 * Handle refund action on profile orders list.
1031 *
1032 * @since 4.3.5
1033 * @version 1.0.0
1034 */
1035 class OrderRefund {
1036 constructor() {
1037 this.isRequesting = false;
1038 }
1039 static selectors = {
1040 actionRefund: '.lp-refund-order-action'
1041 };
1042 init() {
1043 this.events();
1044 }
1045 events() {
1046 if (OrderRefund._loadedEvents) {
1047 return;
1048 }
1049 OrderRefund._loadedEvents = this;
1050 _utils_js__WEBPACK_IMPORTED_MODULE_2__.eventHandlers('click', [{
1051 selector: OrderRefund.selectors.actionRefund,
1052 class: this,
1053 callBack: this.handleRefundClick.name
1054 }]);
1055 }
1056 getAjaxHandle() {
1057 const ajaxHandle = window.lpAJAXG;
1058 if (!ajaxHandle || typeof ajaxHandle.fetchAJAX !== 'function') {
1059 return null;
1060 }
1061 return ajaxHandle;
1062 }
1063 setActionLoadingState(actionLink, isLoading) {
1064 if (!actionLink) {
1065 return;
1066 }
1067 if (isLoading) {
1068 actionLink.dataset.refundSubmitting = 'yes';
1069 } else {
1070 delete actionLink.dataset.refundSubmitting;
1071 }
1072 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpSetLoadingEl(actionLink, isLoading ? 1 : 0);
1073 }
1074 getActionData(actionLink) {
1075 const reasonMin = parseInt(actionLink.dataset.reasonMin || '10', 10);
1076 return {
1077 orderId: parseInt(actionLink.dataset.orderId || '0', 10),
1078 requireReason: actionLink.dataset.requireReason === 'yes',
1079 reasonMin: Number.isNaN(reasonMin) ? 10 : reasonMin,
1080 reasonPrompt: actionLink.dataset.reasonPrompt || '',
1081 reasonPlaceholder: actionLink.dataset.reasonPlaceholder || '',
1082 reasonRequired: actionLink.dataset.reasonRequired || '',
1083 confirmTitle: actionLink.dataset.confirmTitle || '',
1084 confirmText: actionLink.dataset.confirmText || '',
1085 confirmButton: actionLink.dataset.confirmButton || '',
1086 cancelButton: actionLink.dataset.cancelButton || ''
1087 };
1088 }
1089 openReasonModal(data) {
1090 return sweetalert2__WEBPACK_IMPORTED_MODULE_0___default().fire({
1091 title: data.reasonPrompt,
1092 input: 'textarea',
1093 inputPlaceholder: data.reasonPlaceholder,
1094 inputAutoTrim: true,
1095 showCancelButton: true,
1096 confirmButtonText: data.confirmButton,
1097 cancelButtonText: data.cancelButton,
1098 inputValidator: value => {
1099 const reason = (value || '').trim();
1100 if (!reason.length) {
1101 return data.reasonRequired;
1102 }
1103 return undefined;
1104 }
1105 });
1106 }
1107 openConfirmModal(data) {
1108 return sweetalert2__WEBPACK_IMPORTED_MODULE_0___default().fire({
1109 icon: 'warning',
1110 title: data.confirmTitle,
1111 text: data.confirmText,
1112 showCancelButton: true,
1113 confirmButtonText: data.confirmButton,
1114 cancelButtonText: data.cancelButton
1115 });
1116 }
1117 sendRefundRequest(actionLink, data, reason = '') {
1118 const ajaxHandle = this.getAjaxHandle();
1119 if (!ajaxHandle) {
1120 _lpToastify__WEBPACK_IMPORTED_MODULE_1__.show('Refund action is unavailable right now.', 'error');
1121 return;
1122 }
1123 if (!data.orderId) {
1124 _lpToastify__WEBPACK_IMPORTED_MODULE_1__.show('Invalid order.', 'error');
1125 return;
1126 }
1127 this.isRequesting = true;
1128 this.setActionLoadingState(actionLink, true);
1129 const dataSend = {
1130 action: 'request_refund_order',
1131 order_id: data.orderId,
1132 reason
1133 };
1134 ajaxHandle.fetchAJAX(dataSend, {
1135 success: response => {
1136 const {
1137 status,
1138 message,
1139 data
1140 } = response;
1141 if (status !== 'success') {
1142 throw new Error(message);
1143 }
1144 _lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, 'success');
1145 setTimeout(() => {
1146 window.location.reload();
1147 }, 1200);
1148 },
1149 error: error => {
1150 const message = error?.message || error || 'Refund request failed.';
1151 _lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, 'error');
1152 },
1153 completed: () => {
1154 this.isRequesting = false;
1155 this.setActionLoadingState(actionLink, false);
1156 }
1157 });
1158 }
1159 async handleRefundClick(args) {
1160 const {
1161 e,
1162 target
1163 } = args;
1164 e.preventDefault();
1165 const actionLink = target.closest(OrderRefund.selectors.actionRefund);
1166 if (!actionLink) {
1167 return;
1168 }
1169 if (this.isRequesting || actionLink.dataset.refundSubmitting === 'yes' || actionLink.classList.contains('loading')) {
1170 return;
1171 }
1172 const actionData = this.getActionData(actionLink);
1173 let reason = '';
1174 if (actionData.requireReason) {
1175 const reasonResult = await this.openReasonModal(actionData);
1176 if (!reasonResult.isConfirmed) {
1177 return;
1178 }
1179 reason = (reasonResult.value || '').trim();
1180 }
1181 const confirmResult = await this.openConfirmModal(actionData);
1182 if (!confirmResult.isConfirmed) {
1183 return;
1184 }
1185 this.sendRefundRequest(actionLink, actionData, reason);
1186 }
1187 }
1188 const orderRefund = () => {
1189 const orderRefundHandle = new OrderRefund();
1190 _utils_js__WEBPACK_IMPORTED_MODULE_2__.lpOnElementReady(OrderRefund.selectors.actionRefund, () => {
1191 orderRefundHandle.init();
1192 });
1193 };
1194 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (orderRefund);
1195
1196 /***/ },
1197
1198 /***/ "./assets/src/js/frontend/profile/quiz.js"
1199 /*!************************************************!*\
1200 !*** ./assets/src/js/frontend/profile/quiz.js ***!
1201 \************************************************/
1202 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1203
1204 "use strict";
1205 __webpack_require__.r(__webpack_exports__);
1206 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1207 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
1208 /* harmony export */ });
1209 /**
1210 * Handle click tab call API
1211 *
1212 * @since 4.2.8.2
1213 * @version 1.0.0
1214 */
1215 const profileQuizTab = () => {
1216 const handleClickTab = (e, target) => {
1217 if (target.closest('span')) {
1218 const elParent = target.closest('#profile-content-quizzes');
1219 if (!elParent) {
1220 return;
1221 }
1222 const elLPTarget = target.closest('.lp-target');
1223 if (!elLPTarget) {
1224 return;
1225 }
1226 window.lpAJAXG.showHideLoading(elLPTarget, 1);
1227 const dataSendJson = elLPTarget?.dataset?.send || {};
1228 const dataSend = JSON.parse(dataSendJson);
1229 const elTabChoice = target?.dataset?.filter || 'all';
1230 const liActive = elParent.querySelector('li.active');
1231 if (liActive.classList.contains(elTabChoice)) {
1232 return;
1233 }
1234 liActive.classList.remove('active');
1235 const liTarget = target.closest('li');
1236 liTarget.classList.add('active');
1237 dataSend.args.type = elTabChoice;
1238
1239 // Load list courses by AJAX.
1240 const callBack = {
1241 success: response => {
1242 const {
1243 data,
1244 message,
1245 status
1246 } = response;
1247 if ('success' === status) {
1248 elLPTarget.innerHTML = data.content || '';
1249 }
1250 },
1251 error: error => {
1252 console.log(error);
1253 },
1254 completed: () => {
1255 window.lpAJAXG.showHideLoading(elLPTarget, 0);
1256 }
1257 };
1258 window.lpAJAXG.fetchAJAX(dataSend, callBack);
1259 }
1260 };
1261 document.addEventListener('click', e => {
1262 const target = e.target;
1263 handleClickTab(e, target);
1264 });
1265 };
1266 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (profileQuizTab);
1267
1268 /***/ },
1269
1270 /***/ "./assets/src/js/frontend/profile/statistic.js"
1271 /*!*****************************************************!*\
1272 !*** ./assets/src/js/frontend/profile/statistic.js ***!
1273 \*****************************************************/
1274 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1275
1276 "use strict";
1277 __webpack_require__.r(__webpack_exports__);
1278 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1279 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
1280 /* harmony export */ });
1281 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils.js */ "./assets/src/js/utils.js");
1282
1283
1284 // Rest API load content course progress - Nhamdv.
1285 const courseStatistics = () => {
1286 const loadAPICourseStatistic = elCourseStatistic => {
1287 let apiUrl = 'lp/v1/profile/student/statistic';
1288 const tabActive = document.querySelector('.lp-profile-nav-tabs li.active');
1289 if (!tabActive) {
1290 return;
1291 }
1292 if (tabActive.classList.contains('courses')) {
1293 apiUrl = 'lp/v1/profile/instructor/statistic';
1294 }
1295 const elArgStatistic = elCourseStatistic.querySelector('[name="args_query_user_courses_statistic"]');
1296 if (!elArgStatistic) {
1297 return;
1298 }
1299 const data = JSON.parse(elArgStatistic.value);
1300 const callBack = {
1301 success: response => {
1302 if (response.status === 'success' && response.data) {
1303 elCourseStatistic.innerHTML = response.data;
1304 } else {
1305 elCourseStatistic.innerHTML = `<div class="lp-ajax-message error" style="display:block">${response.message && response.message}</div>`;
1306 }
1307 },
1308 error: error => {
1309 console.log(error);
1310 },
1311 completed: () => {}
1312 };
1313 apiUrl = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpAddQueryArgs)(lpData.lp_rest_url + apiUrl, data);
1314 if (0 !== parseInt(lpData.user_id)) {
1315 data.headers = {
1316 'X-WP-Nonce': lpData.nonce
1317 };
1318 }
1319 (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpFetchAPI)(apiUrl, data, callBack);
1320 };
1321 (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpOnElementReady)('.learn-press-profile-course__statistic', elCourseStatistic => {
1322 loadAPICourseStatistic(elCourseStatistic);
1323 });
1324 };
1325 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (courseStatistics);
1326
1327 /***/ },
1328
1329 /***/ "./assets/src/js/lpToastify.js"
1330 /*!*************************************!*\
1331 !*** ./assets/src/js/lpToastify.js ***!
1332 \*************************************/
1333 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1334
1335 "use strict";
1336 __webpack_require__.r(__webpack_exports__);
1337 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1338 /* harmony export */ show: () => (/* binding */ show)
1339 /* harmony export */ });
1340 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! toastify-js */ "./node_modules/toastify-js/src/toastify.js");
1341 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(toastify_js__WEBPACK_IMPORTED_MODULE_0__);
1342 /* harmony import */ var toastify_js_src_toastify_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! toastify-js/src/toastify.css */ "./node_modules/toastify-js/src/toastify.css");
1343 /**
1344 * Utils functions
1345 *
1346 * @param url
1347 * @param data
1348 * @param functions
1349 * @since 4.3.0
1350 * @version 1.0.0
1351 */
1352
1353
1354 const argsToastify = {
1355 text: '',
1356 gravity: lpData.toast.gravity,
1357 // `top` or `bottom`
1358 position: lpData.toast.position,
1359 // `left`, `center` or `right`
1360 className: `${lpData.toast.classPrefix}`,
1361 close: lpData.toast.close == 1,
1362 stopOnFocus: lpData.toast.stopOnFocus == 1,
1363 duration: lpData.toast.duration
1364 };
1365 const show = (message, status = 'success', argsCustom) => {
1366 let args = argsToastify;
1367 if (argsCustom) {
1368 args = {
1369 ...args,
1370 ...argsCustom
1371 };
1372 }
1373 const toastify = new (toastify_js__WEBPACK_IMPORTED_MODULE_0___default())({
1374 ...args,
1375 text: message,
1376 className: `${lpData.toast.classPrefix} ${status}`
1377 });
1378 toastify.showToast();
1379 };
1380
1381 /***/ },
1382
1383 /***/ "./assets/src/js/utils.js"
1384 /*!********************************!*\
1385 !*** ./assets/src/js/utils.js ***!
1386 \********************************/
1387 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1388
1389 "use strict";
1390 __webpack_require__.r(__webpack_exports__);
1391 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1392 /* harmony export */ debounce: () => (/* binding */ debounce),
1393 /* harmony export */ eventHandlers: () => (/* binding */ eventHandlers),
1394 /* harmony export */ getDataOfForm: () => (/* binding */ getDataOfForm),
1395 /* harmony export */ getFieldKeysOfForm: () => (/* binding */ getFieldKeysOfForm),
1396 /* harmony export */ listenElementCreated: () => (/* binding */ listenElementCreated),
1397 /* harmony export */ listenElementViewed: () => (/* binding */ listenElementViewed),
1398 /* harmony export */ lpAddQueryArgs: () => (/* binding */ lpAddQueryArgs),
1399 /* harmony export */ lpAjaxParseJsonOld: () => (/* binding */ lpAjaxParseJsonOld),
1400 /* harmony export */ lpClassName: () => (/* binding */ lpClassName),
1401 /* harmony export */ lpFetchAPI: () => (/* binding */ lpFetchAPI),
1402 /* harmony export */ lpGetCurrentURLNoParam: () => (/* binding */ lpGetCurrentURLNoParam),
1403 /* harmony export */ lpOnElementReady: () => (/* binding */ lpOnElementReady),
1404 /* harmony export */ lpSetLoadingEl: () => (/* binding */ lpSetLoadingEl),
1405 /* harmony export */ lpShowHideEl: () => (/* binding */ lpShowHideEl),
1406 /* harmony export */ mergeDataWithDatForm: () => (/* binding */ mergeDataWithDatForm),
1407 /* harmony export */ toggleCollapse: () => (/* binding */ toggleCollapse)
1408 /* harmony export */ });
1409 /**
1410 * Utils functions
1411 *
1412 * @param url
1413 * @param data
1414 * @param functions
1415 * @since 4.2.5.1
1416 * @version 1.0.6
1417 */
1418 const lpClassName = {
1419 hidden: 'lp-hidden',
1420 loading: 'loading',
1421 elCollapse: 'lp-collapse',
1422 elSectionToggle: '.lp-section-toggle',
1423 elTriggerToggle: '.lp-trigger-toggle'
1424 };
1425 const lpFetchAPI = (url, data = {}, functions = {}) => {
1426 if ('function' === typeof functions.before) {
1427 functions.before();
1428 }
1429 fetch(url, {
1430 method: 'GET',
1431 ...data
1432 }).then(response => response.json()).then(response => {
1433 if ('function' === typeof functions.success) {
1434 functions.success(response);
1435 }
1436 }).catch(err => {
1437 if ('function' === typeof functions.error) {
1438 functions.error(err);
1439 }
1440 }).finally(() => {
1441 if ('function' === typeof functions.completed) {
1442 functions.completed();
1443 }
1444 });
1445 };
1446
1447 /**
1448 * Get current URL without params.
1449 *
1450 * @since 4.2.5.1
1451 */
1452 const lpGetCurrentURLNoParam = () => {
1453 let currentUrl = window.location.href;
1454 const hasParams = currentUrl.includes('?');
1455 if (hasParams) {
1456 currentUrl = currentUrl.split('?')[0];
1457 }
1458 return currentUrl;
1459 };
1460 const lpAddQueryArgs = (endpoint, args) => {
1461 const url = new URL(endpoint);
1462 Object.keys(args).forEach(arg => {
1463 url.searchParams.set(arg, args[arg]);
1464 });
1465 return url;
1466 };
1467
1468 /**
1469 * Listen element viewed.
1470 *
1471 * @param el
1472 * @param callback
1473 * @since 4.2.5.8
1474 */
1475 const listenElementViewed = (el, callback) => {
1476 const observerSeeItem = new IntersectionObserver(function (entries) {
1477 for (const entry of entries) {
1478 if (entry.isIntersecting) {
1479 callback(entry);
1480 }
1481 }
1482 });
1483 observerSeeItem.observe(el);
1484 };
1485
1486 /**
1487 * Listen element created.
1488 *
1489 * @param callback
1490 * @since 4.2.5.8
1491 */
1492 const listenElementCreated = callback => {
1493 const observerCreateItem = new MutationObserver(function (mutations) {
1494 mutations.forEach(function (mutation) {
1495 if (mutation.addedNodes) {
1496 mutation.addedNodes.forEach(function (node) {
1497 if (node.nodeType === 1) {
1498 callback(node);
1499 }
1500 });
1501 }
1502 });
1503 });
1504 observerCreateItem.observe(document, {
1505 childList: true,
1506 subtree: true
1507 });
1508 // End.
1509 };
1510
1511 /**
1512 * Listen element created.
1513 *
1514 * @param selector
1515 * @param callback
1516 * @since 4.2.7.1
1517 */
1518 const lpOnElementReady = (selector, callback) => {
1519 const element = document.querySelector(selector);
1520 if (element) {
1521 callback(element);
1522 return;
1523 }
1524 const observer = new MutationObserver((mutations, obs) => {
1525 const element = document.querySelector(selector);
1526 if (element) {
1527 obs.disconnect();
1528 callback(element);
1529 }
1530 });
1531 observer.observe(document.documentElement, {
1532 childList: true,
1533 subtree: true
1534 });
1535 };
1536
1537 // Parse JSON from string with content include LP_AJAX_START.
1538 const lpAjaxParseJsonOld = data => {
1539 if (typeof data !== 'string') {
1540 return data;
1541 }
1542 const m = String.raw({
1543 raw: data
1544 }).match(/<-- LP_AJAX_START -->(.*)<-- LP_AJAX_END -->/s);
1545 try {
1546 if (m) {
1547 data = JSON.parse(m[1].replace(/(?:\r\n|\r|\n)/g, ''));
1548 } else {
1549 data = JSON.parse(data);
1550 }
1551 } catch (e) {
1552 data = {};
1553 }
1554 return data;
1555 };
1556
1557 // status 0: hide, 1: show
1558 const lpShowHideEl = (el, status = 0) => {
1559 if (!el) {
1560 return;
1561 }
1562 if (!status) {
1563 el.classList.add(lpClassName.hidden);
1564 } else {
1565 el.classList.remove(lpClassName.hidden);
1566 }
1567 };
1568
1569 // status 0: hide, 1: show
1570 const lpSetLoadingEl = (el, status) => {
1571 if (!el) {
1572 return;
1573 }
1574 if (!status) {
1575 el.classList.remove(lpClassName.loading);
1576 } else {
1577 el.classList.add(lpClassName.loading);
1578 }
1579 };
1580
1581 // Toggle collapse section
1582 const toggleCollapse = (e, target, elTriggerClassName = '', elsExclude = [], callback) => {
1583 if (!elTriggerClassName) {
1584 elTriggerClassName = lpClassName.elTriggerToggle;
1585 }
1586
1587 // Exclude elements, which should not trigger the collapse toggle
1588 if (elsExclude && elsExclude.length > 0) {
1589 for (const elExclude of elsExclude) {
1590 if (target.closest(elExclude)) {
1591 return;
1592 }
1593 }
1594 }
1595 const elTrigger = target.closest(elTriggerClassName);
1596 if (!elTrigger) {
1597 return;
1598 }
1599
1600 //console.log( 'elTrigger', elTrigger );
1601
1602 const elSectionToggle = elTrigger.closest(`${lpClassName.elSectionToggle}`);
1603 if (!elSectionToggle) {
1604 return;
1605 }
1606 elSectionToggle.classList.toggle(`${lpClassName.elCollapse}`);
1607 if ('function' === typeof callback) {
1608 callback(elSectionToggle);
1609 }
1610 };
1611
1612 // Get data of form
1613 const getDataOfForm = form => {
1614 const dataSend = {};
1615 const formData = new FormData(form);
1616 for (const pair of formData.entries()) {
1617 const key = pair[0];
1618 const value = formData.getAll(key);
1619 if (!dataSend.hasOwnProperty(key)) {
1620 // Convert value array to string.
1621 dataSend[key] = value.join(',');
1622 }
1623 }
1624 return dataSend;
1625 };
1626
1627 // Get field keys of form
1628 const getFieldKeysOfForm = form => {
1629 const keys = [];
1630 const elements = form.elements;
1631 for (let i = 0; i < elements.length; i++) {
1632 const name = elements[i].name;
1633 if (name && !keys.includes(name)) {
1634 keys.push(name);
1635 }
1636 }
1637 return keys;
1638 };
1639
1640 // Merge data handle with data form.
1641 const mergeDataWithDatForm = (elForm, dataHandle) => {
1642 const dataForm = getDataOfForm(elForm);
1643 const keys = getFieldKeysOfForm(elForm);
1644 keys.forEach(key => {
1645 if (!dataForm.hasOwnProperty(key)) {
1646 delete dataHandle[key];
1647 } else if (dataForm[key][0] === '') {
1648 delete dataForm[key];
1649 delete dataHandle[key];
1650 }
1651 });
1652 dataHandle = {
1653 ...dataHandle,
1654 ...dataForm
1655 };
1656 return dataHandle;
1657 };
1658
1659 /**
1660 * Event trigger
1661 * For each list of event handlers, listen event on document.
1662 *
1663 * eventName: 'click', 'change', ...
1664 * eventHandlers = [ { selector: '.lp-button', callBack: function(){}, class: object } ]
1665 *
1666 * @param eventName
1667 * @param eventHandlers
1668 */
1669 const eventHandlers = (eventName, eventHandlers) => {
1670 document.addEventListener(eventName, e => {
1671 const target = e.target;
1672 let args = {
1673 e,
1674 target
1675 };
1676 eventHandlers.forEach(eventHandler => {
1677 args = {
1678 ...args,
1679 ...eventHandler
1680 };
1681
1682 //console.log( args );
1683
1684 // Check condition before call back
1685 if (eventHandler.conditionBeforeCallBack) {
1686 if (eventHandler.conditionBeforeCallBack(args) !== true) {
1687 return;
1688 }
1689 }
1690
1691 // Special check for keydown event with checkIsEventEnter = true
1692 if (eventName === 'keydown' && eventHandler.checkIsEventEnter) {
1693 if (e.key !== 'Enter') {
1694 return;
1695 }
1696 }
1697 if (target.closest(eventHandler.selector)) {
1698 if (eventHandler.class) {
1699 // Call method of class, function callBack will understand exactly {this} is class object.
1700 eventHandler.class[eventHandler.callBack](args);
1701 } else {
1702 // For send args is objected, {this} is eventHandler object, not class object.
1703 eventHandler.callBack(args);
1704 }
1705 }
1706 });
1707 });
1708 };
1709
1710 /**
1711 * Debounce - delays function execution until after `wait` ms of inactivity.
1712 *
1713 * Each call resets the timer. Only the last call in a burst executes.
1714 *
1715 * USE CASES:
1716 * - Search inputs, form validation, window resize
1717 * - Multiple elements need independent timers
1718 * - When you need to call with different arguments
1719 *
1720 * EXAMPLES:
1721 * const debouncedSearch = debounce( (query) => fetchResults(query), 300 );
1722 * searchInput.addEventListener('input', (e) => debouncedSearch(e.target.value));
1723 *
1724 * const debouncedResize = debounce( recalculateLayout, 250 );
1725 * window.addEventListener('resize', debouncedResize);
1726 *
1727 * ⚠️ Create ONCE outside event handlers, not inside.
1728 *
1729 * @param {Function} func - Function to debounce (can be anonymous)
1730 * @param {number} wait - Milliseconds to wait (default: 500)
1731 * @return {Function} Debounced wrapper function
1732 * @since 4.3.7
1733 * @version 1.0.0
1734 */
1735 const debounce = (func, wait = 500) => {
1736 let timer;
1737 return args => {
1738 clearTimeout(timer);
1739 timer = setTimeout(() => func(args), wait);
1740 };
1741 };
1742
1743 /***/ },
1744
1745 /***/ "./node_modules/cropperjs/dist/cropper.js"
1746 /*!************************************************!*\
1747 !*** ./node_modules/cropperjs/dist/cropper.js ***!
1748 \************************************************/
1749 (module) {
1750
1751 /*!
1752 * Cropper.js v1.6.2
1753 * https://fengyuanchen.github.io/cropperjs
1754 *
1755 * Copyright 2015-present Chen Fengyuan
1756 * Released under the MIT license
1757 *
1758 * Date: 2024-04-21T07:43:05.335Z
1759 */
1760
1761 (function (global, factory) {
1762 true ? module.exports = factory() :
1763 0;
1764 })(this, (function () { 'use strict';
1765
1766 function ownKeys(e, r) {
1767 var t = Object.keys(e);
1768 if (Object.getOwnPropertySymbols) {
1769 var o = Object.getOwnPropertySymbols(e);
1770 r && (o = o.filter(function (r) {
1771 return Object.getOwnPropertyDescriptor(e, r).enumerable;
1772 })), t.push.apply(t, o);
1773 }
1774 return t;
1775 }
1776 function _objectSpread2(e) {
1777 for (var r = 1; r < arguments.length; r++) {
1778 var t = null != arguments[r] ? arguments[r] : {};
1779 r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
1780 _defineProperty(e, r, t[r]);
1781 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
1782 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
1783 });
1784 }
1785 return e;
1786 }
1787 function _toPrimitive(t, r) {
1788 if ("object" != typeof t || !t) return t;
1789 var e = t[Symbol.toPrimitive];
1790 if (void 0 !== e) {
1791 var i = e.call(t, r || "default");
1792 if ("object" != typeof i) return i;
1793 throw new TypeError("@@toPrimitive must return a primitive value.");
1794 }
1795 return ("string" === r ? String : Number)(t);
1796 }
1797 function _toPropertyKey(t) {
1798 var i = _toPrimitive(t, "string");
1799 return "symbol" == typeof i ? i : i + "";
1800 }
1801 function _typeof(o) {
1802 "@babel/helpers - typeof";
1803
1804 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
1805 return typeof o;
1806 } : function (o) {
1807 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
1808 }, _typeof(o);
1809 }
1810 function _classCallCheck(instance, Constructor) {
1811 if (!(instance instanceof Constructor)) {
1812 throw new TypeError("Cannot call a class as a function");
1813 }
1814 }
1815 function _defineProperties(target, props) {
1816 for (var i = 0; i < props.length; i++) {
1817 var descriptor = props[i];
1818 descriptor.enumerable = descriptor.enumerable || false;
1819 descriptor.configurable = true;
1820 if ("value" in descriptor) descriptor.writable = true;
1821 Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
1822 }
1823 }
1824 function _createClass(Constructor, protoProps, staticProps) {
1825 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1826 if (staticProps) _defineProperties(Constructor, staticProps);
1827 Object.defineProperty(Constructor, "prototype", {
1828 writable: false
1829 });
1830 return Constructor;
1831 }
1832 function _defineProperty(obj, key, value) {
1833 key = _toPropertyKey(key);
1834 if (key in obj) {
1835 Object.defineProperty(obj, key, {
1836 value: value,
1837 enumerable: true,
1838 configurable: true,
1839 writable: true
1840 });
1841 } else {
1842 obj[key] = value;
1843 }
1844 return obj;
1845 }
1846 function _toConsumableArray(arr) {
1847 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
1848 }
1849 function _arrayWithoutHoles(arr) {
1850 if (Array.isArray(arr)) return _arrayLikeToArray(arr);
1851 }
1852 function _iterableToArray(iter) {
1853 if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1854 }
1855 function _unsupportedIterableToArray(o, minLen) {
1856 if (!o) return;
1857 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
1858 var n = Object.prototype.toString.call(o).slice(8, -1);
1859 if (n === "Object" && o.constructor) n = o.constructor.name;
1860 if (n === "Map" || n === "Set") return Array.from(o);
1861 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
1862 }
1863 function _arrayLikeToArray(arr, len) {
1864 if (len == null || len > arr.length) len = arr.length;
1865 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
1866 return arr2;
1867 }
1868 function _nonIterableSpread() {
1869 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1870 }
1871
1872 var IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined';
1873 var WINDOW = IS_BROWSER ? window : {};
1874 var IS_TOUCH_DEVICE = IS_BROWSER && WINDOW.document.documentElement ? 'ontouchstart' in WINDOW.document.documentElement : false;
1875 var HAS_POINTER_EVENT = IS_BROWSER ? 'PointerEvent' in WINDOW : false;
1876 var NAMESPACE = 'cropper';
1877
1878 // Actions
1879 var ACTION_ALL = 'all';
1880 var ACTION_CROP = 'crop';
1881 var ACTION_MOVE = 'move';
1882 var ACTION_ZOOM = 'zoom';
1883 var ACTION_EAST = 'e';
1884 var ACTION_WEST = 'w';
1885 var ACTION_SOUTH = 's';
1886 var ACTION_NORTH = 'n';
1887 var ACTION_NORTH_EAST = 'ne';
1888 var ACTION_NORTH_WEST = 'nw';
1889 var ACTION_SOUTH_EAST = 'se';
1890 var ACTION_SOUTH_WEST = 'sw';
1891
1892 // Classes
1893 var CLASS_CROP = "".concat(NAMESPACE, "-crop");
1894 var CLASS_DISABLED = "".concat(NAMESPACE, "-disabled");
1895 var CLASS_HIDDEN = "".concat(NAMESPACE, "-hidden");
1896 var CLASS_HIDE = "".concat(NAMESPACE, "-hide");
1897 var CLASS_INVISIBLE = "".concat(NAMESPACE, "-invisible");
1898 var CLASS_MODAL = "".concat(NAMESPACE, "-modal");
1899 var CLASS_MOVE = "".concat(NAMESPACE, "-move");
1900
1901 // Data keys
1902 var DATA_ACTION = "".concat(NAMESPACE, "Action");
1903 var DATA_PREVIEW = "".concat(NAMESPACE, "Preview");
1904
1905 // Drag modes
1906 var DRAG_MODE_CROP = 'crop';
1907 var DRAG_MODE_MOVE = 'move';
1908 var DRAG_MODE_NONE = 'none';
1909
1910 // Events
1911 var EVENT_CROP = 'crop';
1912 var EVENT_CROP_END = 'cropend';
1913 var EVENT_CROP_MOVE = 'cropmove';
1914 var EVENT_CROP_START = 'cropstart';
1915 var EVENT_DBLCLICK = 'dblclick';
1916 var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? 'touchstart' : 'mousedown';
1917 var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? 'touchmove' : 'mousemove';
1918 var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? 'touchend touchcancel' : 'mouseup';
1919 var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? 'pointerdown' : EVENT_TOUCH_START;
1920 var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? 'pointermove' : EVENT_TOUCH_MOVE;
1921 var EVENT_POINTER_UP = HAS_POINTER_EVENT ? 'pointerup pointercancel' : EVENT_TOUCH_END;
1922 var EVENT_READY = 'ready';
1923 var EVENT_RESIZE = 'resize';
1924 var EVENT_WHEEL = 'wheel';
1925 var EVENT_ZOOM = 'zoom';
1926
1927 // Mime types
1928 var MIME_TYPE_JPEG = 'image/jpeg';
1929
1930 // RegExps
1931 var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/;
1932 var REGEXP_DATA_URL = /^data:/;
1933 var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg;base64,/;
1934 var REGEXP_TAG_NAME = /^img|canvas$/i;
1935
1936 // Misc
1937 // Inspired by the default width and height of a canvas element.
1938 var MIN_CONTAINER_WIDTH = 200;
1939 var MIN_CONTAINER_HEIGHT = 100;
1940
1941 var DEFAULTS = {
1942 // Define the view mode of the cropper
1943 viewMode: 0,
1944 // 0, 1, 2, 3
1945
1946 // Define the dragging mode of the cropper
1947 dragMode: DRAG_MODE_CROP,
1948 // 'crop', 'move' or 'none'
1949
1950 // Define the initial aspect ratio of the crop box
1951 initialAspectRatio: NaN,
1952 // Define the aspect ratio of the crop box
1953 aspectRatio: NaN,
1954 // An object with the previous cropping result data
1955 data: null,
1956 // A selector for adding extra containers to preview
1957 preview: '',
1958 // Re-render the cropper when resize the window
1959 responsive: true,
1960 // Restore the cropped area after resize the window
1961 restore: true,
1962 // Check if the current image is a cross-origin image
1963 checkCrossOrigin: true,
1964 // Check the current image's Exif Orientation information
1965 checkOrientation: true,
1966 // Show the black modal
1967 modal: true,
1968 // Show the dashed lines for guiding
1969 guides: true,
1970 // Show the center indicator for guiding
1971 center: true,
1972 // Show the white modal to highlight the crop box
1973 highlight: true,
1974 // Show the grid background
1975 background: true,
1976 // Enable to crop the image automatically when initialize
1977 autoCrop: true,
1978 // Define the percentage of automatic cropping area when initializes
1979 autoCropArea: 0.8,
1980 // Enable to move the image
1981 movable: true,
1982 // Enable to rotate the image
1983 rotatable: true,
1984 // Enable to scale the image
1985 scalable: true,
1986 // Enable to zoom the image
1987 zoomable: true,
1988 // Enable to zoom the image by dragging touch
1989 zoomOnTouch: true,
1990 // Enable to zoom the image by wheeling mouse
1991 zoomOnWheel: true,
1992 // Define zoom ratio when zoom the image by wheeling mouse
1993 wheelZoomRatio: 0.1,
1994 // Enable to move the crop box
1995 cropBoxMovable: true,
1996 // Enable to resize the crop box
1997 cropBoxResizable: true,
1998 // Toggle drag mode between "crop" and "move" when click twice on the cropper
1999 toggleDragModeOnDblclick: true,
2000 // Size limitation
2001 minCanvasWidth: 0,
2002 minCanvasHeight: 0,
2003 minCropBoxWidth: 0,
2004 minCropBoxHeight: 0,
2005 minContainerWidth: MIN_CONTAINER_WIDTH,
2006 minContainerHeight: MIN_CONTAINER_HEIGHT,
2007 // Shortcuts of events
2008 ready: null,
2009 cropstart: null,
2010 cropmove: null,
2011 cropend: null,
2012 crop: null,
2013 zoom: null
2014 };
2015
2016 var TEMPLATE = '<div class="cropper-container" touch-action="none">' + '<div class="cropper-wrap-box">' + '<div class="cropper-canvas"></div>' + '</div>' + '<div class="cropper-drag-box"></div>' + '<div class="cropper-crop-box">' + '<span class="cropper-view-box"></span>' + '<span class="cropper-dashed dashed-h"></span>' + '<span class="cropper-dashed dashed-v"></span>' + '<span class="cropper-center"></span>' + '<span class="cropper-face"></span>' + '<span class="cropper-line line-e" data-cropper-action="e"></span>' + '<span class="cropper-line line-n" data-cropper-action="n"></span>' + '<span class="cropper-line line-w" data-cropper-action="w"></span>' + '<span class="cropper-line line-s" data-cropper-action="s"></span>' + '<span class="cropper-point point-e" data-cropper-action="e"></span>' + '<span class="cropper-point point-n" data-cropper-action="n"></span>' + '<span class="cropper-point point-w" data-cropper-action="w"></span>' + '<span class="cropper-point point-s" data-cropper-action="s"></span>' + '<span class="cropper-point point-ne" data-cropper-action="ne"></span>' + '<span class="cropper-point point-nw" data-cropper-action="nw"></span>' + '<span class="cropper-point point-sw" data-cropper-action="sw"></span>' + '<span class="cropper-point point-se" data-cropper-action="se"></span>' + '</div>' + '</div>';
2017
2018 /**
2019 * Check if the given value is not a number.
2020 */
2021 var isNaN = Number.isNaN || WINDOW.isNaN;
2022
2023 /**
2024 * Check if the given value is a number.
2025 * @param {*} value - The value to check.
2026 * @returns {boolean} Returns `true` if the given value is a number, else `false`.
2027 */
2028 function isNumber(value) {
2029 return typeof value === 'number' && !isNaN(value);
2030 }
2031
2032 /**
2033 * Check if the given value is a positive number.
2034 * @param {*} value - The value to check.
2035 * @returns {boolean} Returns `true` if the given value is a positive number, else `false`.
2036 */
2037 var isPositiveNumber = function isPositiveNumber(value) {
2038 return value > 0 && value < Infinity;
2039 };
2040
2041 /**
2042 * Check if the given value is undefined.
2043 * @param {*} value - The value to check.
2044 * @returns {boolean} Returns `true` if the given value is undefined, else `false`.
2045 */
2046 function isUndefined(value) {
2047 return typeof value === 'undefined';
2048 }
2049
2050 /**
2051 * Check if the given value is an object.
2052 * @param {*} value - The value to check.
2053 * @returns {boolean} Returns `true` if the given value is an object, else `false`.
2054 */
2055 function isObject(value) {
2056 return _typeof(value) === 'object' && value !== null;
2057 }
2058 var hasOwnProperty = Object.prototype.hasOwnProperty;
2059
2060 /**
2061 * Check if the given value is a plain object.
2062 * @param {*} value - The value to check.
2063 * @returns {boolean} Returns `true` if the given value is a plain object, else `false`.
2064 */
2065 function isPlainObject(value) {
2066 if (!isObject(value)) {
2067 return false;
2068 }
2069 try {
2070 var _constructor = value.constructor;
2071 var prototype = _constructor.prototype;
2072 return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');
2073 } catch (error) {
2074 return false;
2075 }
2076 }
2077
2078 /**
2079 * Check if the given value is a function.
2080 * @param {*} value - The value to check.
2081 * @returns {boolean} Returns `true` if the given value is a function, else `false`.
2082 */
2083 function isFunction(value) {
2084 return typeof value === 'function';
2085 }
2086 var slice = Array.prototype.slice;
2087
2088 /**
2089 * Convert array-like or iterable object to an array.
2090 * @param {*} value - The value to convert.
2091 * @returns {Array} Returns a new array.
2092 */
2093 function toArray(value) {
2094 return Array.from ? Array.from(value) : slice.call(value);
2095 }
2096
2097 /**
2098 * Iterate the given data.
2099 * @param {*} data - The data to iterate.
2100 * @param {Function} callback - The process function for each element.
2101 * @returns {*} The original data.
2102 */
2103 function forEach(data, callback) {
2104 if (data && isFunction(callback)) {
2105 if (Array.isArray(data) || isNumber(data.length) /* array-like */) {
2106 toArray(data).forEach(function (value, key) {
2107 callback.call(data, value, key, data);
2108 });
2109 } else if (isObject(data)) {
2110 Object.keys(data).forEach(function (key) {
2111 callback.call(data, data[key], key, data);
2112 });
2113 }
2114 }
2115 return data;
2116 }
2117
2118 /**
2119 * Extend the given object.
2120 * @param {*} target - The target object to extend.
2121 * @param {*} args - The rest objects for merging to the target object.
2122 * @returns {Object} The extended object.
2123 */
2124 var assign = Object.assign || function assign(target) {
2125 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2126 args[_key - 1] = arguments[_key];
2127 }
2128 if (isObject(target) && args.length > 0) {
2129 args.forEach(function (arg) {
2130 if (isObject(arg)) {
2131 Object.keys(arg).forEach(function (key) {
2132 target[key] = arg[key];
2133 });
2134 }
2135 });
2136 }
2137 return target;
2138 };
2139 var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/;
2140
2141 /**
2142 * Normalize decimal number.
2143 * Check out {@link https://0.30000000000000004.com/}
2144 * @param {number} value - The value to normalize.
2145 * @param {number} [times=100000000000] - The times for normalizing.
2146 * @returns {number} Returns the normalized number.
2147 */
2148 function normalizeDecimalNumber(value) {
2149 var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;
2150 return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;
2151 }
2152 var REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/;
2153
2154 /**
2155 * Apply styles to the given element.
2156 * @param {Element} element - The target element.
2157 * @param {Object} styles - The styles for applying.
2158 */
2159 function setStyle(element, styles) {
2160 var style = element.style;
2161 forEach(styles, function (value, property) {
2162 if (REGEXP_SUFFIX.test(property) && isNumber(value)) {
2163 value = "".concat(value, "px");
2164 }
2165 style[property] = value;
2166 });
2167 }
2168
2169 /**
2170 * Check if the given element has a special class.
2171 * @param {Element} element - The element to check.
2172 * @param {string} value - The class to search.
2173 * @returns {boolean} Returns `true` if the special class was found.
2174 */
2175 function hasClass(element, value) {
2176 return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1;
2177 }
2178
2179 /**
2180 * Add classes to the given element.
2181 * @param {Element} element - The target element.
2182 * @param {string} value - The classes to be added.
2183 */
2184 function addClass(element, value) {
2185 if (!value) {
2186 return;
2187 }
2188 if (isNumber(element.length)) {
2189 forEach(element, function (elem) {
2190 addClass(elem, value);
2191 });
2192 return;
2193 }
2194 if (element.classList) {
2195 element.classList.add(value);
2196 return;
2197 }
2198 var className = element.className.trim();
2199 if (!className) {
2200 element.className = value;
2201 } else if (className.indexOf(value) < 0) {
2202 element.className = "".concat(className, " ").concat(value);
2203 }
2204 }
2205
2206 /**
2207 * Remove classes from the given element.
2208 * @param {Element} element - The target element.
2209 * @param {string} value - The classes to be removed.
2210 */
2211 function removeClass(element, value) {
2212 if (!value) {
2213 return;
2214 }
2215 if (isNumber(element.length)) {
2216 forEach(element, function (elem) {
2217 removeClass(elem, value);
2218 });
2219 return;
2220 }
2221 if (element.classList) {
2222 element.classList.remove(value);
2223 return;
2224 }
2225 if (element.className.indexOf(value) >= 0) {
2226 element.className = element.className.replace(value, '');
2227 }
2228 }
2229
2230 /**
2231 * Add or remove classes from the given element.
2232 * @param {Element} element - The target element.
2233 * @param {string} value - The classes to be toggled.
2234 * @param {boolean} added - Add only.
2235 */
2236 function toggleClass(element, value, added) {
2237 if (!value) {
2238 return;
2239 }
2240 if (isNumber(element.length)) {
2241 forEach(element, function (elem) {
2242 toggleClass(elem, value, added);
2243 });
2244 return;
2245 }
2246
2247 // IE10-11 doesn't support the second parameter of `classList.toggle`
2248 if (added) {
2249 addClass(element, value);
2250 } else {
2251 removeClass(element, value);
2252 }
2253 }
2254 var REGEXP_CAMEL_CASE = /([a-z\d])([A-Z])/g;
2255
2256 /**
2257 * Transform the given string from camelCase to kebab-case
2258 * @param {string} value - The value to transform.
2259 * @returns {string} The transformed value.
2260 */
2261 function toParamCase(value) {
2262 return value.replace(REGEXP_CAMEL_CASE, '$1-$2').toLowerCase();
2263 }
2264
2265 /**
2266 * Get data from the given element.
2267 * @param {Element} element - The target element.
2268 * @param {string} name - The data key to get.
2269 * @returns {string} The data value.
2270 */
2271 function getData(element, name) {
2272 if (isObject(element[name])) {
2273 return element[name];
2274 }
2275 if (element.dataset) {
2276 return element.dataset[name];
2277 }
2278 return element.getAttribute("data-".concat(toParamCase(name)));
2279 }
2280
2281 /**
2282 * Set data to the given element.
2283 * @param {Element} element - The target element.
2284 * @param {string} name - The data key to set.
2285 * @param {string} data - The data value.
2286 */
2287 function setData(element, name, data) {
2288 if (isObject(data)) {
2289 element[name] = data;
2290 } else if (element.dataset) {
2291 element.dataset[name] = data;
2292 } else {
2293 element.setAttribute("data-".concat(toParamCase(name)), data);
2294 }
2295 }
2296
2297 /**
2298 * Remove data from the given element.
2299 * @param {Element} element - The target element.
2300 * @param {string} name - The data key to remove.
2301 */
2302 function removeData(element, name) {
2303 if (isObject(element[name])) {
2304 try {
2305 delete element[name];
2306 } catch (error) {
2307 element[name] = undefined;
2308 }
2309 } else if (element.dataset) {
2310 // #128 Safari not allows to delete dataset property
2311 try {
2312 delete element.dataset[name];
2313 } catch (error) {
2314 element.dataset[name] = undefined;
2315 }
2316 } else {
2317 element.removeAttribute("data-".concat(toParamCase(name)));
2318 }
2319 }
2320 var REGEXP_SPACES = /\s\s*/;
2321 var onceSupported = function () {
2322 var supported = false;
2323 if (IS_BROWSER) {
2324 var once = false;
2325 var listener = function listener() {};
2326 var options = Object.defineProperty({}, 'once', {
2327 get: function get() {
2328 supported = true;
2329 return once;
2330 },
2331 /**
2332 * This setter can fix a `TypeError` in strict mode
2333 * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only}
2334 * @param {boolean} value - The value to set
2335 */
2336 set: function set(value) {
2337 once = value;
2338 }
2339 });
2340 WINDOW.addEventListener('test', listener, options);
2341 WINDOW.removeEventListener('test', listener, options);
2342 }
2343 return supported;
2344 }();
2345
2346 /**
2347 * Remove event listener from the target element.
2348 * @param {Element} element - The event target.
2349 * @param {string} type - The event type(s).
2350 * @param {Function} listener - The event listener.
2351 * @param {Object} options - The event options.
2352 */
2353 function removeListener(element, type, listener) {
2354 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2355 var handler = listener;
2356 type.trim().split(REGEXP_SPACES).forEach(function (event) {
2357 if (!onceSupported) {
2358 var listeners = element.listeners;
2359 if (listeners && listeners[event] && listeners[event][listener]) {
2360 handler = listeners[event][listener];
2361 delete listeners[event][listener];
2362 if (Object.keys(listeners[event]).length === 0) {
2363 delete listeners[event];
2364 }
2365 if (Object.keys(listeners).length === 0) {
2366 delete element.listeners;
2367 }
2368 }
2369 }
2370 element.removeEventListener(event, handler, options);
2371 });
2372 }
2373
2374 /**
2375 * Add event listener to the target element.
2376 * @param {Element} element - The event target.
2377 * @param {string} type - The event type(s).
2378 * @param {Function} listener - The event listener.
2379 * @param {Object} options - The event options.
2380 */
2381 function addListener(element, type, listener) {
2382 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2383 var _handler = listener;
2384 type.trim().split(REGEXP_SPACES).forEach(function (event) {
2385 if (options.once && !onceSupported) {
2386 var _element$listeners = element.listeners,
2387 listeners = _element$listeners === void 0 ? {} : _element$listeners;
2388 _handler = function handler() {
2389 delete listeners[event][listener];
2390 element.removeEventListener(event, _handler, options);
2391 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
2392 args[_key2] = arguments[_key2];
2393 }
2394 listener.apply(element, args);
2395 };
2396 if (!listeners[event]) {
2397 listeners[event] = {};
2398 }
2399 if (listeners[event][listener]) {
2400 element.removeEventListener(event, listeners[event][listener], options);
2401 }
2402 listeners[event][listener] = _handler;
2403 element.listeners = listeners;
2404 }
2405 element.addEventListener(event, _handler, options);
2406 });
2407 }
2408
2409 /**
2410 * Dispatch event on the target element.
2411 * @param {Element} element - The event target.
2412 * @param {string} type - The event type(s).
2413 * @param {Object} data - The additional event data.
2414 * @returns {boolean} Indicate if the event is default prevented or not.
2415 */
2416 function dispatchEvent(element, type, data) {
2417 var event;
2418
2419 // Event and CustomEvent on IE9-11 are global objects, not constructors
2420 if (isFunction(Event) && isFunction(CustomEvent)) {
2421 event = new CustomEvent(type, {
2422 detail: data,
2423 bubbles: true,
2424 cancelable: true
2425 });
2426 } else {
2427 event = document.createEvent('CustomEvent');
2428 event.initCustomEvent(type, true, true, data);
2429 }
2430 return element.dispatchEvent(event);
2431 }
2432
2433 /**
2434 * Get the offset base on the document.
2435 * @param {Element} element - The target element.
2436 * @returns {Object} The offset data.
2437 */
2438 function getOffset(element) {
2439 var box = element.getBoundingClientRect();
2440 return {
2441 left: box.left + (window.pageXOffset - document.documentElement.clientLeft),
2442 top: box.top + (window.pageYOffset - document.documentElement.clientTop)
2443 };
2444 }
2445 var location = WINDOW.location;
2446 var REGEXP_ORIGINS = /^(\w+:)\/\/([^:/?#]*):?(\d*)/i;
2447
2448 /**
2449 * Check if the given URL is a cross origin URL.
2450 * @param {string} url - The target URL.
2451 * @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.
2452 */
2453 function isCrossOriginURL(url) {
2454 var parts = url.match(REGEXP_ORIGINS);
2455 return parts !== null && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);
2456 }
2457
2458 /**
2459 * Add timestamp to the given URL.
2460 * @param {string} url - The target URL.
2461 * @returns {string} The result URL.
2462 */
2463 function addTimestamp(url) {
2464 var timestamp = "timestamp=".concat(new Date().getTime());
2465 return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;
2466 }
2467
2468 /**
2469 * Get transforms base on the given object.
2470 * @param {Object} obj - The target object.
2471 * @returns {string} A string contains transform values.
2472 */
2473 function getTransforms(_ref) {
2474 var rotate = _ref.rotate,
2475 scaleX = _ref.scaleX,
2476 scaleY = _ref.scaleY,
2477 translateX = _ref.translateX,
2478 translateY = _ref.translateY;
2479 var values = [];
2480 if (isNumber(translateX) && translateX !== 0) {
2481 values.push("translateX(".concat(translateX, "px)"));
2482 }
2483 if (isNumber(translateY) && translateY !== 0) {
2484 values.push("translateY(".concat(translateY, "px)"));
2485 }
2486
2487 // Rotate should come first before scale to match orientation transform
2488 if (isNumber(rotate) && rotate !== 0) {
2489 values.push("rotate(".concat(rotate, "deg)"));
2490 }
2491 if (isNumber(scaleX) && scaleX !== 1) {
2492 values.push("scaleX(".concat(scaleX, ")"));
2493 }
2494 if (isNumber(scaleY) && scaleY !== 1) {
2495 values.push("scaleY(".concat(scaleY, ")"));
2496 }
2497 var transform = values.length ? values.join(' ') : 'none';
2498 return {
2499 WebkitTransform: transform,
2500 msTransform: transform,
2501 transform: transform
2502 };
2503 }
2504
2505 /**
2506 * Get the max ratio of a group of pointers.
2507 * @param {string} pointers - The target pointers.
2508 * @returns {number} The result ratio.
2509 */
2510 function getMaxZoomRatio(pointers) {
2511 var pointers2 = _objectSpread2({}, pointers);
2512 var maxRatio = 0;
2513 forEach(pointers, function (pointer, pointerId) {
2514 delete pointers2[pointerId];
2515 forEach(pointers2, function (pointer2) {
2516 var x1 = Math.abs(pointer.startX - pointer2.startX);
2517 var y1 = Math.abs(pointer.startY - pointer2.startY);
2518 var x2 = Math.abs(pointer.endX - pointer2.endX);
2519 var y2 = Math.abs(pointer.endY - pointer2.endY);
2520 var z1 = Math.sqrt(x1 * x1 + y1 * y1);
2521 var z2 = Math.sqrt(x2 * x2 + y2 * y2);
2522 var ratio = (z2 - z1) / z1;
2523 if (Math.abs(ratio) > Math.abs(maxRatio)) {
2524 maxRatio = ratio;
2525 }
2526 });
2527 });
2528 return maxRatio;
2529 }
2530
2531 /**
2532 * Get a pointer from an event object.
2533 * @param {Object} event - The target event object.
2534 * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not.
2535 * @returns {Object} The result pointer contains start and/or end point coordinates.
2536 */
2537 function getPointer(_ref2, endOnly) {
2538 var pageX = _ref2.pageX,
2539 pageY = _ref2.pageY;
2540 var end = {
2541 endX: pageX,
2542 endY: pageY
2543 };
2544 return endOnly ? end : _objectSpread2({
2545 startX: pageX,
2546 startY: pageY
2547 }, end);
2548 }
2549
2550 /**
2551 * Get the center point coordinate of a group of pointers.
2552 * @param {Object} pointers - The target pointers.
2553 * @returns {Object} The center point coordinate.
2554 */
2555 function getPointersCenter(pointers) {
2556 var pageX = 0;
2557 var pageY = 0;
2558 var count = 0;
2559 forEach(pointers, function (_ref3) {
2560 var startX = _ref3.startX,
2561 startY = _ref3.startY;
2562 pageX += startX;
2563 pageY += startY;
2564 count += 1;
2565 });
2566 pageX /= count;
2567 pageY /= count;
2568 return {
2569 pageX: pageX,
2570 pageY: pageY
2571 };
2572 }
2573
2574 /**
2575 * Get the max sizes in a rectangle under the given aspect ratio.
2576 * @param {Object} data - The original sizes.
2577 * @param {string} [type='contain'] - The adjust type.
2578 * @returns {Object} The result sizes.
2579 */
2580 function getAdjustedSizes(_ref4) {
2581 var aspectRatio = _ref4.aspectRatio,
2582 height = _ref4.height,
2583 width = _ref4.width;
2584 var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain';
2585 var isValidWidth = isPositiveNumber(width);
2586 var isValidHeight = isPositiveNumber(height);
2587 if (isValidWidth && isValidHeight) {
2588 var adjustedWidth = height * aspectRatio;
2589 if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {
2590 height = width / aspectRatio;
2591 } else {
2592 width = height * aspectRatio;
2593 }
2594 } else if (isValidWidth) {
2595 height = width / aspectRatio;
2596 } else if (isValidHeight) {
2597 width = height * aspectRatio;
2598 }
2599 return {
2600 width: width,
2601 height: height
2602 };
2603 }
2604
2605 /**
2606 * Get the new sizes of a rectangle after rotated.
2607 * @param {Object} data - The original sizes.
2608 * @returns {Object} The result sizes.
2609 */
2610 function getRotatedSizes(_ref5) {
2611 var width = _ref5.width,
2612 height = _ref5.height,
2613 degree = _ref5.degree;
2614 degree = Math.abs(degree) % 180;
2615 if (degree === 90) {
2616 return {
2617 width: height,
2618 height: width
2619 };
2620 }
2621 var arc = degree % 90 * Math.PI / 180;
2622 var sinArc = Math.sin(arc);
2623 var cosArc = Math.cos(arc);
2624 var newWidth = width * cosArc + height * sinArc;
2625 var newHeight = width * sinArc + height * cosArc;
2626 return degree > 90 ? {
2627 width: newHeight,
2628 height: newWidth
2629 } : {
2630 width: newWidth,
2631 height: newHeight
2632 };
2633 }
2634
2635 /**
2636 * Get a canvas which drew the given image.
2637 * @param {HTMLImageElement} image - The image for drawing.
2638 * @param {Object} imageData - The image data.
2639 * @param {Object} canvasData - The canvas data.
2640 * @param {Object} options - The options.
2641 * @returns {HTMLCanvasElement} The result canvas.
2642 */
2643 function getSourceCanvas(image, _ref6, _ref7, _ref8) {
2644 var imageAspectRatio = _ref6.aspectRatio,
2645 imageNaturalWidth = _ref6.naturalWidth,
2646 imageNaturalHeight = _ref6.naturalHeight,
2647 _ref6$rotate = _ref6.rotate,
2648 rotate = _ref6$rotate === void 0 ? 0 : _ref6$rotate,
2649 _ref6$scaleX = _ref6.scaleX,
2650 scaleX = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX,
2651 _ref6$scaleY = _ref6.scaleY,
2652 scaleY = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY;
2653 var aspectRatio = _ref7.aspectRatio,
2654 naturalWidth = _ref7.naturalWidth,
2655 naturalHeight = _ref7.naturalHeight;
2656 var _ref8$fillColor = _ref8.fillColor,
2657 fillColor = _ref8$fillColor === void 0 ? 'transparent' : _ref8$fillColor,
2658 _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled,
2659 imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE,
2660 _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality,
2661 imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? 'low' : _ref8$imageSmoothingQ,
2662 _ref8$maxWidth = _ref8.maxWidth,
2663 maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth,
2664 _ref8$maxHeight = _ref8.maxHeight,
2665 maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight,
2666 _ref8$minWidth = _ref8.minWidth,
2667 minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth,
2668 _ref8$minHeight = _ref8.minHeight,
2669 minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight;
2670 var canvas = document.createElement('canvas');
2671 var context = canvas.getContext('2d');
2672 var maxSizes = getAdjustedSizes({
2673 aspectRatio: aspectRatio,
2674 width: maxWidth,
2675 height: maxHeight
2676 });
2677 var minSizes = getAdjustedSizes({
2678 aspectRatio: aspectRatio,
2679 width: minWidth,
2680 height: minHeight
2681 }, 'cover');
2682 var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth));
2683 var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight));
2684
2685 // Note: should always use image's natural sizes for drawing as
2686 // imageData.naturalWidth === canvasData.naturalHeight when rotate % 180 === 90
2687 var destMaxSizes = getAdjustedSizes({
2688 aspectRatio: imageAspectRatio,
2689 width: maxWidth,
2690 height: maxHeight
2691 });
2692 var destMinSizes = getAdjustedSizes({
2693 aspectRatio: imageAspectRatio,
2694 width: minWidth,
2695 height: minHeight
2696 }, 'cover');
2697 var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth));
2698 var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight));
2699 var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight];
2700 canvas.width = normalizeDecimalNumber(width);
2701 canvas.height = normalizeDecimalNumber(height);
2702 context.fillStyle = fillColor;
2703 context.fillRect(0, 0, width, height);
2704 context.save();
2705 context.translate(width / 2, height / 2);
2706 context.rotate(rotate * Math.PI / 180);
2707 context.scale(scaleX, scaleY);
2708 context.imageSmoothingEnabled = imageSmoothingEnabled;
2709 context.imageSmoothingQuality = imageSmoothingQuality;
2710 context.drawImage.apply(context, [image].concat(_toConsumableArray(params.map(function (param) {
2711 return Math.floor(normalizeDecimalNumber(param));
2712 }))));
2713 context.restore();
2714 return canvas;
2715 }
2716 var fromCharCode = String.fromCharCode;
2717
2718 /**
2719 * Get string from char code in data view.
2720 * @param {DataView} dataView - The data view for read.
2721 * @param {number} start - The start index.
2722 * @param {number} length - The read length.
2723 * @returns {string} The read result.
2724 */
2725 function getStringFromCharCode(dataView, start, length) {
2726 var str = '';
2727 length += start;
2728 for (var i = start; i < length; i += 1) {
2729 str += fromCharCode(dataView.getUint8(i));
2730 }
2731 return str;
2732 }
2733 var REGEXP_DATA_URL_HEAD = /^data:.*,/;
2734
2735 /**
2736 * Transform Data URL to array buffer.
2737 * @param {string} dataURL - The Data URL to transform.
2738 * @returns {ArrayBuffer} The result array buffer.
2739 */
2740 function dataURLToArrayBuffer(dataURL) {
2741 var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');
2742 var binary = atob(base64);
2743 var arrayBuffer = new ArrayBuffer(binary.length);
2744 var uint8 = new Uint8Array(arrayBuffer);
2745 forEach(uint8, function (value, i) {
2746 uint8[i] = binary.charCodeAt(i);
2747 });
2748 return arrayBuffer;
2749 }
2750
2751 /**
2752 * Transform array buffer to Data URL.
2753 * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.
2754 * @param {string} mimeType - The mime type of the Data URL.
2755 * @returns {string} The result Data URL.
2756 */
2757 function arrayBufferToDataURL(arrayBuffer, mimeType) {
2758 var chunks = [];
2759
2760 // Chunk Typed Array for better performance (#435)
2761 var chunkSize = 8192;
2762 var uint8 = new Uint8Array(arrayBuffer);
2763 while (uint8.length > 0) {
2764 // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9
2765 // eslint-disable-next-line prefer-spread
2766 chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));
2767 uint8 = uint8.subarray(chunkSize);
2768 }
2769 return "data:".concat(mimeType, ";base64,").concat(btoa(chunks.join('')));
2770 }
2771
2772 /**
2773 * Get orientation value from given array buffer.
2774 * @param {ArrayBuffer} arrayBuffer - The array buffer to read.
2775 * @returns {number} The read orientation value.
2776 */
2777 function resetAndGetOrientation(arrayBuffer) {
2778 var dataView = new DataView(arrayBuffer);
2779 var orientation;
2780
2781 // Ignores range error when the image does not have correct Exif information
2782 try {
2783 var littleEndian;
2784 var app1Start;
2785 var ifdStart;
2786
2787 // Only handle JPEG image (start by 0xFFD8)
2788 if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {
2789 var length = dataView.byteLength;
2790 var offset = 2;
2791 while (offset + 1 < length) {
2792 if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {
2793 app1Start = offset;
2794 break;
2795 }
2796 offset += 1;
2797 }
2798 }
2799 if (app1Start) {
2800 var exifIDCode = app1Start + 4;
2801 var tiffOffset = app1Start + 10;
2802 if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {
2803 var endianness = dataView.getUint16(tiffOffset);
2804 littleEndian = endianness === 0x4949;
2805 if (littleEndian || endianness === 0x4D4D /* bigEndian */) {
2806 if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {
2807 var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
2808 if (firstIFDOffset >= 0x00000008) {
2809 ifdStart = tiffOffset + firstIFDOffset;
2810 }
2811 }
2812 }
2813 }
2814 }
2815 if (ifdStart) {
2816 var _length = dataView.getUint16(ifdStart, littleEndian);
2817 var _offset;
2818 var i;
2819 for (i = 0; i < _length; i += 1) {
2820 _offset = ifdStart + i * 12 + 2;
2821 if (dataView.getUint16(_offset, littleEndian) === 0x0112 /* Orientation */) {
2822 // 8 is the offset of the current tag's value
2823 _offset += 8;
2824
2825 // Get the original orientation value
2826 orientation = dataView.getUint16(_offset, littleEndian);
2827
2828 // Override the orientation with its default value
2829 dataView.setUint16(_offset, 1, littleEndian);
2830 break;
2831 }
2832 }
2833 }
2834 } catch (error) {
2835 orientation = 1;
2836 }
2837 return orientation;
2838 }
2839
2840 /**
2841 * Parse Exif Orientation value.
2842 * @param {number} orientation - The orientation to parse.
2843 * @returns {Object} The parsed result.
2844 */
2845 function parseOrientation(orientation) {
2846 var rotate = 0;
2847 var scaleX = 1;
2848 var scaleY = 1;
2849 switch (orientation) {
2850 // Flip horizontal
2851 case 2:
2852 scaleX = -1;
2853 break;
2854
2855 // Rotate left 180°
2856 case 3:
2857 rotate = -180;
2858 break;
2859
2860 // Flip vertical
2861 case 4:
2862 scaleY = -1;
2863 break;
2864
2865 // Flip vertical and rotate right 90°
2866 case 5:
2867 rotate = 90;
2868 scaleY = -1;
2869 break;
2870
2871 // Rotate right 90°
2872 case 6:
2873 rotate = 90;
2874 break;
2875
2876 // Flip horizontal and rotate right 90°
2877 case 7:
2878 rotate = 90;
2879 scaleX = -1;
2880 break;
2881
2882 // Rotate left 90°
2883 case 8:
2884 rotate = -90;
2885 break;
2886 }
2887 return {
2888 rotate: rotate,
2889 scaleX: scaleX,
2890 scaleY: scaleY
2891 };
2892 }
2893
2894 var render = {
2895 render: function render() {
2896 this.initContainer();
2897 this.initCanvas();
2898 this.initCropBox();
2899 this.renderCanvas();
2900 if (this.cropped) {
2901 this.renderCropBox();
2902 }
2903 },
2904 initContainer: function initContainer() {
2905 var element = this.element,
2906 options = this.options,
2907 container = this.container,
2908 cropper = this.cropper;
2909 var minWidth = Number(options.minContainerWidth);
2910 var minHeight = Number(options.minContainerHeight);
2911 addClass(cropper, CLASS_HIDDEN);
2912 removeClass(element, CLASS_HIDDEN);
2913 var containerData = {
2914 width: Math.max(container.offsetWidth, minWidth >= 0 ? minWidth : MIN_CONTAINER_WIDTH),
2915 height: Math.max(container.offsetHeight, minHeight >= 0 ? minHeight : MIN_CONTAINER_HEIGHT)
2916 };
2917 this.containerData = containerData;
2918 setStyle(cropper, {
2919 width: containerData.width,
2920 height: containerData.height
2921 });
2922 addClass(element, CLASS_HIDDEN);
2923 removeClass(cropper, CLASS_HIDDEN);
2924 },
2925 // Canvas (image wrapper)
2926 initCanvas: function initCanvas() {
2927 var containerData = this.containerData,
2928 imageData = this.imageData;
2929 var viewMode = this.options.viewMode;
2930 var rotated = Math.abs(imageData.rotate) % 180 === 90;
2931 var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth;
2932 var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight;
2933 var aspectRatio = naturalWidth / naturalHeight;
2934 var canvasWidth = containerData.width;
2935 var canvasHeight = containerData.height;
2936 if (containerData.height * aspectRatio > containerData.width) {
2937 if (viewMode === 3) {
2938 canvasWidth = containerData.height * aspectRatio;
2939 } else {
2940 canvasHeight = containerData.width / aspectRatio;
2941 }
2942 } else if (viewMode === 3) {
2943 canvasHeight = containerData.width / aspectRatio;
2944 } else {
2945 canvasWidth = containerData.height * aspectRatio;
2946 }
2947 var canvasData = {
2948 aspectRatio: aspectRatio,
2949 naturalWidth: naturalWidth,
2950 naturalHeight: naturalHeight,
2951 width: canvasWidth,
2952 height: canvasHeight
2953 };
2954 this.canvasData = canvasData;
2955 this.limited = viewMode === 1 || viewMode === 2;
2956 this.limitCanvas(true, true);
2957 canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);
2958 canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);
2959 canvasData.left = (containerData.width - canvasData.width) / 2;
2960 canvasData.top = (containerData.height - canvasData.height) / 2;
2961 canvasData.oldLeft = canvasData.left;
2962 canvasData.oldTop = canvasData.top;
2963 this.initialCanvasData = assign({}, canvasData);
2964 },
2965 limitCanvas: function limitCanvas(sizeLimited, positionLimited) {
2966 var options = this.options,
2967 containerData = this.containerData,
2968 canvasData = this.canvasData,
2969 cropBoxData = this.cropBoxData;
2970 var viewMode = options.viewMode;
2971 var aspectRatio = canvasData.aspectRatio;
2972 var cropped = this.cropped && cropBoxData;
2973 if (sizeLimited) {
2974 var minCanvasWidth = Number(options.minCanvasWidth) || 0;
2975 var minCanvasHeight = Number(options.minCanvasHeight) || 0;
2976 if (viewMode > 1) {
2977 minCanvasWidth = Math.max(minCanvasWidth, containerData.width);
2978 minCanvasHeight = Math.max(minCanvasHeight, containerData.height);
2979 if (viewMode === 3) {
2980 if (minCanvasHeight * aspectRatio > minCanvasWidth) {
2981 minCanvasWidth = minCanvasHeight * aspectRatio;
2982 } else {
2983 minCanvasHeight = minCanvasWidth / aspectRatio;
2984 }
2985 }
2986 } else if (viewMode > 0) {
2987 if (minCanvasWidth) {
2988 minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0);
2989 } else if (minCanvasHeight) {
2990 minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0);
2991 } else if (cropped) {
2992 minCanvasWidth = cropBoxData.width;
2993 minCanvasHeight = cropBoxData.height;
2994 if (minCanvasHeight * aspectRatio > minCanvasWidth) {
2995 minCanvasWidth = minCanvasHeight * aspectRatio;
2996 } else {
2997 minCanvasHeight = minCanvasWidth / aspectRatio;
2998 }
2999 }
3000 }
3001 var _getAdjustedSizes = getAdjustedSizes({
3002 aspectRatio: aspectRatio,
3003 width: minCanvasWidth,
3004 height: minCanvasHeight
3005 });
3006 minCanvasWidth = _getAdjustedSizes.width;
3007 minCanvasHeight = _getAdjustedSizes.height;
3008 canvasData.minWidth = minCanvasWidth;
3009 canvasData.minHeight = minCanvasHeight;
3010 canvasData.maxWidth = Infinity;
3011 canvasData.maxHeight = Infinity;
3012 }
3013 if (positionLimited) {
3014 if (viewMode > (cropped ? 0 : 1)) {
3015 var newCanvasLeft = containerData.width - canvasData.width;
3016 var newCanvasTop = containerData.height - canvasData.height;
3017 canvasData.minLeft = Math.min(0, newCanvasLeft);
3018 canvasData.minTop = Math.min(0, newCanvasTop);
3019 canvasData.maxLeft = Math.max(0, newCanvasLeft);
3020 canvasData.maxTop = Math.max(0, newCanvasTop);
3021 if (cropped && this.limited) {
3022 canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width));
3023 canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height));
3024 canvasData.maxLeft = cropBoxData.left;
3025 canvasData.maxTop = cropBoxData.top;
3026 if (viewMode === 2) {
3027 if (canvasData.width >= containerData.width) {
3028 canvasData.minLeft = Math.min(0, newCanvasLeft);
3029 canvasData.maxLeft = Math.max(0, newCanvasLeft);
3030 }
3031 if (canvasData.height >= containerData.height) {
3032 canvasData.minTop = Math.min(0, newCanvasTop);
3033 canvasData.maxTop = Math.max(0, newCanvasTop);
3034 }
3035 }
3036 }
3037 } else {
3038 canvasData.minLeft = -canvasData.width;
3039 canvasData.minTop = -canvasData.height;
3040 canvasData.maxLeft = containerData.width;
3041 canvasData.maxTop = containerData.height;
3042 }
3043 }
3044 },
3045 renderCanvas: function renderCanvas(changed, transformed) {
3046 var canvasData = this.canvasData,
3047 imageData = this.imageData;
3048 if (transformed) {
3049 var _getRotatedSizes = getRotatedSizes({
3050 width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1),
3051 height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1),
3052 degree: imageData.rotate || 0
3053 }),
3054 naturalWidth = _getRotatedSizes.width,
3055 naturalHeight = _getRotatedSizes.height;
3056 var width = canvasData.width * (naturalWidth / canvasData.naturalWidth);
3057 var height = canvasData.height * (naturalHeight / canvasData.naturalHeight);
3058 canvasData.left -= (width - canvasData.width) / 2;
3059 canvasData.top -= (height - canvasData.height) / 2;
3060 canvasData.width = width;
3061 canvasData.height = height;
3062 canvasData.aspectRatio = naturalWidth / naturalHeight;
3063 canvasData.naturalWidth = naturalWidth;
3064 canvasData.naturalHeight = naturalHeight;
3065 this.limitCanvas(true, false);
3066 }
3067 if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) {
3068 canvasData.left = canvasData.oldLeft;
3069 }
3070 if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) {
3071 canvasData.top = canvasData.oldTop;
3072 }
3073 canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);
3074 canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);
3075 this.limitCanvas(false, true);
3076 canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft);
3077 canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop);
3078 canvasData.oldLeft = canvasData.left;
3079 canvasData.oldTop = canvasData.top;
3080 setStyle(this.canvas, assign({
3081 width: canvasData.width,
3082 height: canvasData.height
3083 }, getTransforms({
3084 translateX: canvasData.left,
3085 translateY: canvasData.top
3086 })));
3087 this.renderImage(changed);
3088 if (this.cropped && this.limited) {
3089 this.limitCropBox(true, true);
3090 }
3091 },
3092 renderImage: function renderImage(changed) {
3093 var canvasData = this.canvasData,
3094 imageData = this.imageData;
3095 var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth);
3096 var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight);
3097 assign(imageData, {
3098 width: width,
3099 height: height,
3100 left: (canvasData.width - width) / 2,
3101 top: (canvasData.height - height) / 2
3102 });
3103 setStyle(this.image, assign({
3104 width: imageData.width,
3105 height: imageData.height
3106 }, getTransforms(assign({
3107 translateX: imageData.left,
3108 translateY: imageData.top
3109 }, imageData))));
3110 if (changed) {
3111 this.output();
3112 }
3113 },
3114 initCropBox: function initCropBox() {
3115 var options = this.options,
3116 canvasData = this.canvasData;
3117 var aspectRatio = options.aspectRatio || options.initialAspectRatio;
3118 var autoCropArea = Number(options.autoCropArea) || 0.8;
3119 var cropBoxData = {
3120 width: canvasData.width,
3121 height: canvasData.height
3122 };
3123 if (aspectRatio) {
3124 if (canvasData.height * aspectRatio > canvasData.width) {
3125 cropBoxData.height = cropBoxData.width / aspectRatio;
3126 } else {
3127 cropBoxData.width = cropBoxData.height * aspectRatio;
3128 }
3129 }
3130 this.cropBoxData = cropBoxData;
3131 this.limitCropBox(true, true);
3132
3133 // Initialize auto crop area
3134 cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);
3135 cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);
3136
3137 // The width/height of auto crop area must large than "minWidth/Height"
3138 cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea);
3139 cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea);
3140 cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2;
3141 cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2;
3142 cropBoxData.oldLeft = cropBoxData.left;
3143 cropBoxData.oldTop = cropBoxData.top;
3144 this.initialCropBoxData = assign({}, cropBoxData);
3145 },
3146 limitCropBox: function limitCropBox(sizeLimited, positionLimited) {
3147 var options = this.options,
3148 containerData = this.containerData,
3149 canvasData = this.canvasData,
3150 cropBoxData = this.cropBoxData,
3151 limited = this.limited;
3152 var aspectRatio = options.aspectRatio;
3153 if (sizeLimited) {
3154 var minCropBoxWidth = Number(options.minCropBoxWidth) || 0;
3155 var minCropBoxHeight = Number(options.minCropBoxHeight) || 0;
3156 var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width;
3157 var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height;
3158
3159 // The min/maxCropBoxWidth/Height must be less than container's width/height
3160 minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width);
3161 minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height);
3162 if (aspectRatio) {
3163 if (minCropBoxWidth && minCropBoxHeight) {
3164 if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {
3165 minCropBoxHeight = minCropBoxWidth / aspectRatio;
3166 } else {
3167 minCropBoxWidth = minCropBoxHeight * aspectRatio;
3168 }
3169 } else if (minCropBoxWidth) {
3170 minCropBoxHeight = minCropBoxWidth / aspectRatio;
3171 } else if (minCropBoxHeight) {
3172 minCropBoxWidth = minCropBoxHeight * aspectRatio;
3173 }
3174 if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {
3175 maxCropBoxHeight = maxCropBoxWidth / aspectRatio;
3176 } else {
3177 maxCropBoxWidth = maxCropBoxHeight * aspectRatio;
3178 }
3179 }
3180
3181 // The minWidth/Height must be less than maxWidth/Height
3182 cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth);
3183 cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight);
3184 cropBoxData.maxWidth = maxCropBoxWidth;
3185 cropBoxData.maxHeight = maxCropBoxHeight;
3186 }
3187 if (positionLimited) {
3188 if (limited) {
3189 cropBoxData.minLeft = Math.max(0, canvasData.left);
3190 cropBoxData.minTop = Math.max(0, canvasData.top);
3191 cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width;
3192 cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height;
3193 } else {
3194 cropBoxData.minLeft = 0;
3195 cropBoxData.minTop = 0;
3196 cropBoxData.maxLeft = containerData.width - cropBoxData.width;
3197 cropBoxData.maxTop = containerData.height - cropBoxData.height;
3198 }
3199 }
3200 },
3201 renderCropBox: function renderCropBox() {
3202 var options = this.options,
3203 containerData = this.containerData,
3204 cropBoxData = this.cropBoxData;
3205 if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) {
3206 cropBoxData.left = cropBoxData.oldLeft;
3207 }
3208 if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) {
3209 cropBoxData.top = cropBoxData.oldTop;
3210 }
3211 cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);
3212 cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);
3213 this.limitCropBox(false, true);
3214 cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft);
3215 cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop);
3216 cropBoxData.oldLeft = cropBoxData.left;
3217 cropBoxData.oldTop = cropBoxData.top;
3218 if (options.movable && options.cropBoxMovable) {
3219 // Turn to move the canvas when the crop box is equal to the container
3220 setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL);
3221 }
3222 setStyle(this.cropBox, assign({
3223 width: cropBoxData.width,
3224 height: cropBoxData.height
3225 }, getTransforms({
3226 translateX: cropBoxData.left,
3227 translateY: cropBoxData.top
3228 })));
3229 if (this.cropped && this.limited) {
3230 this.limitCanvas(true, true);
3231 }
3232 if (!this.disabled) {
3233 this.output();
3234 }
3235 },
3236 output: function output() {
3237 this.preview();
3238 dispatchEvent(this.element, EVENT_CROP, this.getData());
3239 }
3240 };
3241
3242 var preview = {
3243 initPreview: function initPreview() {
3244 var element = this.element,
3245 crossOrigin = this.crossOrigin;
3246 var preview = this.options.preview;
3247 var url = crossOrigin ? this.crossOriginUrl : this.url;
3248 var alt = element.alt || 'The image to preview';
3249 var image = document.createElement('img');
3250 if (crossOrigin) {
3251 image.crossOrigin = crossOrigin;
3252 }
3253 image.src = url;
3254 image.alt = alt;
3255 this.viewBox.appendChild(image);
3256 this.viewBoxImage = image;
3257 if (!preview) {
3258 return;
3259 }
3260 var previews = preview;
3261 if (typeof preview === 'string') {
3262 previews = element.ownerDocument.querySelectorAll(preview);
3263 } else if (preview.querySelector) {
3264 previews = [preview];
3265 }
3266 this.previews = previews;
3267 forEach(previews, function (el) {
3268 var img = document.createElement('img');
3269
3270 // Save the original size for recover
3271 setData(el, DATA_PREVIEW, {
3272 width: el.offsetWidth,
3273 height: el.offsetHeight,
3274 html: el.innerHTML
3275 });
3276 if (crossOrigin) {
3277 img.crossOrigin = crossOrigin;
3278 }
3279 img.src = url;
3280 img.alt = alt;
3281
3282 /**
3283 * Override img element styles
3284 * Add `display:block` to avoid margin top issue
3285 * Add `height:auto` to override `height` attribute on IE8
3286 * (Occur only when margin-top <= -height)
3287 */
3288 img.style.cssText = 'display:block;' + 'width:100%;' + 'height:auto;' + 'min-width:0!important;' + 'min-height:0!important;' + 'max-width:none!important;' + 'max-height:none!important;' + 'image-orientation:0deg!important;"';
3289 el.innerHTML = '';
3290 el.appendChild(img);
3291 });
3292 },
3293 resetPreview: function resetPreview() {
3294 forEach(this.previews, function (element) {
3295 var data = getData(element, DATA_PREVIEW);
3296 setStyle(element, {
3297 width: data.width,
3298 height: data.height
3299 });
3300 element.innerHTML = data.html;
3301 removeData(element, DATA_PREVIEW);
3302 });
3303 },
3304 preview: function preview() {
3305 var imageData = this.imageData,
3306 canvasData = this.canvasData,
3307 cropBoxData = this.cropBoxData;
3308 var cropBoxWidth = cropBoxData.width,
3309 cropBoxHeight = cropBoxData.height;
3310 var width = imageData.width,
3311 height = imageData.height;
3312 var left = cropBoxData.left - canvasData.left - imageData.left;
3313 var top = cropBoxData.top - canvasData.top - imageData.top;
3314 if (!this.cropped || this.disabled) {
3315 return;
3316 }
3317 setStyle(this.viewBoxImage, assign({
3318 width: width,
3319 height: height
3320 }, getTransforms(assign({
3321 translateX: -left,
3322 translateY: -top
3323 }, imageData))));
3324 forEach(this.previews, function (element) {
3325 var data = getData(element, DATA_PREVIEW);
3326 var originalWidth = data.width;
3327 var originalHeight = data.height;
3328 var newWidth = originalWidth;
3329 var newHeight = originalHeight;
3330 var ratio = 1;
3331 if (cropBoxWidth) {
3332 ratio = originalWidth / cropBoxWidth;
3333 newHeight = cropBoxHeight * ratio;
3334 }
3335 if (cropBoxHeight && newHeight > originalHeight) {
3336 ratio = originalHeight / cropBoxHeight;
3337 newWidth = cropBoxWidth * ratio;
3338 newHeight = originalHeight;
3339 }
3340 setStyle(element, {
3341 width: newWidth,
3342 height: newHeight
3343 });
3344 setStyle(element.getElementsByTagName('img')[0], assign({
3345 width: width * ratio,
3346 height: height * ratio
3347 }, getTransforms(assign({
3348 translateX: -left * ratio,
3349 translateY: -top * ratio
3350 }, imageData))));
3351 });
3352 }
3353 };
3354
3355 var events = {
3356 bind: function bind() {
3357 var element = this.element,
3358 options = this.options,
3359 cropper = this.cropper;
3360 if (isFunction(options.cropstart)) {
3361 addListener(element, EVENT_CROP_START, options.cropstart);
3362 }
3363 if (isFunction(options.cropmove)) {
3364 addListener(element, EVENT_CROP_MOVE, options.cropmove);
3365 }
3366 if (isFunction(options.cropend)) {
3367 addListener(element, EVENT_CROP_END, options.cropend);
3368 }
3369 if (isFunction(options.crop)) {
3370 addListener(element, EVENT_CROP, options.crop);
3371 }
3372 if (isFunction(options.zoom)) {
3373 addListener(element, EVENT_ZOOM, options.zoom);
3374 }
3375 addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this));
3376 if (options.zoomable && options.zoomOnWheel) {
3377 addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), {
3378 passive: false,
3379 capture: true
3380 });
3381 }
3382 if (options.toggleDragModeOnDblclick) {
3383 addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this));
3384 }
3385 addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this));
3386 addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this));
3387 if (options.responsive) {
3388 addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this));
3389 }
3390 },
3391 unbind: function unbind() {
3392 var element = this.element,
3393 options = this.options,
3394 cropper = this.cropper;
3395 if (isFunction(options.cropstart)) {
3396 removeListener(element, EVENT_CROP_START, options.cropstart);
3397 }
3398 if (isFunction(options.cropmove)) {
3399 removeListener(element, EVENT_CROP_MOVE, options.cropmove);
3400 }
3401 if (isFunction(options.cropend)) {
3402 removeListener(element, EVENT_CROP_END, options.cropend);
3403 }
3404 if (isFunction(options.crop)) {
3405 removeListener(element, EVENT_CROP, options.crop);
3406 }
3407 if (isFunction(options.zoom)) {
3408 removeListener(element, EVENT_ZOOM, options.zoom);
3409 }
3410 removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart);
3411 if (options.zoomable && options.zoomOnWheel) {
3412 removeListener(cropper, EVENT_WHEEL, this.onWheel, {
3413 passive: false,
3414 capture: true
3415 });
3416 }
3417 if (options.toggleDragModeOnDblclick) {
3418 removeListener(cropper, EVENT_DBLCLICK, this.onDblclick);
3419 }
3420 removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove);
3421 removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd);
3422 if (options.responsive) {
3423 removeListener(window, EVENT_RESIZE, this.onResize);
3424 }
3425 }
3426 };
3427
3428 var handlers = {
3429 resize: function resize() {
3430 if (this.disabled) {
3431 return;
3432 }
3433 var options = this.options,
3434 container = this.container,
3435 containerData = this.containerData;
3436 var ratioX = container.offsetWidth / containerData.width;
3437 var ratioY = container.offsetHeight / containerData.height;
3438 var ratio = Math.abs(ratioX - 1) > Math.abs(ratioY - 1) ? ratioX : ratioY;
3439
3440 // Resize when width changed or height changed
3441 if (ratio !== 1) {
3442 var canvasData;
3443 var cropBoxData;
3444 if (options.restore) {
3445 canvasData = this.getCanvasData();
3446 cropBoxData = this.getCropBoxData();
3447 }
3448 this.render();
3449 if (options.restore) {
3450 this.setCanvasData(forEach(canvasData, function (n, i) {
3451 canvasData[i] = n * ratio;
3452 }));
3453 this.setCropBoxData(forEach(cropBoxData, function (n, i) {
3454 cropBoxData[i] = n * ratio;
3455 }));
3456 }
3457 }
3458 },
3459 dblclick: function dblclick() {
3460 if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) {
3461 return;
3462 }
3463 this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP);
3464 },
3465 wheel: function wheel(event) {
3466 var _this = this;
3467 var ratio = Number(this.options.wheelZoomRatio) || 0.1;
3468 var delta = 1;
3469 if (this.disabled) {
3470 return;
3471 }
3472 event.preventDefault();
3473
3474 // Limit wheel speed to prevent zoom too fast (#21)
3475 if (this.wheeling) {
3476 return;
3477 }
3478 this.wheeling = true;
3479 setTimeout(function () {
3480 _this.wheeling = false;
3481 }, 50);
3482 if (event.deltaY) {
3483 delta = event.deltaY > 0 ? 1 : -1;
3484 } else if (event.wheelDelta) {
3485 delta = -event.wheelDelta / 120;
3486 } else if (event.detail) {
3487 delta = event.detail > 0 ? 1 : -1;
3488 }
3489 this.zoom(-delta * ratio, event);
3490 },
3491 cropStart: function cropStart(event) {
3492 var buttons = event.buttons,
3493 button = event.button;
3494 if (this.disabled
3495
3496 // Handle mouse event and pointer event and ignore touch event
3497 || (event.type === 'mousedown' || event.type === 'pointerdown' && event.pointerType === 'mouse') && (
3498 // No primary button (Usually the left button)
3499 isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0
3500
3501 // Open context menu
3502 || event.ctrlKey)) {
3503 return;
3504 }
3505 var options = this.options,
3506 pointers = this.pointers;
3507 var action;
3508 if (event.changedTouches) {
3509 // Handle touch event
3510 forEach(event.changedTouches, function (touch) {
3511 pointers[touch.identifier] = getPointer(touch);
3512 });
3513 } else {
3514 // Handle mouse event and pointer event
3515 pointers[event.pointerId || 0] = getPointer(event);
3516 }
3517 if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {
3518 action = ACTION_ZOOM;
3519 } else {
3520 action = getData(event.target, DATA_ACTION);
3521 }
3522 if (!REGEXP_ACTIONS.test(action)) {
3523 return;
3524 }
3525 if (dispatchEvent(this.element, EVENT_CROP_START, {
3526 originalEvent: event,
3527 action: action
3528 }) === false) {
3529 return;
3530 }
3531
3532 // This line is required for preventing page zooming in iOS browsers
3533 event.preventDefault();
3534 this.action = action;
3535 this.cropping = false;
3536 if (action === ACTION_CROP) {
3537 this.cropping = true;
3538 addClass(this.dragBox, CLASS_MODAL);
3539 }
3540 },
3541 cropMove: function cropMove(event) {
3542 var action = this.action;
3543 if (this.disabled || !action) {
3544 return;
3545 }
3546 var pointers = this.pointers;
3547 event.preventDefault();
3548 if (dispatchEvent(this.element, EVENT_CROP_MOVE, {
3549 originalEvent: event,
3550 action: action
3551 }) === false) {
3552 return;
3553 }
3554 if (event.changedTouches) {
3555 forEach(event.changedTouches, function (touch) {
3556 // The first parameter should not be undefined (#432)
3557 assign(pointers[touch.identifier] || {}, getPointer(touch, true));
3558 });
3559 } else {
3560 assign(pointers[event.pointerId || 0] || {}, getPointer(event, true));
3561 }
3562 this.change(event);
3563 },
3564 cropEnd: function cropEnd(event) {
3565 if (this.disabled) {
3566 return;
3567 }
3568 var action = this.action,
3569 pointers = this.pointers;
3570 if (event.changedTouches) {
3571 forEach(event.changedTouches, function (touch) {
3572 delete pointers[touch.identifier];
3573 });
3574 } else {
3575 delete pointers[event.pointerId || 0];
3576 }
3577 if (!action) {
3578 return;
3579 }
3580 event.preventDefault();
3581 if (!Object.keys(pointers).length) {
3582 this.action = '';
3583 }
3584 if (this.cropping) {
3585 this.cropping = false;
3586 toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal);
3587 }
3588 dispatchEvent(this.element, EVENT_CROP_END, {
3589 originalEvent: event,
3590 action: action
3591 });
3592 }
3593 };
3594
3595 var change = {
3596 change: function change(event) {
3597 var options = this.options,
3598 canvasData = this.canvasData,
3599 containerData = this.containerData,
3600 cropBoxData = this.cropBoxData,
3601 pointers = this.pointers;
3602 var action = this.action;
3603 var aspectRatio = options.aspectRatio;
3604 var left = cropBoxData.left,
3605 top = cropBoxData.top,
3606 width = cropBoxData.width,
3607 height = cropBoxData.height;
3608 var right = left + width;
3609 var bottom = top + height;
3610 var minLeft = 0;
3611 var minTop = 0;
3612 var maxWidth = containerData.width;
3613 var maxHeight = containerData.height;
3614 var renderable = true;
3615 var offset;
3616
3617 // Locking aspect ratio in "free mode" by holding shift key
3618 if (!aspectRatio && event.shiftKey) {
3619 aspectRatio = width && height ? width / height : 1;
3620 }
3621 if (this.limited) {
3622 minLeft = cropBoxData.minLeft;
3623 minTop = cropBoxData.minTop;
3624 maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width);
3625 maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height);
3626 }
3627 var pointer = pointers[Object.keys(pointers)[0]];
3628 var range = {
3629 x: pointer.endX - pointer.startX,
3630 y: pointer.endY - pointer.startY
3631 };
3632 var check = function check(side) {
3633 switch (side) {
3634 case ACTION_EAST:
3635 if (right + range.x > maxWidth) {
3636 range.x = maxWidth - right;
3637 }
3638 break;
3639 case ACTION_WEST:
3640 if (left + range.x < minLeft) {
3641 range.x = minLeft - left;
3642 }
3643 break;
3644 case ACTION_NORTH:
3645 if (top + range.y < minTop) {
3646 range.y = minTop - top;
3647 }
3648 break;
3649 case ACTION_SOUTH:
3650 if (bottom + range.y > maxHeight) {
3651 range.y = maxHeight - bottom;
3652 }
3653 break;
3654 }
3655 };
3656 switch (action) {
3657 // Move crop box
3658 case ACTION_ALL:
3659 left += range.x;
3660 top += range.y;
3661 break;
3662
3663 // Resize crop box
3664 case ACTION_EAST:
3665 if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) {
3666 renderable = false;
3667 break;
3668 }
3669 check(ACTION_EAST);
3670 width += range.x;
3671 if (width < 0) {
3672 action = ACTION_WEST;
3673 width = -width;
3674 left -= width;
3675 }
3676 if (aspectRatio) {
3677 height = width / aspectRatio;
3678 top += (cropBoxData.height - height) / 2;
3679 }
3680 break;
3681 case ACTION_NORTH:
3682 if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) {
3683 renderable = false;
3684 break;
3685 }
3686 check(ACTION_NORTH);
3687 height -= range.y;
3688 top += range.y;
3689 if (height < 0) {
3690 action = ACTION_SOUTH;
3691 height = -height;
3692 top -= height;
3693 }
3694 if (aspectRatio) {
3695 width = height * aspectRatio;
3696 left += (cropBoxData.width - width) / 2;
3697 }
3698 break;
3699 case ACTION_WEST:
3700 if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) {
3701 renderable = false;
3702 break;
3703 }
3704 check(ACTION_WEST);
3705 width -= range.x;
3706 left += range.x;
3707 if (width < 0) {
3708 action = ACTION_EAST;
3709 width = -width;
3710 left -= width;
3711 }
3712 if (aspectRatio) {
3713 height = width / aspectRatio;
3714 top += (cropBoxData.height - height) / 2;
3715 }
3716 break;
3717 case ACTION_SOUTH:
3718 if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) {
3719 renderable = false;
3720 break;
3721 }
3722 check(ACTION_SOUTH);
3723 height += range.y;
3724 if (height < 0) {
3725 action = ACTION_NORTH;
3726 height = -height;
3727 top -= height;
3728 }
3729 if (aspectRatio) {
3730 width = height * aspectRatio;
3731 left += (cropBoxData.width - width) / 2;
3732 }
3733 break;
3734 case ACTION_NORTH_EAST:
3735 if (aspectRatio) {
3736 if (range.y <= 0 && (top <= minTop || right >= maxWidth)) {
3737 renderable = false;
3738 break;
3739 }
3740 check(ACTION_NORTH);
3741 height -= range.y;
3742 top += range.y;
3743 width = height * aspectRatio;
3744 } else {
3745 check(ACTION_NORTH);
3746 check(ACTION_EAST);
3747 if (range.x >= 0) {
3748 if (right < maxWidth) {
3749 width += range.x;
3750 } else if (range.y <= 0 && top <= minTop) {
3751 renderable = false;
3752 }
3753 } else {
3754 width += range.x;
3755 }
3756 if (range.y <= 0) {
3757 if (top > minTop) {
3758 height -= range.y;
3759 top += range.y;
3760 }
3761 } else {
3762 height -= range.y;
3763 top += range.y;
3764 }
3765 }
3766 if (width < 0 && height < 0) {
3767 action = ACTION_SOUTH_WEST;
3768 height = -height;
3769 width = -width;
3770 top -= height;
3771 left -= width;
3772 } else if (width < 0) {
3773 action = ACTION_NORTH_WEST;
3774 width = -width;
3775 left -= width;
3776 } else if (height < 0) {
3777 action = ACTION_SOUTH_EAST;
3778 height = -height;
3779 top -= height;
3780 }
3781 break;
3782 case ACTION_NORTH_WEST:
3783 if (aspectRatio) {
3784 if (range.y <= 0 && (top <= minTop || left <= minLeft)) {
3785 renderable = false;
3786 break;
3787 }
3788 check(ACTION_NORTH);
3789 height -= range.y;
3790 top += range.y;
3791 width = height * aspectRatio;
3792 left += cropBoxData.width - width;
3793 } else {
3794 check(ACTION_NORTH);
3795 check(ACTION_WEST);
3796 if (range.x <= 0) {
3797 if (left > minLeft) {
3798 width -= range.x;
3799 left += range.x;
3800 } else if (range.y <= 0 && top <= minTop) {
3801 renderable = false;
3802 }
3803 } else {
3804 width -= range.x;
3805 left += range.x;
3806 }
3807 if (range.y <= 0) {
3808 if (top > minTop) {
3809 height -= range.y;
3810 top += range.y;
3811 }
3812 } else {
3813 height -= range.y;
3814 top += range.y;
3815 }
3816 }
3817 if (width < 0 && height < 0) {
3818 action = ACTION_SOUTH_EAST;
3819 height = -height;
3820 width = -width;
3821 top -= height;
3822 left -= width;
3823 } else if (width < 0) {
3824 action = ACTION_NORTH_EAST;
3825 width = -width;
3826 left -= width;
3827 } else if (height < 0) {
3828 action = ACTION_SOUTH_WEST;
3829 height = -height;
3830 top -= height;
3831 }
3832 break;
3833 case ACTION_SOUTH_WEST:
3834 if (aspectRatio) {
3835 if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) {
3836 renderable = false;
3837 break;
3838 }
3839 check(ACTION_WEST);
3840 width -= range.x;
3841 left += range.x;
3842 height = width / aspectRatio;
3843 } else {
3844 check(ACTION_SOUTH);
3845 check(ACTION_WEST);
3846 if (range.x <= 0) {
3847 if (left > minLeft) {
3848 width -= range.x;
3849 left += range.x;
3850 } else if (range.y >= 0 && bottom >= maxHeight) {
3851 renderable = false;
3852 }
3853 } else {
3854 width -= range.x;
3855 left += range.x;
3856 }
3857 if (range.y >= 0) {
3858 if (bottom < maxHeight) {
3859 height += range.y;
3860 }
3861 } else {
3862 height += range.y;
3863 }
3864 }
3865 if (width < 0 && height < 0) {
3866 action = ACTION_NORTH_EAST;
3867 height = -height;
3868 width = -width;
3869 top -= height;
3870 left -= width;
3871 } else if (width < 0) {
3872 action = ACTION_SOUTH_EAST;
3873 width = -width;
3874 left -= width;
3875 } else if (height < 0) {
3876 action = ACTION_NORTH_WEST;
3877 height = -height;
3878 top -= height;
3879 }
3880 break;
3881 case ACTION_SOUTH_EAST:
3882 if (aspectRatio) {
3883 if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) {
3884 renderable = false;
3885 break;
3886 }
3887 check(ACTION_EAST);
3888 width += range.x;
3889 height = width / aspectRatio;
3890 } else {
3891 check(ACTION_SOUTH);
3892 check(ACTION_EAST);
3893 if (range.x >= 0) {
3894 if (right < maxWidth) {
3895 width += range.x;
3896 } else if (range.y >= 0 && bottom >= maxHeight) {
3897 renderable = false;
3898 }
3899 } else {
3900 width += range.x;
3901 }
3902 if (range.y >= 0) {
3903 if (bottom < maxHeight) {
3904 height += range.y;
3905 }
3906 } else {
3907 height += range.y;
3908 }
3909 }
3910 if (width < 0 && height < 0) {
3911 action = ACTION_NORTH_WEST;
3912 height = -height;
3913 width = -width;
3914 top -= height;
3915 left -= width;
3916 } else if (width < 0) {
3917 action = ACTION_SOUTH_WEST;
3918 width = -width;
3919 left -= width;
3920 } else if (height < 0) {
3921 action = ACTION_NORTH_EAST;
3922 height = -height;
3923 top -= height;
3924 }
3925 break;
3926
3927 // Move canvas
3928 case ACTION_MOVE:
3929 this.move(range.x, range.y);
3930 renderable = false;
3931 break;
3932
3933 // Zoom canvas
3934 case ACTION_ZOOM:
3935 this.zoom(getMaxZoomRatio(pointers), event);
3936 renderable = false;
3937 break;
3938
3939 // Create crop box
3940 case ACTION_CROP:
3941 if (!range.x || !range.y) {
3942 renderable = false;
3943 break;
3944 }
3945 offset = getOffset(this.cropper);
3946 left = pointer.startX - offset.left;
3947 top = pointer.startY - offset.top;
3948 width = cropBoxData.minWidth;
3949 height = cropBoxData.minHeight;
3950 if (range.x > 0) {
3951 action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST;
3952 } else if (range.x < 0) {
3953 left -= width;
3954 action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST;
3955 }
3956 if (range.y < 0) {
3957 top -= height;
3958 }
3959
3960 // Show the crop box if is hidden
3961 if (!this.cropped) {
3962 removeClass(this.cropBox, CLASS_HIDDEN);
3963 this.cropped = true;
3964 if (this.limited) {
3965 this.limitCropBox(true, true);
3966 }
3967 }
3968 break;
3969 }
3970 if (renderable) {
3971 cropBoxData.width = width;
3972 cropBoxData.height = height;
3973 cropBoxData.left = left;
3974 cropBoxData.top = top;
3975 this.action = action;
3976 this.renderCropBox();
3977 }
3978
3979 // Override
3980 forEach(pointers, function (p) {
3981 p.startX = p.endX;
3982 p.startY = p.endY;
3983 });
3984 }
3985 };
3986
3987 var methods = {
3988 // Show the crop box manually
3989 crop: function crop() {
3990 if (this.ready && !this.cropped && !this.disabled) {
3991 this.cropped = true;
3992 this.limitCropBox(true, true);
3993 if (this.options.modal) {
3994 addClass(this.dragBox, CLASS_MODAL);
3995 }
3996 removeClass(this.cropBox, CLASS_HIDDEN);
3997 this.setCropBoxData(this.initialCropBoxData);
3998 }
3999 return this;
4000 },
4001 // Reset the image and crop box to their initial states
4002 reset: function reset() {
4003 if (this.ready && !this.disabled) {
4004 this.imageData = assign({}, this.initialImageData);
4005 this.canvasData = assign({}, this.initialCanvasData);
4006 this.cropBoxData = assign({}, this.initialCropBoxData);
4007 this.renderCanvas();
4008 if (this.cropped) {
4009 this.renderCropBox();
4010 }
4011 }
4012 return this;
4013 },
4014 // Clear the crop box
4015 clear: function clear() {
4016 if (this.cropped && !this.disabled) {
4017 assign(this.cropBoxData, {
4018 left: 0,
4019 top: 0,
4020 width: 0,
4021 height: 0
4022 });
4023 this.cropped = false;
4024 this.renderCropBox();
4025 this.limitCanvas(true, true);
4026
4027 // Render canvas after crop box rendered
4028 this.renderCanvas();
4029 removeClass(this.dragBox, CLASS_MODAL);
4030 addClass(this.cropBox, CLASS_HIDDEN);
4031 }
4032 return this;
4033 },
4034 /**
4035 * Replace the image's src and rebuild the cropper
4036 * @param {string} url - The new URL.
4037 * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one.
4038 * @returns {Cropper} this
4039 */
4040 replace: function replace(url) {
4041 var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
4042 if (!this.disabled && url) {
4043 if (this.isImg) {
4044 this.element.src = url;
4045 }
4046 if (hasSameSize) {
4047 this.url = url;
4048 this.image.src = url;
4049 if (this.ready) {
4050 this.viewBoxImage.src = url;
4051 forEach(this.previews, function (element) {
4052 element.getElementsByTagName('img')[0].src = url;
4053 });
4054 }
4055 } else {
4056 if (this.isImg) {
4057 this.replaced = true;
4058 }
4059 this.options.data = null;
4060 this.uncreate();
4061 this.load(url);
4062 }
4063 }
4064 return this;
4065 },
4066 // Enable (unfreeze) the cropper
4067 enable: function enable() {
4068 if (this.ready && this.disabled) {
4069 this.disabled = false;
4070 removeClass(this.cropper, CLASS_DISABLED);
4071 }
4072 return this;
4073 },
4074 // Disable (freeze) the cropper
4075 disable: function disable() {
4076 if (this.ready && !this.disabled) {
4077 this.disabled = true;
4078 addClass(this.cropper, CLASS_DISABLED);
4079 }
4080 return this;
4081 },
4082 /**
4083 * Destroy the cropper and remove the instance from the image
4084 * @returns {Cropper} this
4085 */
4086 destroy: function destroy() {
4087 var element = this.element;
4088 if (!element[NAMESPACE]) {
4089 return this;
4090 }
4091 element[NAMESPACE] = undefined;
4092 if (this.isImg && this.replaced) {
4093 element.src = this.originalUrl;
4094 }
4095 this.uncreate();
4096 return this;
4097 },
4098 /**
4099 * Move the canvas with relative offsets
4100 * @param {number} offsetX - The relative offset distance on the x-axis.
4101 * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis.
4102 * @returns {Cropper} this
4103 */
4104 move: function move(offsetX) {
4105 var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX;
4106 var _this$canvasData = this.canvasData,
4107 left = _this$canvasData.left,
4108 top = _this$canvasData.top;
4109 return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY));
4110 },
4111 /**
4112 * Move the canvas to an absolute point
4113 * @param {number} x - The x-axis coordinate.
4114 * @param {number} [y=x] - The y-axis coordinate.
4115 * @returns {Cropper} this
4116 */
4117 moveTo: function moveTo(x) {
4118 var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;
4119 var canvasData = this.canvasData;
4120 var changed = false;
4121 x = Number(x);
4122 y = Number(y);
4123 if (this.ready && !this.disabled && this.options.movable) {
4124 if (isNumber(x)) {
4125 canvasData.left = x;
4126 changed = true;
4127 }
4128 if (isNumber(y)) {
4129 canvasData.top = y;
4130 changed = true;
4131 }
4132 if (changed) {
4133 this.renderCanvas(true);
4134 }
4135 }
4136 return this;
4137 },
4138 /**
4139 * Zoom the canvas with a relative ratio
4140 * @param {number} ratio - The target ratio.
4141 * @param {Event} _originalEvent - The original event if any.
4142 * @returns {Cropper} this
4143 */
4144 zoom: function zoom(ratio, _originalEvent) {
4145 var canvasData = this.canvasData;
4146 ratio = Number(ratio);
4147 if (ratio < 0) {
4148 ratio = 1 / (1 - ratio);
4149 } else {
4150 ratio = 1 + ratio;
4151 }
4152 return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent);
4153 },
4154 /**
4155 * Zoom the canvas to an absolute ratio
4156 * @param {number} ratio - The target ratio.
4157 * @param {Object} pivot - The zoom pivot point coordinate.
4158 * @param {Event} _originalEvent - The original event if any.
4159 * @returns {Cropper} this
4160 */
4161 zoomTo: function zoomTo(ratio, pivot, _originalEvent) {
4162 var options = this.options,
4163 canvasData = this.canvasData;
4164 var width = canvasData.width,
4165 height = canvasData.height,
4166 naturalWidth = canvasData.naturalWidth,
4167 naturalHeight = canvasData.naturalHeight;
4168 ratio = Number(ratio);
4169 if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) {
4170 var newWidth = naturalWidth * ratio;
4171 var newHeight = naturalHeight * ratio;
4172 if (dispatchEvent(this.element, EVENT_ZOOM, {
4173 ratio: ratio,
4174 oldRatio: width / naturalWidth,
4175 originalEvent: _originalEvent
4176 }) === false) {
4177 return this;
4178 }
4179 if (_originalEvent) {
4180 var pointers = this.pointers;
4181 var offset = getOffset(this.cropper);
4182 var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : {
4183 pageX: _originalEvent.pageX,
4184 pageY: _originalEvent.pageY
4185 };
4186
4187 // Zoom from the triggering point of the event
4188 canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width);
4189 canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height);
4190 } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) {
4191 canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width);
4192 canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height);
4193 } else {
4194 // Zoom from the center of the canvas
4195 canvasData.left -= (newWidth - width) / 2;
4196 canvasData.top -= (newHeight - height) / 2;
4197 }
4198 canvasData.width = newWidth;
4199 canvasData.height = newHeight;
4200 this.renderCanvas(true);
4201 }
4202 return this;
4203 },
4204 /**
4205 * Rotate the canvas with a relative degree
4206 * @param {number} degree - The rotate degree.
4207 * @returns {Cropper} this
4208 */
4209 rotate: function rotate(degree) {
4210 return this.rotateTo((this.imageData.rotate || 0) + Number(degree));
4211 },
4212 /**
4213 * Rotate the canvas to an absolute degree
4214 * @param {number} degree - The rotate degree.
4215 * @returns {Cropper} this
4216 */
4217 rotateTo: function rotateTo(degree) {
4218 degree = Number(degree);
4219 if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) {
4220 this.imageData.rotate = degree % 360;
4221 this.renderCanvas(true, true);
4222 }
4223 return this;
4224 },
4225 /**
4226 * Scale the image on the x-axis.
4227 * @param {number} scaleX - The scale ratio on the x-axis.
4228 * @returns {Cropper} this
4229 */
4230 scaleX: function scaleX(_scaleX) {
4231 var scaleY = this.imageData.scaleY;
4232 return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1);
4233 },
4234 /**
4235 * Scale the image on the y-axis.
4236 * @param {number} scaleY - The scale ratio on the y-axis.
4237 * @returns {Cropper} this
4238 */
4239 scaleY: function scaleY(_scaleY) {
4240 var scaleX = this.imageData.scaleX;
4241 return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY);
4242 },
4243 /**
4244 * Scale the image
4245 * @param {number} scaleX - The scale ratio on the x-axis.
4246 * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis.
4247 * @returns {Cropper} this
4248 */
4249 scale: function scale(scaleX) {
4250 var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;
4251 var imageData = this.imageData;
4252 var transformed = false;
4253 scaleX = Number(scaleX);
4254 scaleY = Number(scaleY);
4255 if (this.ready && !this.disabled && this.options.scalable) {
4256 if (isNumber(scaleX)) {
4257 imageData.scaleX = scaleX;
4258 transformed = true;
4259 }
4260 if (isNumber(scaleY)) {
4261 imageData.scaleY = scaleY;
4262 transformed = true;
4263 }
4264 if (transformed) {
4265 this.renderCanvas(true, true);
4266 }
4267 }
4268 return this;
4269 },
4270 /**
4271 * Get the cropped area position and size data (base on the original image)
4272 * @param {boolean} [rounded=false] - Indicate if round the data values or not.
4273 * @returns {Object} The result cropped data.
4274 */
4275 getData: function getData() {
4276 var rounded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
4277 var options = this.options,
4278 imageData = this.imageData,
4279 canvasData = this.canvasData,
4280 cropBoxData = this.cropBoxData;
4281 var data;
4282 if (this.ready && this.cropped) {
4283 data = {
4284 x: cropBoxData.left - canvasData.left,
4285 y: cropBoxData.top - canvasData.top,
4286 width: cropBoxData.width,
4287 height: cropBoxData.height
4288 };
4289 var ratio = imageData.width / imageData.naturalWidth;
4290 forEach(data, function (n, i) {
4291 data[i] = n / ratio;
4292 });
4293 if (rounded) {
4294 // In case rounding off leads to extra 1px in right or bottom border
4295 // we should round the top-left corner and the dimension (#343).
4296 var bottom = Math.round(data.y + data.height);
4297 var right = Math.round(data.x + data.width);
4298 data.x = Math.round(data.x);
4299 data.y = Math.round(data.y);
4300 data.width = right - data.x;
4301 data.height = bottom - data.y;
4302 }
4303 } else {
4304 data = {
4305 x: 0,
4306 y: 0,
4307 width: 0,
4308 height: 0
4309 };
4310 }
4311 if (options.rotatable) {
4312 data.rotate = imageData.rotate || 0;
4313 }
4314 if (options.scalable) {
4315 data.scaleX = imageData.scaleX || 1;
4316 data.scaleY = imageData.scaleY || 1;
4317 }
4318 return data;
4319 },
4320 /**
4321 * Set the cropped area position and size with new data
4322 * @param {Object} data - The new data.
4323 * @returns {Cropper} this
4324 */
4325 setData: function setData(data) {
4326 var options = this.options,
4327 imageData = this.imageData,
4328 canvasData = this.canvasData;
4329 var cropBoxData = {};
4330 if (this.ready && !this.disabled && isPlainObject(data)) {
4331 var transformed = false;
4332 if (options.rotatable) {
4333 if (isNumber(data.rotate) && data.rotate !== imageData.rotate) {
4334 imageData.rotate = data.rotate;
4335 transformed = true;
4336 }
4337 }
4338 if (options.scalable) {
4339 if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) {
4340 imageData.scaleX = data.scaleX;
4341 transformed = true;
4342 }
4343 if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) {
4344 imageData.scaleY = data.scaleY;
4345 transformed = true;
4346 }
4347 }
4348 if (transformed) {
4349 this.renderCanvas(true, true);
4350 }
4351 var ratio = imageData.width / imageData.naturalWidth;
4352 if (isNumber(data.x)) {
4353 cropBoxData.left = data.x * ratio + canvasData.left;
4354 }
4355 if (isNumber(data.y)) {
4356 cropBoxData.top = data.y * ratio + canvasData.top;
4357 }
4358 if (isNumber(data.width)) {
4359 cropBoxData.width = data.width * ratio;
4360 }
4361 if (isNumber(data.height)) {
4362 cropBoxData.height = data.height * ratio;
4363 }
4364 this.setCropBoxData(cropBoxData);
4365 }
4366 return this;
4367 },
4368 /**
4369 * Get the container size data.
4370 * @returns {Object} The result container data.
4371 */
4372 getContainerData: function getContainerData() {
4373 return this.ready ? assign({}, this.containerData) : {};
4374 },
4375 /**
4376 * Get the image position and size data.
4377 * @returns {Object} The result image data.
4378 */
4379 getImageData: function getImageData() {
4380 return this.sized ? assign({}, this.imageData) : {};
4381 },
4382 /**
4383 * Get the canvas position and size data.
4384 * @returns {Object} The result canvas data.
4385 */
4386 getCanvasData: function getCanvasData() {
4387 var canvasData = this.canvasData;
4388 var data = {};
4389 if (this.ready) {
4390 forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) {
4391 data[n] = canvasData[n];
4392 });
4393 }
4394 return data;
4395 },
4396 /**
4397 * Set the canvas position and size with new data.
4398 * @param {Object} data - The new canvas data.
4399 * @returns {Cropper} this
4400 */
4401 setCanvasData: function setCanvasData(data) {
4402 var canvasData = this.canvasData;
4403 var aspectRatio = canvasData.aspectRatio;
4404 if (this.ready && !this.disabled && isPlainObject(data)) {
4405 if (isNumber(data.left)) {
4406 canvasData.left = data.left;
4407 }
4408 if (isNumber(data.top)) {
4409 canvasData.top = data.top;
4410 }
4411 if (isNumber(data.width)) {
4412 canvasData.width = data.width;
4413 canvasData.height = data.width / aspectRatio;
4414 } else if (isNumber(data.height)) {
4415 canvasData.height = data.height;
4416 canvasData.width = data.height * aspectRatio;
4417 }
4418 this.renderCanvas(true);
4419 }
4420 return this;
4421 },
4422 /**
4423 * Get the crop box position and size data.
4424 * @returns {Object} The result crop box data.
4425 */
4426 getCropBoxData: function getCropBoxData() {
4427 var cropBoxData = this.cropBoxData;
4428 var data;
4429 if (this.ready && this.cropped) {
4430 data = {
4431 left: cropBoxData.left,
4432 top: cropBoxData.top,
4433 width: cropBoxData.width,
4434 height: cropBoxData.height
4435 };
4436 }
4437 return data || {};
4438 },
4439 /**
4440 * Set the crop box position and size with new data.
4441 * @param {Object} data - The new crop box data.
4442 * @returns {Cropper} this
4443 */
4444 setCropBoxData: function setCropBoxData(data) {
4445 var cropBoxData = this.cropBoxData;
4446 var aspectRatio = this.options.aspectRatio;
4447 var widthChanged;
4448 var heightChanged;
4449 if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) {
4450 if (isNumber(data.left)) {
4451 cropBoxData.left = data.left;
4452 }
4453 if (isNumber(data.top)) {
4454 cropBoxData.top = data.top;
4455 }
4456 if (isNumber(data.width) && data.width !== cropBoxData.width) {
4457 widthChanged = true;
4458 cropBoxData.width = data.width;
4459 }
4460 if (isNumber(data.height) && data.height !== cropBoxData.height) {
4461 heightChanged = true;
4462 cropBoxData.height = data.height;
4463 }
4464 if (aspectRatio) {
4465 if (widthChanged) {
4466 cropBoxData.height = cropBoxData.width / aspectRatio;
4467 } else if (heightChanged) {
4468 cropBoxData.width = cropBoxData.height * aspectRatio;
4469 }
4470 }
4471 this.renderCropBox();
4472 }
4473 return this;
4474 },
4475 /**
4476 * Get a canvas drawn the cropped image.
4477 * @param {Object} [options={}] - The config options.
4478 * @returns {HTMLCanvasElement} - The result canvas.
4479 */
4480 getCroppedCanvas: function getCroppedCanvas() {
4481 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4482 if (!this.ready || !window.HTMLCanvasElement) {
4483 return null;
4484 }
4485 var canvasData = this.canvasData;
4486 var source = getSourceCanvas(this.image, this.imageData, canvasData, options);
4487
4488 // Returns the source canvas if it is not cropped.
4489 if (!this.cropped) {
4490 return source;
4491 }
4492 var _this$getData = this.getData(options.rounded),
4493 initialX = _this$getData.x,
4494 initialY = _this$getData.y,
4495 initialWidth = _this$getData.width,
4496 initialHeight = _this$getData.height;
4497 var ratio = source.width / Math.floor(canvasData.naturalWidth);
4498 if (ratio !== 1) {
4499 initialX *= ratio;
4500 initialY *= ratio;
4501 initialWidth *= ratio;
4502 initialHeight *= ratio;
4503 }
4504 var aspectRatio = initialWidth / initialHeight;
4505 var maxSizes = getAdjustedSizes({
4506 aspectRatio: aspectRatio,
4507 width: options.maxWidth || Infinity,
4508 height: options.maxHeight || Infinity
4509 });
4510 var minSizes = getAdjustedSizes({
4511 aspectRatio: aspectRatio,
4512 width: options.minWidth || 0,
4513 height: options.minHeight || 0
4514 }, 'cover');
4515 var _getAdjustedSizes = getAdjustedSizes({
4516 aspectRatio: aspectRatio,
4517 width: options.width || (ratio !== 1 ? source.width : initialWidth),
4518 height: options.height || (ratio !== 1 ? source.height : initialHeight)
4519 }),
4520 width = _getAdjustedSizes.width,
4521 height = _getAdjustedSizes.height;
4522 width = Math.min(maxSizes.width, Math.max(minSizes.width, width));
4523 height = Math.min(maxSizes.height, Math.max(minSizes.height, height));
4524 var canvas = document.createElement('canvas');
4525 var context = canvas.getContext('2d');
4526 canvas.width = normalizeDecimalNumber(width);
4527 canvas.height = normalizeDecimalNumber(height);
4528 context.fillStyle = options.fillColor || 'transparent';
4529 context.fillRect(0, 0, width, height);
4530 var _options$imageSmoothi = options.imageSmoothingEnabled,
4531 imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi,
4532 imageSmoothingQuality = options.imageSmoothingQuality;
4533 context.imageSmoothingEnabled = imageSmoothingEnabled;
4534 if (imageSmoothingQuality) {
4535 context.imageSmoothingQuality = imageSmoothingQuality;
4536 }
4537
4538 // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage
4539 var sourceWidth = source.width;
4540 var sourceHeight = source.height;
4541
4542 // Source canvas parameters
4543 var srcX = initialX;
4544 var srcY = initialY;
4545 var srcWidth;
4546 var srcHeight;
4547
4548 // Destination canvas parameters
4549 var dstX;
4550 var dstY;
4551 var dstWidth;
4552 var dstHeight;
4553 if (srcX <= -initialWidth || srcX > sourceWidth) {
4554 srcX = 0;
4555 srcWidth = 0;
4556 dstX = 0;
4557 dstWidth = 0;
4558 } else if (srcX <= 0) {
4559 dstX = -srcX;
4560 srcX = 0;
4561 srcWidth = Math.min(sourceWidth, initialWidth + srcX);
4562 dstWidth = srcWidth;
4563 } else if (srcX <= sourceWidth) {
4564 dstX = 0;
4565 srcWidth = Math.min(initialWidth, sourceWidth - srcX);
4566 dstWidth = srcWidth;
4567 }
4568 if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) {
4569 srcY = 0;
4570 srcHeight = 0;
4571 dstY = 0;
4572 dstHeight = 0;
4573 } else if (srcY <= 0) {
4574 dstY = -srcY;
4575 srcY = 0;
4576 srcHeight = Math.min(sourceHeight, initialHeight + srcY);
4577 dstHeight = srcHeight;
4578 } else if (srcY <= sourceHeight) {
4579 dstY = 0;
4580 srcHeight = Math.min(initialHeight, sourceHeight - srcY);
4581 dstHeight = srcHeight;
4582 }
4583 var params = [srcX, srcY, srcWidth, srcHeight];
4584
4585 // Avoid "IndexSizeError"
4586 if (dstWidth > 0 && dstHeight > 0) {
4587 var scale = width / initialWidth;
4588 params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale);
4589 }
4590
4591 // All the numerical parameters should be integer for `drawImage`
4592 // https://github.com/fengyuanchen/cropper/issues/476
4593 context.drawImage.apply(context, [source].concat(_toConsumableArray(params.map(function (param) {
4594 return Math.floor(normalizeDecimalNumber(param));
4595 }))));
4596 return canvas;
4597 },
4598 /**
4599 * Change the aspect ratio of the crop box.
4600 * @param {number} aspectRatio - The new aspect ratio.
4601 * @returns {Cropper} this
4602 */
4603 setAspectRatio: function setAspectRatio(aspectRatio) {
4604 var options = this.options;
4605 if (!this.disabled && !isUndefined(aspectRatio)) {
4606 // 0 -> NaN
4607 options.aspectRatio = Math.max(0, aspectRatio) || NaN;
4608 if (this.ready) {
4609 this.initCropBox();
4610 if (this.cropped) {
4611 this.renderCropBox();
4612 }
4613 }
4614 }
4615 return this;
4616 },
4617 /**
4618 * Change the drag mode.
4619 * @param {string} mode - The new drag mode.
4620 * @returns {Cropper} this
4621 */
4622 setDragMode: function setDragMode(mode) {
4623 var options = this.options,
4624 dragBox = this.dragBox,
4625 face = this.face;
4626 if (this.ready && !this.disabled) {
4627 var croppable = mode === DRAG_MODE_CROP;
4628 var movable = options.movable && mode === DRAG_MODE_MOVE;
4629 mode = croppable || movable ? mode : DRAG_MODE_NONE;
4630 options.dragMode = mode;
4631 setData(dragBox, DATA_ACTION, mode);
4632 toggleClass(dragBox, CLASS_CROP, croppable);
4633 toggleClass(dragBox, CLASS_MOVE, movable);
4634 if (!options.cropBoxMovable) {
4635 // Sync drag mode to crop box when it is not movable
4636 setData(face, DATA_ACTION, mode);
4637 toggleClass(face, CLASS_CROP, croppable);
4638 toggleClass(face, CLASS_MOVE, movable);
4639 }
4640 }
4641 return this;
4642 }
4643 };
4644
4645 var AnotherCropper = WINDOW.Cropper;
4646 var Cropper = /*#__PURE__*/function () {
4647 /**
4648 * Create a new Cropper.
4649 * @param {Element} element - The target element for cropping.
4650 * @param {Object} [options={}] - The configuration options.
4651 */
4652 function Cropper(element) {
4653 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4654 _classCallCheck(this, Cropper);
4655 if (!element || !REGEXP_TAG_NAME.test(element.tagName)) {
4656 throw new Error('The first argument is required and must be an <img> or <canvas> element.');
4657 }
4658 this.element = element;
4659 this.options = assign({}, DEFAULTS, isPlainObject(options) && options);
4660 this.cropped = false;
4661 this.disabled = false;
4662 this.pointers = {};
4663 this.ready = false;
4664 this.reloading = false;
4665 this.replaced = false;
4666 this.sized = false;
4667 this.sizing = false;
4668 this.init();
4669 }
4670 return _createClass(Cropper, [{
4671 key: "init",
4672 value: function init() {
4673 var element = this.element;
4674 var tagName = element.tagName.toLowerCase();
4675 var url;
4676 if (element[NAMESPACE]) {
4677 return;
4678 }
4679 element[NAMESPACE] = this;
4680 if (tagName === 'img') {
4681 this.isImg = true;
4682
4683 // e.g.: "img/picture.jpg"
4684 url = element.getAttribute('src') || '';
4685 this.originalUrl = url;
4686
4687 // Stop when it's a blank image
4688 if (!url) {
4689 return;
4690 }
4691
4692 // e.g.: "https://example.com/img/picture.jpg"
4693 url = element.src;
4694 } else if (tagName === 'canvas' && window.HTMLCanvasElement) {
4695 url = element.toDataURL();
4696 }
4697 this.load(url);
4698 }
4699 }, {
4700 key: "load",
4701 value: function load(url) {
4702 var _this = this;
4703 if (!url) {
4704 return;
4705 }
4706 this.url = url;
4707 this.imageData = {};
4708 var element = this.element,
4709 options = this.options;
4710 if (!options.rotatable && !options.scalable) {
4711 options.checkOrientation = false;
4712 }
4713
4714 // Only IE10+ supports Typed Arrays
4715 if (!options.checkOrientation || !window.ArrayBuffer) {
4716 this.clone();
4717 return;
4718 }
4719
4720 // Detect the mime type of the image directly if it is a Data URL
4721 if (REGEXP_DATA_URL.test(url)) {
4722 // Read ArrayBuffer from Data URL of JPEG images directly for better performance
4723 if (REGEXP_DATA_URL_JPEG.test(url)) {
4724 this.read(dataURLToArrayBuffer(url));
4725 } else {
4726 // Only a JPEG image may contains Exif Orientation information,
4727 // the rest types of Data URLs are not necessary to check orientation at all.
4728 this.clone();
4729 }
4730 return;
4731 }
4732
4733 // 1. Detect the mime type of the image by a XMLHttpRequest.
4734 // 2. Load the image as ArrayBuffer for reading orientation if its a JPEG image.
4735 var xhr = new XMLHttpRequest();
4736 var clone = this.clone.bind(this);
4737 this.reloading = true;
4738 this.xhr = xhr;
4739
4740 // 1. Cross origin requests are only supported for protocol schemes:
4741 // http, https, data, chrome, chrome-extension.
4742 // 2. Access to XMLHttpRequest from a Data URL will be blocked by CORS policy
4743 // in some browsers as IE11 and Safari.
4744 xhr.onabort = clone;
4745 xhr.onerror = clone;
4746 xhr.ontimeout = clone;
4747 xhr.onprogress = function () {
4748 // Abort the request directly if it not a JPEG image for better performance
4749 if (xhr.getResponseHeader('content-type') !== MIME_TYPE_JPEG) {
4750 xhr.abort();
4751 }
4752 };
4753 xhr.onload = function () {
4754 _this.read(xhr.response);
4755 };
4756 xhr.onloadend = function () {
4757 _this.reloading = false;
4758 _this.xhr = null;
4759 };
4760
4761 // Bust cache when there is a "crossOrigin" property to avoid browser cache error
4762 if (options.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) {
4763 url = addTimestamp(url);
4764 }
4765
4766 // The third parameter is required for avoiding side-effect (#682)
4767 xhr.open('GET', url, true);
4768 xhr.responseType = 'arraybuffer';
4769 xhr.withCredentials = element.crossOrigin === 'use-credentials';
4770 xhr.send();
4771 }
4772 }, {
4773 key: "read",
4774 value: function read(arrayBuffer) {
4775 var options = this.options,
4776 imageData = this.imageData;
4777
4778 // Reset the orientation value to its default value 1
4779 // as some iOS browsers will render image with its orientation
4780 var orientation = resetAndGetOrientation(arrayBuffer);
4781 var rotate = 0;
4782 var scaleX = 1;
4783 var scaleY = 1;
4784 if (orientation > 1) {
4785 // Generate a new URL which has the default orientation value
4786 this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG);
4787 var _parseOrientation = parseOrientation(orientation);
4788 rotate = _parseOrientation.rotate;
4789 scaleX = _parseOrientation.scaleX;
4790 scaleY = _parseOrientation.scaleY;
4791 }
4792 if (options.rotatable) {
4793 imageData.rotate = rotate;
4794 }
4795 if (options.scalable) {
4796 imageData.scaleX = scaleX;
4797 imageData.scaleY = scaleY;
4798 }
4799 this.clone();
4800 }
4801 }, {
4802 key: "clone",
4803 value: function clone() {
4804 var element = this.element,
4805 url = this.url;
4806 var crossOrigin = element.crossOrigin;
4807 var crossOriginUrl = url;
4808 if (this.options.checkCrossOrigin && isCrossOriginURL(url)) {
4809 if (!crossOrigin) {
4810 crossOrigin = 'anonymous';
4811 }
4812
4813 // Bust cache when there is not a "crossOrigin" property (#519)
4814 crossOriginUrl = addTimestamp(url);
4815 }
4816 this.crossOrigin = crossOrigin;
4817 this.crossOriginUrl = crossOriginUrl;
4818 var image = document.createElement('img');
4819 if (crossOrigin) {
4820 image.crossOrigin = crossOrigin;
4821 }
4822 image.src = crossOriginUrl || url;
4823 image.alt = element.alt || 'The image to crop';
4824 this.image = image;
4825 image.onload = this.start.bind(this);
4826 image.onerror = this.stop.bind(this);
4827 addClass(image, CLASS_HIDE);
4828 element.parentNode.insertBefore(image, element.nextSibling);
4829 }
4830 }, {
4831 key: "start",
4832 value: function start() {
4833 var _this2 = this;
4834 var image = this.image;
4835 image.onload = null;
4836 image.onerror = null;
4837 this.sizing = true;
4838
4839 // Match all browsers that use WebKit as the layout engine in iOS devices,
4840 // such as Safari for iOS, Chrome for iOS, and in-app browsers.
4841 var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent);
4842 var done = function done(naturalWidth, naturalHeight) {
4843 assign(_this2.imageData, {
4844 naturalWidth: naturalWidth,
4845 naturalHeight: naturalHeight,
4846 aspectRatio: naturalWidth / naturalHeight
4847 });
4848 _this2.initialImageData = assign({}, _this2.imageData);
4849 _this2.sizing = false;
4850 _this2.sized = true;
4851 _this2.build();
4852 };
4853
4854 // Most modern browsers (excepts iOS WebKit)
4855 if (image.naturalWidth && !isIOSWebKit) {
4856 done(image.naturalWidth, image.naturalHeight);
4857 return;
4858 }
4859 var sizingImage = document.createElement('img');
4860 var body = document.body || document.documentElement;
4861 this.sizingImage = sizingImage;
4862 sizingImage.onload = function () {
4863 done(sizingImage.width, sizingImage.height);
4864 if (!isIOSWebKit) {
4865 body.removeChild(sizingImage);
4866 }
4867 };
4868 sizingImage.src = image.src;
4869
4870 // iOS WebKit will convert the image automatically
4871 // with its orientation once append it into DOM (#279)
4872 if (!isIOSWebKit) {
4873 sizingImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';
4874 body.appendChild(sizingImage);
4875 }
4876 }
4877 }, {
4878 key: "stop",
4879 value: function stop() {
4880 var image = this.image;
4881 image.onload = null;
4882 image.onerror = null;
4883 image.parentNode.removeChild(image);
4884 this.image = null;
4885 }
4886 }, {
4887 key: "build",
4888 value: function build() {
4889 if (!this.sized || this.ready) {
4890 return;
4891 }
4892 var element = this.element,
4893 options = this.options,
4894 image = this.image;
4895
4896 // Create cropper elements
4897 var container = element.parentNode;
4898 var template = document.createElement('div');
4899 template.innerHTML = TEMPLATE;
4900 var cropper = template.querySelector(".".concat(NAMESPACE, "-container"));
4901 var canvas = cropper.querySelector(".".concat(NAMESPACE, "-canvas"));
4902 var dragBox = cropper.querySelector(".".concat(NAMESPACE, "-drag-box"));
4903 var cropBox = cropper.querySelector(".".concat(NAMESPACE, "-crop-box"));
4904 var face = cropBox.querySelector(".".concat(NAMESPACE, "-face"));
4905 this.container = container;
4906 this.cropper = cropper;
4907 this.canvas = canvas;
4908 this.dragBox = dragBox;
4909 this.cropBox = cropBox;
4910 this.viewBox = cropper.querySelector(".".concat(NAMESPACE, "-view-box"));
4911 this.face = face;
4912 canvas.appendChild(image);
4913
4914 // Hide the original image
4915 addClass(element, CLASS_HIDDEN);
4916
4917 // Inserts the cropper after to the current image
4918 container.insertBefore(cropper, element.nextSibling);
4919
4920 // Show the hidden image
4921 removeClass(image, CLASS_HIDE);
4922 this.initPreview();
4923 this.bind();
4924 options.initialAspectRatio = Math.max(0, options.initialAspectRatio) || NaN;
4925 options.aspectRatio = Math.max(0, options.aspectRatio) || NaN;
4926 options.viewMode = Math.max(0, Math.min(3, Math.round(options.viewMode))) || 0;
4927 addClass(cropBox, CLASS_HIDDEN);
4928 if (!options.guides) {
4929 addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-dashed")), CLASS_HIDDEN);
4930 }
4931 if (!options.center) {
4932 addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-center")), CLASS_HIDDEN);
4933 }
4934 if (options.background) {
4935 addClass(cropper, "".concat(NAMESPACE, "-bg"));
4936 }
4937 if (!options.highlight) {
4938 addClass(face, CLASS_INVISIBLE);
4939 }
4940 if (options.cropBoxMovable) {
4941 addClass(face, CLASS_MOVE);
4942 setData(face, DATA_ACTION, ACTION_ALL);
4943 }
4944 if (!options.cropBoxResizable) {
4945 addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-line")), CLASS_HIDDEN);
4946 addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-point")), CLASS_HIDDEN);
4947 }
4948 this.render();
4949 this.ready = true;
4950 this.setDragMode(options.dragMode);
4951 if (options.autoCrop) {
4952 this.crop();
4953 }
4954 this.setData(options.data);
4955 if (isFunction(options.ready)) {
4956 addListener(element, EVENT_READY, options.ready, {
4957 once: true
4958 });
4959 }
4960 dispatchEvent(element, EVENT_READY);
4961 }
4962 }, {
4963 key: "unbuild",
4964 value: function unbuild() {
4965 if (!this.ready) {
4966 return;
4967 }
4968 this.ready = false;
4969 this.unbind();
4970 this.resetPreview();
4971 var parentNode = this.cropper.parentNode;
4972 if (parentNode) {
4973 parentNode.removeChild(this.cropper);
4974 }
4975 removeClass(this.element, CLASS_HIDDEN);
4976 }
4977 }, {
4978 key: "uncreate",
4979 value: function uncreate() {
4980 if (this.ready) {
4981 this.unbuild();
4982 this.ready = false;
4983 this.cropped = false;
4984 } else if (this.sizing) {
4985 this.sizingImage.onload = null;
4986 this.sizing = false;
4987 this.sized = false;
4988 } else if (this.reloading) {
4989 this.xhr.onabort = null;
4990 this.xhr.abort();
4991 } else if (this.image) {
4992 this.stop();
4993 }
4994 }
4995
4996 /**
4997 * Get the no conflict cropper class.
4998 * @returns {Cropper} The cropper class.
4999 */
5000 }], [{
5001 key: "noConflict",
5002 value: function noConflict() {
5003 window.Cropper = AnotherCropper;
5004 return Cropper;
5005 }
5006
5007 /**
5008 * Change the default options.
5009 * @param {Object} options - The new default options.
5010 */
5011 }, {
5012 key: "setDefaults",
5013 value: function setDefaults(options) {
5014 assign(DEFAULTS, isPlainObject(options) && options);
5015 }
5016 }]);
5017 }();
5018 assign(Cropper.prototype, render, preview, events, handlers, change, methods);
5019
5020 return Cropper;
5021
5022 }));
5023
5024
5025 /***/ },
5026
5027 /***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/cropperjs/dist/cropper.css"
5028 /*!***************************************************************************************!*\
5029 !*** ./node_modules/css-loader/dist/cjs.js!./node_modules/cropperjs/dist/cropper.css ***!
5030 \***************************************************************************************/
5031 (module, __webpack_exports__, __webpack_require__) {
5032
5033 "use strict";
5034 __webpack_require__.r(__webpack_exports__);
5035 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5036 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
5037 /* harmony export */ });
5038 /* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../css-loader/dist/runtime/sourceMaps.js */ "./node_modules/css-loader/dist/runtime/sourceMaps.js");
5039 /* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
5040 /* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../css-loader/dist/runtime/api.js */ "./node_modules/css-loader/dist/runtime/api.js");
5041 /* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
5042 /* harmony import */ var _css_loader_dist_runtime_getUrl_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../css-loader/dist/runtime/getUrl.js */ "./node_modules/css-loader/dist/runtime/getUrl.js");
5043 /* harmony import */ var _css_loader_dist_runtime_getUrl_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_getUrl_js__WEBPACK_IMPORTED_MODULE_2__);
5044 // Imports
5045
5046
5047
5048 var ___CSS_LOADER_URL_IMPORT_0___ = new URL(/* asset import */ __webpack_require__(/*! data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC */ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC"), __webpack_require__.b);
5049 var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
5050 var ___CSS_LOADER_URL_REPLACEMENT_0___ = _css_loader_dist_runtime_getUrl_js__WEBPACK_IMPORTED_MODULE_2___default()(___CSS_LOADER_URL_IMPORT_0___);
5051 // Module
5052 ___CSS_LOADER_EXPORT___.push([module.id, `/*!
5053 * Cropper.js v1.6.2
5054 * https://fengyuanchen.github.io/cropperjs
5055 *
5056 * Copyright 2015-present Chen Fengyuan
5057 * Released under the MIT license
5058 *
5059 * Date: 2024-04-21T07:43:02.731Z
5060 */
5061
5062 .cropper-container {
5063 direction: ltr;
5064 font-size: 0;
5065 line-height: 0;
5066 position: relative;
5067 -ms-touch-action: none;
5068 touch-action: none;
5069 -webkit-touch-callout: none;
5070 -webkit-user-select: none;
5071 -moz-user-select: none;
5072 -ms-user-select: none;
5073 user-select: none;
5074 }
5075
5076 .cropper-container img {
5077 backface-visibility: hidden;
5078 display: block;
5079 height: 100%;
5080 image-orientation: 0deg;
5081 max-height: none !important;
5082 max-width: none !important;
5083 min-height: 0 !important;
5084 min-width: 0 !important;
5085 width: 100%;
5086 }
5087
5088 .cropper-wrap-box,
5089 .cropper-canvas,
5090 .cropper-drag-box,
5091 .cropper-crop-box,
5092 .cropper-modal {
5093 bottom: 0;
5094 left: 0;
5095 position: absolute;
5096 right: 0;
5097 top: 0;
5098 }
5099
5100 .cropper-wrap-box,
5101 .cropper-canvas {
5102 overflow: hidden;
5103 }
5104
5105 .cropper-drag-box {
5106 background-color: #fff;
5107 opacity: 0;
5108 }
5109
5110 .cropper-modal {
5111 background-color: #000;
5112 opacity: 0.5;
5113 }
5114
5115 .cropper-view-box {
5116 display: block;
5117 height: 100%;
5118 outline: 1px solid #39f;
5119 outline-color: rgba(51, 153, 255, 0.75);
5120 overflow: hidden;
5121 width: 100%;
5122 }
5123
5124 .cropper-dashed {
5125 border: 0 dashed #eee;
5126 display: block;
5127 opacity: 0.5;
5128 position: absolute;
5129 }
5130
5131 .cropper-dashed.dashed-h {
5132 border-bottom-width: 1px;
5133 border-top-width: 1px;
5134 height: calc(100% / 3);
5135 left: 0;
5136 top: calc(100% / 3);
5137 width: 100%;
5138 }
5139
5140 .cropper-dashed.dashed-v {
5141 border-left-width: 1px;
5142 border-right-width: 1px;
5143 height: 100%;
5144 left: calc(100% / 3);
5145 top: 0;
5146 width: calc(100% / 3);
5147 }
5148
5149 .cropper-center {
5150 display: block;
5151 height: 0;
5152 left: 50%;
5153 opacity: 0.75;
5154 position: absolute;
5155 top: 50%;
5156 width: 0;
5157 }
5158
5159 .cropper-center::before,
5160 .cropper-center::after {
5161 background-color: #eee;
5162 content: ' ';
5163 display: block;
5164 position: absolute;
5165 }
5166
5167 .cropper-center::before {
5168 height: 1px;
5169 left: -3px;
5170 top: 0;
5171 width: 7px;
5172 }
5173
5174 .cropper-center::after {
5175 height: 7px;
5176 left: 0;
5177 top: -3px;
5178 width: 1px;
5179 }
5180
5181 .cropper-face,
5182 .cropper-line,
5183 .cropper-point {
5184 display: block;
5185 height: 100%;
5186 opacity: 0.1;
5187 position: absolute;
5188 width: 100%;
5189 }
5190
5191 .cropper-face {
5192 background-color: #fff;
5193 left: 0;
5194 top: 0;
5195 }
5196
5197 .cropper-line {
5198 background-color: #39f;
5199 }
5200
5201 .cropper-line.line-e {
5202 cursor: ew-resize;
5203 right: -3px;
5204 top: 0;
5205 width: 5px;
5206 }
5207
5208 .cropper-line.line-n {
5209 cursor: ns-resize;
5210 height: 5px;
5211 left: 0;
5212 top: -3px;
5213 }
5214
5215 .cropper-line.line-w {
5216 cursor: ew-resize;
5217 left: -3px;
5218 top: 0;
5219 width: 5px;
5220 }
5221
5222 .cropper-line.line-s {
5223 bottom: -3px;
5224 cursor: ns-resize;
5225 height: 5px;
5226 left: 0;
5227 }
5228
5229 .cropper-point {
5230 background-color: #39f;
5231 height: 5px;
5232 opacity: 0.75;
5233 width: 5px;
5234 }
5235
5236 .cropper-point.point-e {
5237 cursor: ew-resize;
5238 margin-top: -3px;
5239 right: -3px;
5240 top: 50%;
5241 }
5242
5243 .cropper-point.point-n {
5244 cursor: ns-resize;
5245 left: 50%;
5246 margin-left: -3px;
5247 top: -3px;
5248 }
5249
5250 .cropper-point.point-w {
5251 cursor: ew-resize;
5252 left: -3px;
5253 margin-top: -3px;
5254 top: 50%;
5255 }
5256
5257 .cropper-point.point-s {
5258 bottom: -3px;
5259 cursor: s-resize;
5260 left: 50%;
5261 margin-left: -3px;
5262 }
5263
5264 .cropper-point.point-ne {
5265 cursor: nesw-resize;
5266 right: -3px;
5267 top: -3px;
5268 }
5269
5270 .cropper-point.point-nw {
5271 cursor: nwse-resize;
5272 left: -3px;
5273 top: -3px;
5274 }
5275
5276 .cropper-point.point-sw {
5277 bottom: -3px;
5278 cursor: nesw-resize;
5279 left: -3px;
5280 }
5281
5282 .cropper-point.point-se {
5283 bottom: -3px;
5284 cursor: nwse-resize;
5285 height: 20px;
5286 opacity: 1;
5287 right: -3px;
5288 width: 20px;
5289 }
5290
5291 @media (min-width: 768px) {
5292
5293 .cropper-point.point-se {
5294 height: 15px;
5295 width: 15px;
5296 }
5297 }
5298
5299 @media (min-width: 992px) {
5300
5301 .cropper-point.point-se {
5302 height: 10px;
5303 width: 10px;
5304 }
5305 }
5306
5307 @media (min-width: 1200px) {
5308
5309 .cropper-point.point-se {
5310 height: 5px;
5311 opacity: 0.75;
5312 width: 5px;
5313 }
5314 }
5315
5316 .cropper-point.point-se::before {
5317 background-color: #39f;
5318 bottom: -50%;
5319 content: ' ';
5320 display: block;
5321 height: 200%;
5322 opacity: 0;
5323 position: absolute;
5324 right: -50%;
5325 width: 200%;
5326 }
5327
5328 .cropper-invisible {
5329 opacity: 0;
5330 }
5331
5332 .cropper-bg {
5333 background-image: url(${___CSS_LOADER_URL_REPLACEMENT_0___});
5334 }
5335
5336 .cropper-hide {
5337 display: block;
5338 height: 0;
5339 position: absolute;
5340 width: 0;
5341 }
5342
5343 .cropper-hidden {
5344 display: none !important;
5345 }
5346
5347 .cropper-move {
5348 cursor: move;
5349 }
5350
5351 .cropper-crop {
5352 cursor: crosshair;
5353 }
5354
5355 .cropper-disabled .cropper-drag-box,
5356 .cropper-disabled .cropper-face,
5357 .cropper-disabled .cropper-line,
5358 .cropper-disabled .cropper-point {
5359 cursor: not-allowed;
5360 }
5361 `, "",{"version":3,"sources":["webpack://./node_modules/cropperjs/dist/cropper.css"],"names":[],"mappings":"AAAA;;;;;;;;EAQE;;AAEF;EACE,cAAc;EACd,YAAY;EACZ,cAAc;EACd,kBAAkB;EAClB,sBAAsB;MAClB,kBAAkB;EACtB,2BAA2B;EAC3B,yBAAyB;KACtB,sBAAsB;MACrB,qBAAqB;UACjB,iBAAiB;AAC3B;;AAEA;IACI,2BAA2B;IAC3B,cAAc;IACd,YAAY;IACZ,uBAAuB;IACvB,2BAA2B;IAC3B,0BAA0B;IAC1B,wBAAwB;IACxB,uBAAuB;IACvB,WAAW;EACb;;AAEF;;;;;EAKE,SAAS;EACT,OAAO;EACP,kBAAkB;EAClB,QAAQ;EACR,MAAM;AACR;;AAEA;;EAEE,gBAAgB;AAClB;;AAEA;EACE,sBAAsB;EACtB,UAAU;AACZ;;AAEA;EACE,sBAAsB;EACtB,YAAY;AACd;;AAEA;EACE,cAAc;EACd,YAAY;EACZ,uBAAuB;EACvB,uCAAuC;EACvC,gBAAgB;EAChB,WAAW;AACb;;AAEA;EACE,qBAAqB;EACrB,cAAc;EACd,YAAY;EACZ,kBAAkB;AACpB;;AAEA;IACI,wBAAwB;IACxB,qBAAqB;IACrB,sBAAsB;IACtB,OAAO;IACP,mBAAmB;IACnB,WAAW;EACb;;AAEF;IACI,sBAAsB;IACtB,uBAAuB;IACvB,YAAY;IACZ,oBAAoB;IACpB,MAAM;IACN,qBAAqB;EACvB;;AAEF;EACE,cAAc;EACd,SAAS;EACT,SAAS;EACT,aAAa;EACb,kBAAkB;EAClB,QAAQ;EACR,QAAQ;AACV;;AAEA;;IAEI,sBAAsB;IACtB,YAAY;IACZ,cAAc;IACd,kBAAkB;EACpB;;AAEF;IACI,WAAW;IACX,UAAU;IACV,MAAM;IACN,UAAU;EACZ;;AAEF;IACI,WAAW;IACX,OAAO;IACP,SAAS;IACT,UAAU;EACZ;;AAEF;;;EAGE,cAAc;EACd,YAAY;EACZ,YAAY;EACZ,kBAAkB;EAClB,WAAW;AACb;;AAEA;EACE,sBAAsB;EACtB,OAAO;EACP,MAAM;AACR;;AAEA;EACE,sBAAsB;AACxB;;AAEA;IACI,iBAAiB;IACjB,WAAW;IACX,MAAM;IACN,UAAU;EACZ;;AAEF;IACI,iBAAiB;IACjB,WAAW;IACX,OAAO;IACP,SAAS;EACX;;AAEF;IACI,iBAAiB;IACjB,UAAU;IACV,MAAM;IACN,UAAU;EACZ;;AAEF;IACI,YAAY;IACZ,iBAAiB;IACjB,WAAW;IACX,OAAO;EACT;;AAEF;EACE,sBAAsB;EACtB,WAAW;EACX,aAAa;EACb,UAAU;AACZ;;AAEA;IACI,iBAAiB;IACjB,gBAAgB;IAChB,WAAW;IACX,QAAQ;EACV;;AAEF;IACI,iBAAiB;IACjB,SAAS;IACT,iBAAiB;IACjB,SAAS;EACX;;AAEF;IACI,iBAAiB;IACjB,UAAU;IACV,gBAAgB;IAChB,QAAQ;EACV;;AAEF;IACI,YAAY;IACZ,gBAAgB;IAChB,SAAS;IACT,iBAAiB;EACnB;;AAEF;IACI,mBAAmB;IACnB,WAAW;IACX,SAAS;EACX;;AAEF;IACI,mBAAmB;IACnB,UAAU;IACV,SAAS;EACX;;AAEF;IACI,YAAY;IACZ,mBAAmB;IACnB,UAAU;EACZ;;AAEF;IACI,YAAY;IACZ,mBAAmB;IACnB,YAAY;IACZ,UAAU;IACV,WAAW;IACX,WAAW;EACb;;AAEF;;AAEA;MACM,YAAY;MACZ,WAAW;EACf;IACE;;AAEJ;;AAEA;MACM,YAAY;MACZ,WAAW;EACf;IACE;;AAEJ;;AAEA;MACM,WAAW;MACX,aAAa;MACb,UAAU;EACd;IACE;;AAEJ;IACI,sBAAsB;IACtB,YAAY;IACZ,YAAY;IACZ,cAAc;IACd,YAAY;IACZ,UAAU;IACV,kBAAkB;IAClB,WAAW;IACX,WAAW;EACb;;AAEF;EACE,UAAU;AACZ;;AAEA;EACE,yDAA+Q;AACjR;;AAEA;EACE,cAAc;EACd,SAAS;EACT,kBAAkB;EAClB,QAAQ;AACV;;AAEA;EACE,wBAAwB;AAC1B;;AAEA;EACE,YAAY;AACd;;AAEA;EACE,iBAAiB;AACnB;;AAEA;;;;EAIE,mBAAmB;AACrB","sourcesContent":["/*!\n * Cropper.js v1.6.2\n * https://fengyuanchen.github.io/cropperjs\n *\n * Copyright 2015-present Chen Fengyuan\n * Released under the MIT license\n *\n * Date: 2024-04-21T07:43:02.731Z\n */\n\n.cropper-container {\n direction: ltr;\n font-size: 0;\n line-height: 0;\n position: relative;\n -ms-touch-action: none;\n touch-action: none;\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n\n.cropper-container img {\n backface-visibility: hidden;\n display: block;\n height: 100%;\n image-orientation: 0deg;\n max-height: none !important;\n max-width: none !important;\n min-height: 0 !important;\n min-width: 0 !important;\n width: 100%;\n }\n\n.cropper-wrap-box,\n.cropper-canvas,\n.cropper-drag-box,\n.cropper-crop-box,\n.cropper-modal {\n bottom: 0;\n left: 0;\n position: absolute;\n right: 0;\n top: 0;\n}\n\n.cropper-wrap-box,\n.cropper-canvas {\n overflow: hidden;\n}\n\n.cropper-drag-box {\n background-color: #fff;\n opacity: 0;\n}\n\n.cropper-modal {\n background-color: #000;\n opacity: 0.5;\n}\n\n.cropper-view-box {\n display: block;\n height: 100%;\n outline: 1px solid #39f;\n outline-color: rgba(51, 153, 255, 0.75);\n overflow: hidden;\n width: 100%;\n}\n\n.cropper-dashed {\n border: 0 dashed #eee;\n display: block;\n opacity: 0.5;\n position: absolute;\n}\n\n.cropper-dashed.dashed-h {\n border-bottom-width: 1px;\n border-top-width: 1px;\n height: calc(100% / 3);\n left: 0;\n top: calc(100% / 3);\n width: 100%;\n }\n\n.cropper-dashed.dashed-v {\n border-left-width: 1px;\n border-right-width: 1px;\n height: 100%;\n left: calc(100% / 3);\n top: 0;\n width: calc(100% / 3);\n }\n\n.cropper-center {\n display: block;\n height: 0;\n left: 50%;\n opacity: 0.75;\n position: absolute;\n top: 50%;\n width: 0;\n}\n\n.cropper-center::before,\n .cropper-center::after {\n background-color: #eee;\n content: ' ';\n display: block;\n position: absolute;\n }\n\n.cropper-center::before {\n height: 1px;\n left: -3px;\n top: 0;\n width: 7px;\n }\n\n.cropper-center::after {\n height: 7px;\n left: 0;\n top: -3px;\n width: 1px;\n }\n\n.cropper-face,\n.cropper-line,\n.cropper-point {\n display: block;\n height: 100%;\n opacity: 0.1;\n position: absolute;\n width: 100%;\n}\n\n.cropper-face {\n background-color: #fff;\n left: 0;\n top: 0;\n}\n\n.cropper-line {\n background-color: #39f;\n}\n\n.cropper-line.line-e {\n cursor: ew-resize;\n right: -3px;\n top: 0;\n width: 5px;\n }\n\n.cropper-line.line-n {\n cursor: ns-resize;\n height: 5px;\n left: 0;\n top: -3px;\n }\n\n.cropper-line.line-w {\n cursor: ew-resize;\n left: -3px;\n top: 0;\n width: 5px;\n }\n\n.cropper-line.line-s {\n bottom: -3px;\n cursor: ns-resize;\n height: 5px;\n left: 0;\n }\n\n.cropper-point {\n background-color: #39f;\n height: 5px;\n opacity: 0.75;\n width: 5px;\n}\n\n.cropper-point.point-e {\n cursor: ew-resize;\n margin-top: -3px;\n right: -3px;\n top: 50%;\n }\n\n.cropper-point.point-n {\n cursor: ns-resize;\n left: 50%;\n margin-left: -3px;\n top: -3px;\n }\n\n.cropper-point.point-w {\n cursor: ew-resize;\n left: -3px;\n margin-top: -3px;\n top: 50%;\n }\n\n.cropper-point.point-s {\n bottom: -3px;\n cursor: s-resize;\n left: 50%;\n margin-left: -3px;\n }\n\n.cropper-point.point-ne {\n cursor: nesw-resize;\n right: -3px;\n top: -3px;\n }\n\n.cropper-point.point-nw {\n cursor: nwse-resize;\n left: -3px;\n top: -3px;\n }\n\n.cropper-point.point-sw {\n bottom: -3px;\n cursor: nesw-resize;\n left: -3px;\n }\n\n.cropper-point.point-se {\n bottom: -3px;\n cursor: nwse-resize;\n height: 20px;\n opacity: 1;\n right: -3px;\n width: 20px;\n }\n\n@media (min-width: 768px) {\n\n.cropper-point.point-se {\n height: 15px;\n width: 15px;\n }\n }\n\n@media (min-width: 992px) {\n\n.cropper-point.point-se {\n height: 10px;\n width: 10px;\n }\n }\n\n@media (min-width: 1200px) {\n\n.cropper-point.point-se {\n height: 5px;\n opacity: 0.75;\n width: 5px;\n }\n }\n\n.cropper-point.point-se::before {\n background-color: #39f;\n bottom: -50%;\n content: ' ';\n display: block;\n height: 200%;\n opacity: 0;\n position: absolute;\n right: -50%;\n width: 200%;\n }\n\n.cropper-invisible {\n opacity: 0;\n}\n\n.cropper-bg {\n background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC');\n}\n\n.cropper-hide {\n display: block;\n height: 0;\n position: absolute;\n width: 0;\n}\n\n.cropper-hidden {\n display: none !important;\n}\n\n.cropper-move {\n cursor: move;\n}\n\n.cropper-crop {\n cursor: crosshair;\n}\n\n.cropper-disabled .cropper-drag-box,\n.cropper-disabled .cropper-face,\n.cropper-disabled .cropper-line,\n.cropper-disabled .cropper-point {\n cursor: not-allowed;\n}\n"],"sourceRoot":""}]);
5362 // Exports
5363 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);
5364
5365
5366 /***/ },
5367
5368 /***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/toastify-js/src/toastify.css"
5369 /*!*****************************************************************************************!*\
5370 !*** ./node_modules/css-loader/dist/cjs.js!./node_modules/toastify-js/src/toastify.css ***!
5371 \*****************************************************************************************/
5372 (module, __webpack_exports__, __webpack_require__) {
5373
5374 "use strict";
5375 __webpack_require__.r(__webpack_exports__);
5376 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5377 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
5378 /* harmony export */ });
5379 /* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../css-loader/dist/runtime/sourceMaps.js */ "./node_modules/css-loader/dist/runtime/sourceMaps.js");
5380 /* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
5381 /* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../css-loader/dist/runtime/api.js */ "./node_modules/css-loader/dist/runtime/api.js");
5382 /* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
5383 // Imports
5384
5385
5386 var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
5387 // Module
5388 ___CSS_LOADER_EXPORT___.push([module.id, `/*!
5389 * Toastify js 1.12.0
5390 * https://github.com/apvarun/toastify-js
5391 * @license MIT licensed
5392 *
5393 * Copyright (C) 2018 Varun A P
5394 */
5395
5396 .toastify {
5397 padding: 12px 20px;
5398 color: #ffffff;
5399 display: inline-block;
5400 box-shadow: 0 3px 6px -1px rgba(0, 0, 0, 0.12), 0 10px 36px -4px rgba(77, 96, 232, 0.3);
5401 background: -webkit-linear-gradient(315deg, #73a5ff, #5477f5);
5402 background: linear-gradient(135deg, #73a5ff, #5477f5);
5403 position: fixed;
5404 opacity: 0;
5405 transition: all 0.4s cubic-bezier(0.215, 0.61, 0.355, 1);
5406 border-radius: 2px;
5407 cursor: pointer;
5408 text-decoration: none;
5409 max-width: calc(50% - 20px);
5410 z-index: 2147483647;
5411 }
5412
5413 .toastify.on {
5414 opacity: 1;
5415 }
5416
5417 .toast-close {
5418 background: transparent;
5419 border: 0;
5420 color: white;
5421 cursor: pointer;
5422 font-family: inherit;
5423 font-size: 1em;
5424 opacity: 0.4;
5425 padding: 0 5px;
5426 }
5427
5428 .toastify-right {
5429 right: 15px;
5430 }
5431
5432 .toastify-left {
5433 left: 15px;
5434 }
5435
5436 .toastify-top {
5437 top: -150px;
5438 }
5439
5440 .toastify-bottom {
5441 bottom: -150px;
5442 }
5443
5444 .toastify-rounded {
5445 border-radius: 25px;
5446 }
5447
5448 .toastify-avatar {
5449 width: 1.5em;
5450 height: 1.5em;
5451 margin: -7px 5px;
5452 border-radius: 2px;
5453 }
5454
5455 .toastify-center {
5456 margin-left: auto;
5457 margin-right: auto;
5458 left: 0;
5459 right: 0;
5460 max-width: fit-content;
5461 max-width: -moz-fit-content;
5462 }
5463
5464 @media only screen and (max-width: 360px) {
5465 .toastify-right, .toastify-left {
5466 margin-left: auto;
5467 margin-right: auto;
5468 left: 0;
5469 right: 0;
5470 max-width: fit-content;
5471 }
5472 }
5473 `, "",{"version":3,"sources":["webpack://./node_modules/toastify-js/src/toastify.css"],"names":[],"mappings":"AAAA;;;;;;EAME;;AAEF;IACI,kBAAkB;IAClB,cAAc;IACd,qBAAqB;IACrB,uFAAuF;IACvF,6DAA6D;IAC7D,qDAAqD;IACrD,eAAe;IACf,UAAU;IACV,wDAAwD;IACxD,kBAAkB;IAClB,eAAe;IACf,qBAAqB;IACrB,2BAA2B;IAC3B,mBAAmB;AACvB;;AAEA;IACI,UAAU;AACd;;AAEA;IACI,uBAAuB;IACvB,SAAS;IACT,YAAY;IACZ,eAAe;IACf,oBAAoB;IACpB,cAAc;IACd,YAAY;IACZ,cAAc;AAClB;;AAEA;IACI,WAAW;AACf;;AAEA;IACI,UAAU;AACd;;AAEA;IACI,WAAW;AACf;;AAEA;IACI,cAAc;AAClB;;AAEA;IACI,mBAAmB;AACvB;;AAEA;IACI,YAAY;IACZ,aAAa;IACb,gBAAgB;IAChB,kBAAkB;AACtB;;AAEA;IACI,iBAAiB;IACjB,kBAAkB;IAClB,OAAO;IACP,QAAQ;IACR,sBAAsB;IACtB,2BAA2B;AAC/B;;AAEA;IACI;QACI,iBAAiB;QACjB,kBAAkB;QAClB,OAAO;QACP,QAAQ;QACR,sBAAsB;IAC1B;AACJ","sourcesContent":["/*!\n * Toastify js 1.12.0\n * https://github.com/apvarun/toastify-js\n * @license MIT licensed\n *\n * Copyright (C) 2018 Varun A P\n */\n\n.toastify {\n padding: 12px 20px;\n color: #ffffff;\n display: inline-block;\n box-shadow: 0 3px 6px -1px rgba(0, 0, 0, 0.12), 0 10px 36px -4px rgba(77, 96, 232, 0.3);\n background: -webkit-linear-gradient(315deg, #73a5ff, #5477f5);\n background: linear-gradient(135deg, #73a5ff, #5477f5);\n position: fixed;\n opacity: 0;\n transition: all 0.4s cubic-bezier(0.215, 0.61, 0.355, 1);\n border-radius: 2px;\n cursor: pointer;\n text-decoration: none;\n max-width: calc(50% - 20px);\n z-index: 2147483647;\n}\n\n.toastify.on {\n opacity: 1;\n}\n\n.toast-close {\n background: transparent;\n border: 0;\n color: white;\n cursor: pointer;\n font-family: inherit;\n font-size: 1em;\n opacity: 0.4;\n padding: 0 5px;\n}\n\n.toastify-right {\n right: 15px;\n}\n\n.toastify-left {\n left: 15px;\n}\n\n.toastify-top {\n top: -150px;\n}\n\n.toastify-bottom {\n bottom: -150px;\n}\n\n.toastify-rounded {\n border-radius: 25px;\n}\n\n.toastify-avatar {\n width: 1.5em;\n height: 1.5em;\n margin: -7px 5px;\n border-radius: 2px;\n}\n\n.toastify-center {\n margin-left: auto;\n margin-right: auto;\n left: 0;\n right: 0;\n max-width: fit-content;\n max-width: -moz-fit-content;\n}\n\n@media only screen and (max-width: 360px) {\n .toastify-right, .toastify-left {\n margin-left: auto;\n margin-right: auto;\n left: 0;\n right: 0;\n max-width: fit-content;\n }\n}\n"],"sourceRoot":""}]);
5474 // Exports
5475 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);
5476
5477
5478 /***/ },
5479
5480 /***/ "./node_modules/css-loader/dist/runtime/api.js"
5481 /*!*****************************************************!*\
5482 !*** ./node_modules/css-loader/dist/runtime/api.js ***!
5483 \*****************************************************/
5484 (module) {
5485
5486 "use strict";
5487
5488
5489 /*
5490 MIT License http://www.opensource.org/licenses/mit-license.php
5491 Author Tobias Koppers @sokra
5492 */
5493 module.exports = function (cssWithMappingToString) {
5494 var list = [];
5495
5496 // return the list of modules as css string
5497 list.toString = function toString() {
5498 return this.map(function (item) {
5499 var content = "";
5500 var needLayer = typeof item[5] !== "undefined";
5501 if (item[4]) {
5502 content += "@supports (".concat(item[4], ") {");
5503 }
5504 if (item[2]) {
5505 content += "@media ".concat(item[2], " {");
5506 }
5507 if (needLayer) {
5508 content += "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {");
5509 }
5510 content += cssWithMappingToString(item);
5511 if (needLayer) {
5512 content += "}";
5513 }
5514 if (item[2]) {
5515 content += "}";
5516 }
5517 if (item[4]) {
5518 content += "}";
5519 }
5520 return content;
5521 }).join("");
5522 };
5523
5524 // import a list of modules into the list
5525 list.i = function i(modules, media, dedupe, supports, layer) {
5526 if (typeof modules === "string") {
5527 modules = [[null, modules, undefined]];
5528 }
5529 var alreadyImportedModules = {};
5530 if (dedupe) {
5531 for (var k = 0; k < this.length; k++) {
5532 var id = this[k][0];
5533 if (id != null) {
5534 alreadyImportedModules[id] = true;
5535 }
5536 }
5537 }
5538 for (var _k = 0; _k < modules.length; _k++) {
5539 var item = [].concat(modules[_k]);
5540 if (dedupe && alreadyImportedModules[item[0]]) {
5541 continue;
5542 }
5543 if (typeof layer !== "undefined") {
5544 if (typeof item[5] === "undefined") {
5545 item[5] = layer;
5546 } else {
5547 item[1] = "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {").concat(item[1], "}");
5548 item[5] = layer;
5549 }
5550 }
5551 if (media) {
5552 if (!item[2]) {
5553 item[2] = media;
5554 } else {
5555 item[1] = "@media ".concat(item[2], " {").concat(item[1], "}");
5556 item[2] = media;
5557 }
5558 }
5559 if (supports) {
5560 if (!item[4]) {
5561 item[4] = "".concat(supports);
5562 } else {
5563 item[1] = "@supports (".concat(item[4], ") {").concat(item[1], "}");
5564 item[4] = supports;
5565 }
5566 }
5567 list.push(item);
5568 }
5569 };
5570 return list;
5571 };
5572
5573 /***/ },
5574
5575 /***/ "./node_modules/css-loader/dist/runtime/getUrl.js"
5576 /*!********************************************************!*\
5577 !*** ./node_modules/css-loader/dist/runtime/getUrl.js ***!
5578 \********************************************************/
5579 (module) {
5580
5581 "use strict";
5582
5583
5584 module.exports = function (url, options) {
5585 if (!options) {
5586 options = {};
5587 }
5588 if (!url) {
5589 return url;
5590 }
5591 url = String(url.__esModule ? url.default : url);
5592
5593 // If url is already wrapped in quotes, remove them
5594 if (/^['"].*['"]$/.test(url)) {
5595 url = url.slice(1, -1);
5596 }
5597 if (options.hash) {
5598 url += options.hash;
5599 }
5600
5601 // Should url be wrapped?
5602 // See https://drafts.csswg.org/css-values-3/#urls
5603 if (/["'() \t\n]|(%20)/.test(url) || options.needQuotes) {
5604 return "\"".concat(url.replace(/"/g, '\\"').replace(/\n/g, "\\n"), "\"");
5605 }
5606 return url;
5607 };
5608
5609 /***/ },
5610
5611 /***/ "./node_modules/css-loader/dist/runtime/sourceMaps.js"
5612 /*!************************************************************!*\
5613 !*** ./node_modules/css-loader/dist/runtime/sourceMaps.js ***!
5614 \************************************************************/
5615 (module) {
5616
5617 "use strict";
5618
5619
5620 module.exports = function (item) {
5621 var content = item[1];
5622 var cssMapping = item[3];
5623 if (!cssMapping) {
5624 return content;
5625 }
5626 if (typeof btoa === "function") {
5627 var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping))));
5628 var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
5629 var sourceMapping = "/*# ".concat(data, " */");
5630 return [content].concat([sourceMapping]).join("\n");
5631 }
5632 return [content].join("\n");
5633 };
5634
5635 /***/ },
5636
5637 /***/ "./node_modules/cropperjs/dist/cropper.css"
5638 /*!*************************************************!*\
5639 !*** ./node_modules/cropperjs/dist/cropper.css ***!
5640 \*************************************************/
5641 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
5642
5643 "use strict";
5644 __webpack_require__.r(__webpack_exports__);
5645 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5646 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
5647 /* harmony export */ });
5648 /* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../../style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
5649 /* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
5650 /* harmony import */ var _style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !../../style-loader/dist/runtime/styleDomAPI.js */ "./node_modules/style-loader/dist/runtime/styleDomAPI.js");
5651 /* harmony import */ var _style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
5652 /* harmony import */ var _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! !../../style-loader/dist/runtime/insertBySelector.js */ "./node_modules/style-loader/dist/runtime/insertBySelector.js");
5653 /* harmony import */ var _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
5654 /* harmony import */ var _style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! !../../style-loader/dist/runtime/setAttributesWithoutAttributes.js */ "./node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js");
5655 /* harmony import */ var _style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
5656 /* harmony import */ var _style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! !../../style-loader/dist/runtime/insertStyleElement.js */ "./node_modules/style-loader/dist/runtime/insertStyleElement.js");
5657 /* harmony import */ var _style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
5658 /* harmony import */ var _style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! !../../style-loader/dist/runtime/styleTagTransform.js */ "./node_modules/style-loader/dist/runtime/styleTagTransform.js");
5659 /* harmony import */ var _style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
5660 /* harmony import */ var _css_loader_dist_cjs_js_cropper_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! !!../../css-loader/dist/cjs.js!./cropper.css */ "./node_modules/css-loader/dist/cjs.js!./node_modules/cropperjs/dist/cropper.css");
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672 var options = {};
5673
5674 options.styleTagTransform = (_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
5675 options.setAttributes = (_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());
5676
5677 options.insert = _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
5678
5679 options.domAPI = (_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
5680 options.insertStyleElement = (_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());
5681
5682 var update = _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_css_loader_dist_cjs_js_cropper_css__WEBPACK_IMPORTED_MODULE_6__["default"], options);
5683
5684
5685
5686
5687 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_css_loader_dist_cjs_js_cropper_css__WEBPACK_IMPORTED_MODULE_6__["default"] && _css_loader_dist_cjs_js_cropper_css__WEBPACK_IMPORTED_MODULE_6__["default"].locals ? _css_loader_dist_cjs_js_cropper_css__WEBPACK_IMPORTED_MODULE_6__["default"].locals : undefined);
5688
5689
5690 /***/ },
5691
5692 /***/ "./node_modules/toastify-js/src/toastify.css"
5693 /*!***************************************************!*\
5694 !*** ./node_modules/toastify-js/src/toastify.css ***!
5695 \***************************************************/
5696 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
5697
5698 "use strict";
5699 __webpack_require__.r(__webpack_exports__);
5700 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5701 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
5702 /* harmony export */ });
5703 /* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../../style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
5704 /* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
5705 /* harmony import */ var _style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !../../style-loader/dist/runtime/styleDomAPI.js */ "./node_modules/style-loader/dist/runtime/styleDomAPI.js");
5706 /* harmony import */ var _style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
5707 /* harmony import */ var _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! !../../style-loader/dist/runtime/insertBySelector.js */ "./node_modules/style-loader/dist/runtime/insertBySelector.js");
5708 /* harmony import */ var _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
5709 /* harmony import */ var _style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! !../../style-loader/dist/runtime/setAttributesWithoutAttributes.js */ "./node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js");
5710 /* harmony import */ var _style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
5711 /* harmony import */ var _style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! !../../style-loader/dist/runtime/insertStyleElement.js */ "./node_modules/style-loader/dist/runtime/insertStyleElement.js");
5712 /* harmony import */ var _style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
5713 /* harmony import */ var _style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! !../../style-loader/dist/runtime/styleTagTransform.js */ "./node_modules/style-loader/dist/runtime/styleTagTransform.js");
5714 /* harmony import */ var _style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
5715 /* harmony import */ var _css_loader_dist_cjs_js_toastify_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! !!../../css-loader/dist/cjs.js!./toastify.css */ "./node_modules/css-loader/dist/cjs.js!./node_modules/toastify-js/src/toastify.css");
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727 var options = {};
5728
5729 options.styleTagTransform = (_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
5730 options.setAttributes = (_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());
5731
5732 options.insert = _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
5733
5734 options.domAPI = (_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
5735 options.insertStyleElement = (_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());
5736
5737 var update = _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_css_loader_dist_cjs_js_toastify_css__WEBPACK_IMPORTED_MODULE_6__["default"], options);
5738
5739
5740
5741
5742 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_css_loader_dist_cjs_js_toastify_css__WEBPACK_IMPORTED_MODULE_6__["default"] && _css_loader_dist_cjs_js_toastify_css__WEBPACK_IMPORTED_MODULE_6__["default"].locals ? _css_loader_dist_cjs_js_toastify_css__WEBPACK_IMPORTED_MODULE_6__["default"].locals : undefined);
5743
5744
5745 /***/ },
5746
5747 /***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js"
5748 /*!****************************************************************************!*\
5749 !*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
5750 \****************************************************************************/
5751 (module) {
5752
5753 "use strict";
5754
5755
5756 var stylesInDOM = [];
5757 function getIndexByIdentifier(identifier) {
5758 var result = -1;
5759 for (var i = 0; i < stylesInDOM.length; i++) {
5760 if (stylesInDOM[i].identifier === identifier) {
5761 result = i;
5762 break;
5763 }
5764 }
5765 return result;
5766 }
5767 function modulesToDom(list, options) {
5768 var idCountMap = {};
5769 var identifiers = [];
5770 for (var i = 0; i < list.length; i++) {
5771 var item = list[i];
5772 var id = options.base ? item[0] + options.base : item[0];
5773 var count = idCountMap[id] || 0;
5774 var identifier = "".concat(id, " ").concat(count);
5775 idCountMap[id] = count + 1;
5776 var indexByIdentifier = getIndexByIdentifier(identifier);
5777 var obj = {
5778 css: item[1],
5779 media: item[2],
5780 sourceMap: item[3],
5781 supports: item[4],
5782 layer: item[5]
5783 };
5784 if (indexByIdentifier !== -1) {
5785 stylesInDOM[indexByIdentifier].references++;
5786 stylesInDOM[indexByIdentifier].updater(obj);
5787 } else {
5788 var updater = addElementStyle(obj, options);
5789 options.byIndex = i;
5790 stylesInDOM.splice(i, 0, {
5791 identifier: identifier,
5792 updater: updater,
5793 references: 1
5794 });
5795 }
5796 identifiers.push(identifier);
5797 }
5798 return identifiers;
5799 }
5800 function addElementStyle(obj, options) {
5801 var api = options.domAPI(options);
5802 api.update(obj);
5803 var updater = function updater(newObj) {
5804 if (newObj) {
5805 if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap && newObj.supports === obj.supports && newObj.layer === obj.layer) {
5806 return;
5807 }
5808 api.update(obj = newObj);
5809 } else {
5810 api.remove();
5811 }
5812 };
5813 return updater;
5814 }
5815 module.exports = function (list, options) {
5816 options = options || {};
5817 list = list || [];
5818 var lastIdentifiers = modulesToDom(list, options);
5819 return function update(newList) {
5820 newList = newList || [];
5821 for (var i = 0; i < lastIdentifiers.length; i++) {
5822 var identifier = lastIdentifiers[i];
5823 var index = getIndexByIdentifier(identifier);
5824 stylesInDOM[index].references--;
5825 }
5826 var newLastIdentifiers = modulesToDom(newList, options);
5827 for (var _i = 0; _i < lastIdentifiers.length; _i++) {
5828 var _identifier = lastIdentifiers[_i];
5829 var _index = getIndexByIdentifier(_identifier);
5830 if (stylesInDOM[_index].references === 0) {
5831 stylesInDOM[_index].updater();
5832 stylesInDOM.splice(_index, 1);
5833 }
5834 }
5835 lastIdentifiers = newLastIdentifiers;
5836 };
5837 };
5838
5839 /***/ },
5840
5841 /***/ "./node_modules/style-loader/dist/runtime/insertBySelector.js"
5842 /*!********************************************************************!*\
5843 !*** ./node_modules/style-loader/dist/runtime/insertBySelector.js ***!
5844 \********************************************************************/
5845 (module) {
5846
5847 "use strict";
5848
5849
5850 var memo = {};
5851
5852 /* istanbul ignore next */
5853 function getTarget(target) {
5854 if (typeof memo[target] === "undefined") {
5855 var styleTarget = document.querySelector(target);
5856
5857 // Special case to return head of iframe instead of iframe itself
5858 if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
5859 try {
5860 // This will throw an exception if access to iframe is blocked
5861 // due to cross-origin restrictions
5862 styleTarget = styleTarget.contentDocument.head;
5863 } catch (e) {
5864 // istanbul ignore next
5865 styleTarget = null;
5866 }
5867 }
5868 memo[target] = styleTarget;
5869 }
5870 return memo[target];
5871 }
5872
5873 /* istanbul ignore next */
5874 function insertBySelector(insert, style) {
5875 var target = getTarget(insert);
5876 if (!target) {
5877 throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
5878 }
5879 target.appendChild(style);
5880 }
5881 module.exports = insertBySelector;
5882
5883 /***/ },
5884
5885 /***/ "./node_modules/style-loader/dist/runtime/insertStyleElement.js"
5886 /*!**********************************************************************!*\
5887 !*** ./node_modules/style-loader/dist/runtime/insertStyleElement.js ***!
5888 \**********************************************************************/
5889 (module) {
5890
5891 "use strict";
5892
5893
5894 /* istanbul ignore next */
5895 function insertStyleElement(options) {
5896 var element = document.createElement("style");
5897 options.setAttributes(element, options.attributes);
5898 options.insert(element, options.options);
5899 return element;
5900 }
5901 module.exports = insertStyleElement;
5902
5903 /***/ },
5904
5905 /***/ "./node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js"
5906 /*!**********************************************************************************!*\
5907 !*** ./node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js ***!
5908 \**********************************************************************************/
5909 (module, __unused_webpack_exports, __webpack_require__) {
5910
5911 "use strict";
5912
5913
5914 /* istanbul ignore next */
5915 function setAttributesWithoutAttributes(styleElement) {
5916 var nonce = true ? __webpack_require__.nc : 0;
5917 if (nonce) {
5918 styleElement.setAttribute("nonce", nonce);
5919 }
5920 }
5921 module.exports = setAttributesWithoutAttributes;
5922
5923 /***/ },
5924
5925 /***/ "./node_modules/style-loader/dist/runtime/styleDomAPI.js"
5926 /*!***************************************************************!*\
5927 !*** ./node_modules/style-loader/dist/runtime/styleDomAPI.js ***!
5928 \***************************************************************/
5929 (module) {
5930
5931 "use strict";
5932
5933
5934 /* istanbul ignore next */
5935 function apply(styleElement, options, obj) {
5936 var css = "";
5937 if (obj.supports) {
5938 css += "@supports (".concat(obj.supports, ") {");
5939 }
5940 if (obj.media) {
5941 css += "@media ".concat(obj.media, " {");
5942 }
5943 var needLayer = typeof obj.layer !== "undefined";
5944 if (needLayer) {
5945 css += "@layer".concat(obj.layer.length > 0 ? " ".concat(obj.layer) : "", " {");
5946 }
5947 css += obj.css;
5948 if (needLayer) {
5949 css += "}";
5950 }
5951 if (obj.media) {
5952 css += "}";
5953 }
5954 if (obj.supports) {
5955 css += "}";
5956 }
5957 var sourceMap = obj.sourceMap;
5958 if (sourceMap && typeof btoa !== "undefined") {
5959 css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
5960 }
5961
5962 // For old IE
5963 /* istanbul ignore if */
5964 options.styleTagTransform(css, styleElement, options.options);
5965 }
5966 function removeStyleElement(styleElement) {
5967 // istanbul ignore if
5968 if (styleElement.parentNode === null) {
5969 return false;
5970 }
5971 styleElement.parentNode.removeChild(styleElement);
5972 }
5973
5974 /* istanbul ignore next */
5975 function domAPI(options) {
5976 if (typeof document === "undefined") {
5977 return {
5978 update: function update() {},
5979 remove: function remove() {}
5980 };
5981 }
5982 var styleElement = options.insertStyleElement(options);
5983 return {
5984 update: function update(obj) {
5985 apply(styleElement, options, obj);
5986 },
5987 remove: function remove() {
5988 removeStyleElement(styleElement);
5989 }
5990 };
5991 }
5992 module.exports = domAPI;
5993
5994 /***/ },
5995
5996 /***/ "./node_modules/style-loader/dist/runtime/styleTagTransform.js"
5997 /*!*********************************************************************!*\
5998 !*** ./node_modules/style-loader/dist/runtime/styleTagTransform.js ***!
5999 \*********************************************************************/
6000 (module) {
6001
6002 "use strict";
6003
6004
6005 /* istanbul ignore next */
6006 function styleTagTransform(css, styleElement) {
6007 if (styleElement.styleSheet) {
6008 styleElement.styleSheet.cssText = css;
6009 } else {
6010 while (styleElement.firstChild) {
6011 styleElement.removeChild(styleElement.firstChild);
6012 }
6013 styleElement.appendChild(document.createTextNode(css));
6014 }
6015 }
6016 module.exports = styleTagTransform;
6017
6018 /***/ },
6019
6020 /***/ "./node_modules/sweetalert2/dist/sweetalert2.all.js"
6021 /*!**********************************************************!*\
6022 !*** ./node_modules/sweetalert2/dist/sweetalert2.all.js ***!
6023 \**********************************************************/
6024 (module) {
6025
6026 /*!
6027 * sweetalert2 v11.26.17
6028 * Released under the MIT License.
6029 */
6030 (function (global, factory) {
6031 true ? module.exports = factory() :
6032 0;
6033 })(this, (function () { 'use strict';
6034
6035 function _assertClassBrand(e, t, n) {
6036 if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
6037 throw new TypeError("Private element is not present on this object");
6038 }
6039 function _checkPrivateRedeclaration(e, t) {
6040 if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
6041 }
6042 function _classPrivateFieldGet2(s, a) {
6043 return s.get(_assertClassBrand(s, a));
6044 }
6045 function _classPrivateFieldInitSpec(e, t, a) {
6046 _checkPrivateRedeclaration(e, t), t.set(e, a);
6047 }
6048 function _classPrivateFieldSet2(s, a, r) {
6049 return s.set(_assertClassBrand(s, a), r), r;
6050 }
6051
6052 const RESTORE_FOCUS_TIMEOUT = 100;
6053
6054 /** @type {GlobalState} */
6055 const globalState = {};
6056 const focusPreviousActiveElement = () => {
6057 if (globalState.previousActiveElement instanceof HTMLElement) {
6058 globalState.previousActiveElement.focus();
6059 globalState.previousActiveElement = null;
6060 } else if (document.body) {
6061 document.body.focus();
6062 }
6063 };
6064
6065 /**
6066 * Restore previous active (focused) element
6067 *
6068 * @param {boolean} returnFocus
6069 * @returns {Promise<void>}
6070 */
6071 const restoreActiveElement = returnFocus => {
6072 return new Promise(resolve => {
6073 if (!returnFocus) {
6074 return resolve();
6075 }
6076 const x = window.scrollX;
6077 const y = window.scrollY;
6078 globalState.restoreFocusTimeout = setTimeout(() => {
6079 focusPreviousActiveElement();
6080 resolve();
6081 }, RESTORE_FOCUS_TIMEOUT); // issues/900
6082
6083 window.scrollTo(x, y);
6084 });
6085 };
6086
6087 const swalPrefix = 'swal2-';
6088
6089 /**
6090 * @typedef {Record<SwalClass, string>} SwalClasses
6091 */
6092
6093 /**
6094 * @typedef {'success' | 'warning' | 'info' | 'question' | 'error'} SwalIcon
6095 * @typedef {Record<SwalIcon, string>} SwalIcons
6096 */
6097
6098 /** @type {SwalClass[]} */
6099 const classNames = ['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', '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', 'draggable', 'dragging'];
6100 const swalClasses = classNames.reduce((acc, className) => {
6101 acc[className] = swalPrefix + className;
6102 return acc;
6103 }, /** @type {SwalClasses} */{});
6104
6105 /** @type {SwalIcon[]} */
6106 const icons = ['success', 'warning', 'info', 'question', 'error'];
6107 const iconTypes = icons.reduce((acc, icon) => {
6108 acc[icon] = swalPrefix + icon;
6109 return acc;
6110 }, /** @type {SwalIcons} */{});
6111
6112 const consolePrefix = 'SweetAlert2:';
6113
6114 /**
6115 * Capitalize the first letter of a string
6116 *
6117 * @param {string} str
6118 * @returns {string}
6119 */
6120 const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
6121
6122 /**
6123 * Standardize console warnings
6124 *
6125 * @param {string | string[]} message
6126 */
6127 const warn = message => {
6128 console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`);
6129 };
6130
6131 /**
6132 * Standardize console errors
6133 *
6134 * @param {string} message
6135 */
6136 const error = message => {
6137 console.error(`${consolePrefix} ${message}`);
6138 };
6139
6140 /**
6141 * Private global state for `warnOnce`
6142 *
6143 * @type {string[]}
6144 * @private
6145 */
6146 const previousWarnOnceMessages = [];
6147
6148 /**
6149 * Show a console warning, but only if it hasn't already been shown
6150 *
6151 * @param {string} message
6152 */
6153 const warnOnce = message => {
6154 if (!previousWarnOnceMessages.includes(message)) {
6155 previousWarnOnceMessages.push(message);
6156 warn(message);
6157 }
6158 };
6159
6160 /**
6161 * Show a one-time console warning about deprecated params/methods
6162 *
6163 * @param {string} deprecatedParam
6164 * @param {string?} useInstead
6165 */
6166 const warnAboutDeprecation = (deprecatedParam, useInstead = null) => {
6167 warnOnce(`"${deprecatedParam}" is deprecated and will be removed in the next major release.${useInstead ? ` Use "${useInstead}" instead.` : ''}`);
6168 };
6169
6170 /**
6171 * If `arg` is a function, call it (with no arguments or context) and return the result.
6172 * Otherwise, just pass the value through
6173 *
6174 * @param {(() => *) | *} arg
6175 * @returns {*}
6176 */
6177 const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
6178
6179 /**
6180 * @param {*} arg
6181 * @returns {boolean}
6182 */
6183 const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
6184
6185 /**
6186 * @param {*} arg
6187 * @returns {Promise<*>}
6188 */
6189 const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
6190
6191 /**
6192 * @param {*} arg
6193 * @returns {boolean}
6194 */
6195 const isPromise = arg => arg && Promise.resolve(arg) === arg;
6196
6197 /**
6198 * Gets the popup container which contains the backdrop and the popup itself.
6199 *
6200 * @returns {HTMLElement | null}
6201 */
6202 const getContainer = () => document.body.querySelector(`.${swalClasses.container}`);
6203
6204 /**
6205 * @param {string} selectorString
6206 * @returns {HTMLElement | null}
6207 */
6208 const elementBySelector = selectorString => {
6209 const container = getContainer();
6210 return container ? container.querySelector(selectorString) : null;
6211 };
6212
6213 /**
6214 * @param {string} className
6215 * @returns {HTMLElement | null}
6216 */
6217 const elementByClass = className => {
6218 return elementBySelector(`.${className}`);
6219 };
6220
6221 /**
6222 * @returns {HTMLElement | null}
6223 */
6224 const getPopup = () => elementByClass(swalClasses.popup);
6225
6226 /**
6227 * @returns {HTMLElement | null}
6228 */
6229 const getIcon = () => elementByClass(swalClasses.icon);
6230
6231 /**
6232 * @returns {HTMLElement | null}
6233 */
6234 const getIconContent = () => elementByClass(swalClasses['icon-content']);
6235
6236 /**
6237 * @returns {HTMLElement | null}
6238 */
6239 const getTitle = () => elementByClass(swalClasses.title);
6240
6241 /**
6242 * @returns {HTMLElement | null}
6243 */
6244 const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
6245
6246 /**
6247 * @returns {HTMLElement | null}
6248 */
6249 const getImage = () => elementByClass(swalClasses.image);
6250
6251 /**
6252 * @returns {HTMLElement | null}
6253 */
6254 const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
6255
6256 /**
6257 * @returns {HTMLElement | null}
6258 */
6259 const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
6260
6261 /**
6262 * @returns {HTMLButtonElement | null}
6263 */
6264 const getConfirmButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`));
6265
6266 /**
6267 * @returns {HTMLButtonElement | null}
6268 */
6269 const getCancelButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`));
6270
6271 /**
6272 * @returns {HTMLButtonElement | null}
6273 */
6274 const getDenyButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`));
6275
6276 /**
6277 * @returns {HTMLElement | null}
6278 */
6279 const getInputLabel = () => elementByClass(swalClasses['input-label']);
6280
6281 /**
6282 * @returns {HTMLElement | null}
6283 */
6284 const getLoader = () => elementBySelector(`.${swalClasses.loader}`);
6285
6286 /**
6287 * @returns {HTMLElement | null}
6288 */
6289 const getActions = () => elementByClass(swalClasses.actions);
6290
6291 /**
6292 * @returns {HTMLElement | null}
6293 */
6294 const getFooter = () => elementByClass(swalClasses.footer);
6295
6296 /**
6297 * @returns {HTMLElement | null}
6298 */
6299 const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
6300
6301 /**
6302 * @returns {HTMLElement | null}
6303 */
6304 const getCloseButton = () => elementByClass(swalClasses.close);
6305
6306 // https://github.com/jkup/focusable/blob/master/index.js
6307 const focusable = `
6308 a[href],
6309 area[href],
6310 input:not([disabled]),
6311 select:not([disabled]),
6312 textarea:not([disabled]),
6313 button:not([disabled]),
6314 iframe,
6315 object,
6316 embed,
6317 [tabindex="0"],
6318 [contenteditable],
6319 audio[controls],
6320 video[controls],
6321 summary
6322 `;
6323 /**
6324 * @returns {HTMLElement[]}
6325 */
6326 const getFocusableElements = () => {
6327 const popup = getPopup();
6328 if (!popup) {
6329 return [];
6330 }
6331 /** @type {NodeListOf<HTMLElement>} */
6332 const focusableElementsWithTabindex = popup.querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])');
6333 const focusableElementsWithTabindexSorted = Array.from(focusableElementsWithTabindex)
6334 // sort according to tabindex
6335 .sort((a, b) => {
6336 const tabindexA = parseInt(a.getAttribute('tabindex') || '0');
6337 const tabindexB = parseInt(b.getAttribute('tabindex') || '0');
6338 if (tabindexA > tabindexB) {
6339 return 1;
6340 } else if (tabindexA < tabindexB) {
6341 return -1;
6342 }
6343 return 0;
6344 });
6345
6346 /** @type {NodeListOf<HTMLElement>} */
6347 const otherFocusableElements = popup.querySelectorAll(focusable);
6348 const otherFocusableElementsFiltered = Array.from(otherFocusableElements).filter(el => el.getAttribute('tabindex') !== '-1');
6349 return [...new Set(focusableElementsWithTabindexSorted.concat(otherFocusableElementsFiltered))].filter(el => isVisible$1(el));
6350 };
6351
6352 /**
6353 * @returns {boolean}
6354 */
6355 const isModal = () => {
6356 return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
6357 };
6358
6359 /**
6360 * @returns {boolean}
6361 */
6362 const isToast = () => {
6363 const popup = getPopup();
6364 if (!popup) {
6365 return false;
6366 }
6367 return hasClass(popup, swalClasses.toast);
6368 };
6369
6370 /**
6371 * @returns {boolean}
6372 */
6373 const isLoading = () => {
6374 const popup = getPopup();
6375 if (!popup) {
6376 return false;
6377 }
6378 return popup.hasAttribute('data-loading');
6379 };
6380
6381 /**
6382 * Securely set innerHTML of an element
6383 * https://github.com/sweetalert2/sweetalert2/issues/1926
6384 *
6385 * @param {HTMLElement} elem
6386 * @param {string} html
6387 */
6388 const setInnerHtml = (elem, html) => {
6389 elem.textContent = '';
6390 if (html) {
6391 const parser = new DOMParser();
6392 const parsed = parser.parseFromString(html, `text/html`);
6393 const head = parsed.querySelector('head');
6394 if (head) {
6395 Array.from(head.childNodes).forEach(child => {
6396 elem.appendChild(child);
6397 });
6398 }
6399 const body = parsed.querySelector('body');
6400 if (body) {
6401 Array.from(body.childNodes).forEach(child => {
6402 if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) {
6403 elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507
6404 } else {
6405 elem.appendChild(child);
6406 }
6407 });
6408 }
6409 }
6410 };
6411
6412 /**
6413 * @param {HTMLElement} elem
6414 * @param {string} className
6415 * @returns {boolean}
6416 */
6417 const hasClass = (elem, className) => {
6418 if (!className) {
6419 return false;
6420 }
6421 const classList = className.split(/\s+/);
6422 for (let i = 0; i < classList.length; i++) {
6423 if (!elem.classList.contains(classList[i])) {
6424 return false;
6425 }
6426 }
6427 return true;
6428 };
6429
6430 /**
6431 * @param {HTMLElement} elem
6432 * @param {SweetAlertOptions} params
6433 */
6434 const removeCustomClasses = (elem, params) => {
6435 Array.from(elem.classList).forEach(className => {
6436 if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass || {}).includes(className)) {
6437 elem.classList.remove(className);
6438 }
6439 });
6440 };
6441
6442 /**
6443 * @param {HTMLElement} elem
6444 * @param {SweetAlertOptions} params
6445 * @param {string} className
6446 */
6447 const applyCustomClass = (elem, params, className) => {
6448 removeCustomClasses(elem, params);
6449 if (!params.customClass) {
6450 return;
6451 }
6452 const customClass = params.customClass[(/** @type {keyof SweetAlertCustomClass} */className)];
6453 if (!customClass) {
6454 return;
6455 }
6456 if (typeof customClass !== 'string' && !customClass.forEach) {
6457 warn(`Invalid type of customClass.${className}! Expected string or iterable object, got "${typeof customClass}"`);
6458 return;
6459 }
6460 addClass(elem, customClass);
6461 };
6462
6463 /**
6464 * @param {HTMLElement} popup
6465 * @param {import('./renderers/renderInput').InputClass | SweetAlertInput} inputClass
6466 * @returns {HTMLInputElement | null}
6467 */
6468 const getInput$1 = (popup, inputClass) => {
6469 if (!inputClass) {
6470 return null;
6471 }
6472 switch (inputClass) {
6473 case 'select':
6474 case 'textarea':
6475 case 'file':
6476 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`);
6477 case 'checkbox':
6478 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`);
6479 case 'radio':
6480 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`);
6481 case 'range':
6482 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`);
6483 default:
6484 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`);
6485 }
6486 };
6487
6488 /**
6489 * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input
6490 */
6491 const focusInput = input => {
6492 input.focus();
6493
6494 // place cursor at end of text in text input
6495 if (input.type !== 'file') {
6496 // http://stackoverflow.com/a/2345915
6497 const val = input.value;
6498 input.value = '';
6499 input.value = val;
6500 }
6501 };
6502
6503 /**
6504 * @param {HTMLElement | HTMLElement[] | null} target
6505 * @param {string | string[] | readonly string[] | undefined} classList
6506 * @param {boolean} condition
6507 */
6508 const toggleClass = (target, classList, condition) => {
6509 if (!target || !classList) {
6510 return;
6511 }
6512 if (typeof classList === 'string') {
6513 classList = classList.split(/\s+/).filter(Boolean);
6514 }
6515 classList.forEach(className => {
6516 if (Array.isArray(target)) {
6517 target.forEach(elem => {
6518 if (condition) {
6519 elem.classList.add(className);
6520 } else {
6521 elem.classList.remove(className);
6522 }
6523 });
6524 } else {
6525 if (condition) {
6526 target.classList.add(className);
6527 } else {
6528 target.classList.remove(className);
6529 }
6530 }
6531 });
6532 };
6533
6534 /**
6535 * @param {HTMLElement | HTMLElement[] | null} target
6536 * @param {string | string[] | readonly string[] | undefined} classList
6537 */
6538 const addClass = (target, classList) => {
6539 toggleClass(target, classList, true);
6540 };
6541
6542 /**
6543 * @param {HTMLElement | HTMLElement[] | null} target
6544 * @param {string | string[] | readonly string[] | undefined} classList
6545 */
6546 const removeClass = (target, classList) => {
6547 toggleClass(target, classList, false);
6548 };
6549
6550 /**
6551 * Get direct child of an element by class name
6552 *
6553 * @param {HTMLElement} elem
6554 * @param {string} className
6555 * @returns {HTMLElement | undefined}
6556 */
6557 const getDirectChildByClass = (elem, className) => {
6558 const children = Array.from(elem.children);
6559 for (let i = 0; i < children.length; i++) {
6560 const child = children[i];
6561 if (child instanceof HTMLElement && hasClass(child, className)) {
6562 return child;
6563 }
6564 }
6565 };
6566
6567 /**
6568 * @param {HTMLElement} elem
6569 * @param {string} property
6570 * @param {string | number | null | undefined} value
6571 */
6572 const applyNumericalStyle = (elem, property, value) => {
6573 if (value === `${parseInt(`${value}`)}`) {
6574 value = parseInt(value);
6575 }
6576 if (value || parseInt(`${value}`) === 0) {
6577 elem.style.setProperty(property, typeof value === 'number' ? `${value}px` : (/** @type {string} */value));
6578 } else {
6579 elem.style.removeProperty(property);
6580 }
6581 };
6582
6583 /**
6584 * @param {HTMLElement | null} elem
6585 * @param {string} display
6586 */
6587 const show = (elem, display = 'flex') => {
6588 if (!elem) {
6589 return;
6590 }
6591 elem.style.display = display;
6592 };
6593
6594 /**
6595 * @param {HTMLElement | null} elem
6596 */
6597 const hide = elem => {
6598 if (!elem) {
6599 return;
6600 }
6601 elem.style.display = 'none';
6602 };
6603
6604 /**
6605 * @param {HTMLElement | null} elem
6606 * @param {string} display
6607 */
6608 const showWhenInnerHtmlPresent = (elem, display = 'block') => {
6609 if (!elem) {
6610 return;
6611 }
6612 new MutationObserver(() => {
6613 toggle(elem, elem.innerHTML, display);
6614 }).observe(elem, {
6615 childList: true,
6616 subtree: true
6617 });
6618 };
6619
6620 /**
6621 * @param {HTMLElement} parent
6622 * @param {string} selector
6623 * @param {string} property
6624 * @param {string} value
6625 */
6626 const setStyle = (parent, selector, property, value) => {
6627 /** @type {HTMLElement | null} */
6628 const el = parent.querySelector(selector);
6629 if (el) {
6630 el.style.setProperty(property, value);
6631 }
6632 };
6633
6634 /**
6635 * @param {HTMLElement} elem
6636 * @param {boolean | string | null | undefined} condition
6637 * @param {string} display
6638 */
6639 const toggle = (elem, condition, display = 'flex') => {
6640 if (condition) {
6641 show(elem, display);
6642 } else {
6643 hide(elem);
6644 }
6645 };
6646
6647 /**
6648 * borrowed from jquery $(elem).is(':visible') implementation
6649 *
6650 * @param {HTMLElement | null} elem
6651 * @returns {boolean}
6652 */
6653 const isVisible$1 = elem => Boolean(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
6654
6655 /**
6656 * @returns {boolean}
6657 */
6658 const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton());
6659
6660 /**
6661 * @param {HTMLElement} elem
6662 * @returns {boolean}
6663 */
6664 const isScrollable = elem => Boolean(elem.scrollHeight > elem.clientHeight);
6665
6666 /**
6667 * @param {HTMLElement} element
6668 * @param {HTMLElement} stopElement
6669 * @returns {boolean}
6670 */
6671 const selfOrParentIsScrollable = (element, stopElement) => {
6672 let parent = /** @type {HTMLElement | null} */element;
6673 while (parent && parent !== stopElement) {
6674 if (isScrollable(parent)) {
6675 return true;
6676 }
6677 parent = parent.parentElement;
6678 }
6679 return false;
6680 };
6681
6682 /**
6683 * borrowed from https://stackoverflow.com/a/46352119
6684 *
6685 * @param {HTMLElement} elem
6686 * @returns {boolean}
6687 */
6688 const hasCssAnimation = elem => {
6689 const style = window.getComputedStyle(elem);
6690 const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
6691 const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
6692 return animDuration > 0 || transDuration > 0;
6693 };
6694
6695 /**
6696 * @param {number} timer
6697 * @param {boolean} reset
6698 */
6699 const animateTimerProgressBar = (timer, reset = false) => {
6700 const timerProgressBar = getTimerProgressBar();
6701 if (!timerProgressBar) {
6702 return;
6703 }
6704 if (isVisible$1(timerProgressBar)) {
6705 if (reset) {
6706 timerProgressBar.style.transition = 'none';
6707 timerProgressBar.style.width = '100%';
6708 }
6709 setTimeout(() => {
6710 timerProgressBar.style.transition = `width ${timer / 1000}s linear`;
6711 timerProgressBar.style.width = '0%';
6712 }, 10);
6713 }
6714 };
6715 const stopTimerProgressBar = () => {
6716 const timerProgressBar = getTimerProgressBar();
6717 if (!timerProgressBar) {
6718 return;
6719 }
6720 const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
6721 timerProgressBar.style.removeProperty('transition');
6722 timerProgressBar.style.width = '100%';
6723 const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
6724 const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
6725 timerProgressBar.style.width = `${timerProgressBarPercent}%`;
6726 };
6727
6728 /**
6729 * Detect Node env
6730 *
6731 * @returns {boolean}
6732 */
6733 const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
6734
6735 const sweetHTML = `
6736 <div aria-labelledby="${swalClasses.title}" aria-describedby="${swalClasses['html-container']}" class="${swalClasses.popup}" tabindex="-1">
6737 <button type="button" class="${swalClasses.close}"></button>
6738 <ul class="${swalClasses['progress-steps']}"></ul>
6739 <div class="${swalClasses.icon}"></div>
6740 <img class="${swalClasses.image}" />
6741 <h2 class="${swalClasses.title}" id="${swalClasses.title}"></h2>
6742 <div class="${swalClasses['html-container']}" id="${swalClasses['html-container']}"></div>
6743 <input class="${swalClasses.input}" id="${swalClasses.input}" />
6744 <input type="file" class="${swalClasses.file}" />
6745 <div class="${swalClasses.range}">
6746 <input type="range" />
6747 <output></output>
6748 </div>
6749 <select class="${swalClasses.select}" id="${swalClasses.select}"></select>
6750 <div class="${swalClasses.radio}"></div>
6751 <label class="${swalClasses.checkbox}">
6752 <input type="checkbox" id="${swalClasses.checkbox}" />
6753 <span class="${swalClasses.label}"></span>
6754 </label>
6755 <textarea class="${swalClasses.textarea}" id="${swalClasses.textarea}"></textarea>
6756 <div class="${swalClasses['validation-message']}" id="${swalClasses['validation-message']}"></div>
6757 <div class="${swalClasses.actions}">
6758 <div class="${swalClasses.loader}"></div>
6759 <button type="button" class="${swalClasses.confirm}"></button>
6760 <button type="button" class="${swalClasses.deny}"></button>
6761 <button type="button" class="${swalClasses.cancel}"></button>
6762 </div>
6763 <div class="${swalClasses.footer}"></div>
6764 <div class="${swalClasses['timer-progress-bar-container']}">
6765 <div class="${swalClasses['timer-progress-bar']}"></div>
6766 </div>
6767 </div>
6768 `.replace(/(^|\n)\s*/g, '');
6769
6770 /**
6771 * @returns {boolean}
6772 */
6773 const resetOldContainer = () => {
6774 const oldContainer = getContainer();
6775 if (!oldContainer) {
6776 return false;
6777 }
6778 oldContainer.remove();
6779 removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'],
6780 // @ts-ignore: 'has-column' is not defined in swalClasses but may be set dynamically
6781 swalClasses['has-column']]);
6782 return true;
6783 };
6784 const resetValidationMessage$1 = () => {
6785 if (globalState.currentInstance) {
6786 globalState.currentInstance.resetValidationMessage();
6787 }
6788 };
6789 const addInputChangeListeners = () => {
6790 const popup = getPopup();
6791 if (!popup) {
6792 return;
6793 }
6794 const input = getDirectChildByClass(popup, swalClasses.input);
6795 const file = getDirectChildByClass(popup, swalClasses.file);
6796 /** @type {HTMLInputElement | null} */
6797 const range = popup.querySelector(`.${swalClasses.range} input`);
6798 /** @type {HTMLOutputElement | null} */
6799 const rangeOutput = popup.querySelector(`.${swalClasses.range} output`);
6800 const select = getDirectChildByClass(popup, swalClasses.select);
6801 /** @type {HTMLInputElement | null} */
6802 const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`);
6803 const textarea = getDirectChildByClass(popup, swalClasses.textarea);
6804 if (input) {
6805 input.oninput = resetValidationMessage$1;
6806 }
6807 if (file) {
6808 file.onchange = resetValidationMessage$1;
6809 }
6810 if (select) {
6811 select.onchange = resetValidationMessage$1;
6812 }
6813 if (checkbox) {
6814 checkbox.onchange = resetValidationMessage$1;
6815 }
6816 if (textarea) {
6817 textarea.oninput = resetValidationMessage$1;
6818 }
6819 if (range && rangeOutput) {
6820 range.oninput = () => {
6821 resetValidationMessage$1();
6822 rangeOutput.value = range.value;
6823 };
6824 range.onchange = () => {
6825 resetValidationMessage$1();
6826 rangeOutput.value = range.value;
6827 };
6828 }
6829 };
6830
6831 /**
6832 * @param {string | HTMLElement} target
6833 * @returns {HTMLElement}
6834 */
6835 const getTarget = target => {
6836 if (typeof target === 'string') {
6837 const element = document.querySelector(target);
6838 if (!element) {
6839 throw new Error(`Target element "${target}" not found`);
6840 }
6841 return /** @type {HTMLElement} */element;
6842 }
6843 return target;
6844 };
6845
6846 /**
6847 * @param {SweetAlertOptions} params
6848 */
6849 const setupAccessibility = params => {
6850 const popup = getPopup();
6851 if (!popup) {
6852 return;
6853 }
6854 popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
6855 popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
6856 if (!params.toast) {
6857 popup.setAttribute('aria-modal', 'true');
6858 }
6859 };
6860
6861 /**
6862 * @param {HTMLElement} targetElement
6863 */
6864 const setupRTL = targetElement => {
6865 if (window.getComputedStyle(targetElement).direction === 'rtl') {
6866 addClass(getContainer(), swalClasses.rtl);
6867 globalState.isRTL = true;
6868 }
6869 };
6870
6871 /**
6872 * Add modal + backdrop to DOM
6873 *
6874 * @param {SweetAlertOptions} params
6875 */
6876 const init = params => {
6877 // Clean up the old popup container if it exists
6878 const oldContainerExisted = resetOldContainer();
6879 if (isNodeEnv()) {
6880 error('SweetAlert2 requires document to initialize');
6881 return;
6882 }
6883 const container = document.createElement('div');
6884 container.className = swalClasses.container;
6885 if (oldContainerExisted) {
6886 addClass(container, swalClasses['no-transition']);
6887 }
6888 setInnerHtml(container, sweetHTML);
6889 container.dataset['swal2Theme'] = params.theme;
6890 const targetElement = getTarget(params.target || 'body');
6891 targetElement.appendChild(container);
6892 if (params.topLayer) {
6893 container.setAttribute('popover', '');
6894 container.showPopover();
6895 }
6896 setupAccessibility(params);
6897 setupRTL(targetElement);
6898 addInputChangeListeners();
6899 };
6900
6901 /**
6902 * @param {HTMLElement | object | string} param
6903 * @param {HTMLElement} target
6904 */
6905 const parseHtmlToContainer = (param, target) => {
6906 // DOM element
6907 if (param instanceof HTMLElement) {
6908 target.appendChild(param);
6909 }
6910
6911 // Object
6912 else if (typeof param === 'object') {
6913 handleObject(param, target);
6914 }
6915
6916 // Plain string
6917 else if (param) {
6918 setInnerHtml(target, param);
6919 }
6920 };
6921
6922 /**
6923 * @param {object} param
6924 * @param {HTMLElement} target
6925 */
6926 const handleObject = (param, target) => {
6927 // JQuery element(s)
6928 if ('jquery' in param) {
6929 handleJqueryElem(target, param);
6930 }
6931
6932 // For other objects use their string representation
6933 else {
6934 setInnerHtml(target, param.toString());
6935 }
6936 };
6937
6938 /**
6939 * @param {HTMLElement} target
6940 * @param {any} elem
6941 */
6942 const handleJqueryElem = (target, elem) => {
6943 target.textContent = '';
6944 if (0 in elem) {
6945 for (let i = 0; i in elem; i++) {
6946 target.appendChild(elem[i].cloneNode(true));
6947 }
6948 } else {
6949 target.appendChild(elem.cloneNode(true));
6950 }
6951 };
6952
6953 /**
6954 * @param {SweetAlert} instance
6955 * @param {SweetAlertOptions} params
6956 */
6957 const renderActions = (instance, params) => {
6958 const actions = getActions();
6959 const loader = getLoader();
6960 if (!actions || !loader) {
6961 return;
6962 }
6963
6964 // Actions (buttons) wrapper
6965 if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
6966 hide(actions);
6967 } else {
6968 show(actions);
6969 }
6970
6971 // Custom class
6972 applyCustomClass(actions, params, 'actions');
6973
6974 // Render all the buttons
6975 renderButtons(actions, loader, params);
6976
6977 // Loader
6978 setInnerHtml(loader, params.loaderHtml || '');
6979 applyCustomClass(loader, params, 'loader');
6980 };
6981
6982 /**
6983 * @param {HTMLElement} actions
6984 * @param {HTMLElement} loader
6985 * @param {SweetAlertOptions} params
6986 */
6987 function renderButtons(actions, loader, params) {
6988 const confirmButton = getConfirmButton();
6989 const denyButton = getDenyButton();
6990 const cancelButton = getCancelButton();
6991 if (!confirmButton || !denyButton || !cancelButton) {
6992 return;
6993 }
6994
6995 // Render buttons
6996 renderButton(confirmButton, 'confirm', params);
6997 renderButton(denyButton, 'deny', params);
6998 renderButton(cancelButton, 'cancel', params);
6999 handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
7000 if (params.reverseButtons) {
7001 if (params.toast) {
7002 actions.insertBefore(cancelButton, confirmButton);
7003 actions.insertBefore(denyButton, confirmButton);
7004 } else {
7005 actions.insertBefore(cancelButton, loader);
7006 actions.insertBefore(denyButton, loader);
7007 actions.insertBefore(confirmButton, loader);
7008 }
7009 }
7010 }
7011
7012 /**
7013 * @param {HTMLElement} confirmButton
7014 * @param {HTMLElement} denyButton
7015 * @param {HTMLElement} cancelButton
7016 * @param {SweetAlertOptions} params
7017 */
7018 function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
7019 if (!params.buttonsStyling) {
7020 removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
7021 return;
7022 }
7023 addClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
7024
7025 // Apply custom background colors to action buttons
7026 if (params.confirmButtonColor) {
7027 confirmButton.style.setProperty('--swal2-confirm-button-background-color', params.confirmButtonColor);
7028 }
7029 if (params.denyButtonColor) {
7030 denyButton.style.setProperty('--swal2-deny-button-background-color', params.denyButtonColor);
7031 }
7032 if (params.cancelButtonColor) {
7033 cancelButton.style.setProperty('--swal2-cancel-button-background-color', params.cancelButtonColor);
7034 }
7035
7036 // Apply the outline color to action buttons
7037 applyOutlineColor(confirmButton);
7038 applyOutlineColor(denyButton);
7039 applyOutlineColor(cancelButton);
7040 }
7041
7042 /**
7043 * @param {HTMLElement} button
7044 */
7045 function applyOutlineColor(button) {
7046 const buttonStyle = window.getComputedStyle(button);
7047 if (buttonStyle.getPropertyValue('--swal2-action-button-focus-box-shadow')) {
7048 // If the button already has a custom outline color, no need to change it
7049 return;
7050 }
7051 const outlineColor = buttonStyle.backgroundColor.replace(/rgba?\((\d+), (\d+), (\d+).*/, 'rgba($1, $2, $3, 0.5)');
7052 button.style.setProperty('--swal2-action-button-focus-box-shadow', buttonStyle.getPropertyValue('--swal2-outline').replace(/ rgba\(.*/, ` ${outlineColor}`));
7053 }
7054
7055 /**
7056 * @param {HTMLElement} button
7057 * @param {'confirm' | 'deny' | 'cancel'} buttonType
7058 * @param {SweetAlertOptions} params
7059 */
7060 function renderButton(button, buttonType, params) {
7061 const buttonName = /** @type {'Confirm' | 'Deny' | 'Cancel'} */capitalizeFirstLetter(buttonType);
7062 toggle(button, params[`show${buttonName}Button`], 'inline-block');
7063 setInnerHtml(button, params[`${buttonType}ButtonText`] || ''); // Set caption text
7064 button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`] || ''); // ARIA label
7065
7066 // Add buttons custom classes
7067 button.className = swalClasses[buttonType];
7068 applyCustomClass(button, params, `${buttonType}Button`);
7069 }
7070
7071 /**
7072 * @param {SweetAlert} instance
7073 * @param {SweetAlertOptions} params
7074 */
7075 const renderCloseButton = (instance, params) => {
7076 const closeButton = getCloseButton();
7077 if (!closeButton) {
7078 return;
7079 }
7080 setInnerHtml(closeButton, params.closeButtonHtml || '');
7081
7082 // Custom class
7083 applyCustomClass(closeButton, params, 'closeButton');
7084 toggle(closeButton, params.showCloseButton);
7085 closeButton.setAttribute('aria-label', params.closeButtonAriaLabel || '');
7086 };
7087
7088 /**
7089 * @param {SweetAlert} instance
7090 * @param {SweetAlertOptions} params
7091 */
7092 const renderContainer = (instance, params) => {
7093 const container = getContainer();
7094 if (!container) {
7095 return;
7096 }
7097 handleBackdropParam(container, params.backdrop);
7098 handlePositionParam(container, params.position);
7099 handleGrowParam(container, params.grow);
7100
7101 // Custom class
7102 applyCustomClass(container, params, 'container');
7103 };
7104
7105 /**
7106 * @param {HTMLElement} container
7107 * @param {SweetAlertOptions['backdrop']} backdrop
7108 */
7109 function handleBackdropParam(container, backdrop) {
7110 if (typeof backdrop === 'string') {
7111 container.style.background = backdrop;
7112 } else if (!backdrop) {
7113 addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
7114 }
7115 }
7116
7117 /**
7118 * @param {HTMLElement} container
7119 * @param {SweetAlertOptions['position']} position
7120 */
7121 function handlePositionParam(container, position) {
7122 if (!position) {
7123 return;
7124 }
7125 if (position in swalClasses) {
7126 addClass(container, swalClasses[position]);
7127 } else {
7128 warn('The "position" parameter is not valid, defaulting to "center"');
7129 addClass(container, swalClasses.center);
7130 }
7131 }
7132
7133 /**
7134 * @param {HTMLElement} container
7135 * @param {SweetAlertOptions['grow']} grow
7136 */
7137 function handleGrowParam(container, grow) {
7138 if (!grow) {
7139 return;
7140 }
7141 addClass(container, swalClasses[`grow-${grow}`]);
7142 }
7143
7144 /**
7145 * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
7146 * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
7147 * This is the approach that Babel will probably take to implement private methods/fields
7148 * https://github.com/tc39/proposal-private-methods
7149 * https://github.com/babel/babel/pull/7555
7150 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
7151 * then we can use that language feature.
7152 */
7153
7154 var privateProps = {
7155 innerParams: new WeakMap(),
7156 domCache: new WeakMap()
7157 };
7158
7159 /// <reference path="../../../../sweetalert2.d.ts"/>
7160
7161
7162 /** @type {InputClass[]} */
7163 const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
7164
7165 /**
7166 * @param {SweetAlert} instance
7167 * @param {SweetAlertOptions} params
7168 */
7169 const renderInput = (instance, params) => {
7170 const popup = getPopup();
7171 if (!popup) {
7172 return;
7173 }
7174 const innerParams = privateProps.innerParams.get(instance);
7175 const rerender = !innerParams || params.input !== innerParams.input;
7176 inputClasses.forEach(inputClass => {
7177 const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]);
7178 if (!inputContainer) {
7179 return;
7180 }
7181
7182 // set attributes
7183 setAttributes(inputClass, params.inputAttributes);
7184
7185 // set class
7186 inputContainer.className = swalClasses[inputClass];
7187 if (rerender) {
7188 hide(inputContainer);
7189 }
7190 });
7191 if (params.input) {
7192 if (rerender) {
7193 showInput(params);
7194 }
7195 // set custom class
7196 setCustomClass(params);
7197 }
7198 };
7199
7200 /**
7201 * @param {SweetAlertOptions} params
7202 */
7203 const showInput = params => {
7204 if (!params.input) {
7205 return;
7206 }
7207 if (!renderInputType[params.input]) {
7208 error(`Unexpected type of input! Expected ${Object.keys(renderInputType).join(' | ')}, got "${params.input}"`);
7209 return;
7210 }
7211 const inputContainer = getInputContainer(params.input);
7212 if (!inputContainer) {
7213 return;
7214 }
7215 const input = renderInputType[params.input](inputContainer, params);
7216 show(inputContainer);
7217
7218 // input autofocus
7219 if (params.inputAutoFocus) {
7220 setTimeout(() => {
7221 focusInput(input);
7222 });
7223 }
7224 };
7225
7226 /**
7227 * @param {HTMLInputElement} input
7228 */
7229 const removeAttributes = input => {
7230 for (let i = 0; i < input.attributes.length; i++) {
7231 const attrName = input.attributes[i].name;
7232 if (!['id', 'type', 'value', 'style'].includes(attrName)) {
7233 input.removeAttribute(attrName);
7234 }
7235 }
7236 };
7237
7238 /**
7239 * @param {InputClass} inputClass
7240 * @param {SweetAlertOptions['inputAttributes']} inputAttributes
7241 */
7242 const setAttributes = (inputClass, inputAttributes) => {
7243 const popup = getPopup();
7244 if (!popup) {
7245 return;
7246 }
7247 const input = getInput$1(popup, inputClass);
7248 if (!input) {
7249 return;
7250 }
7251 removeAttributes(input);
7252 for (const attr in inputAttributes) {
7253 input.setAttribute(attr, inputAttributes[attr]);
7254 }
7255 };
7256
7257 /**
7258 * @param {SweetAlertOptions} params
7259 */
7260 const setCustomClass = params => {
7261 if (!params.input) {
7262 return;
7263 }
7264 const inputContainer = getInputContainer(params.input);
7265 if (inputContainer) {
7266 applyCustomClass(inputContainer, params, 'input');
7267 }
7268 };
7269
7270 /**
7271 * @param {HTMLInputElement | HTMLTextAreaElement} input
7272 * @param {SweetAlertOptions} params
7273 */
7274 const setInputPlaceholder = (input, params) => {
7275 if (!input.placeholder && params.inputPlaceholder) {
7276 input.placeholder = params.inputPlaceholder;
7277 }
7278 };
7279
7280 /**
7281 * @param {Input} input
7282 * @param {Input} prependTo
7283 * @param {SweetAlertOptions} params
7284 */
7285 const setInputLabel = (input, prependTo, params) => {
7286 if (params.inputLabel) {
7287 const label = document.createElement('label');
7288 const labelClass = swalClasses['input-label'];
7289 label.setAttribute('for', input.id);
7290 label.className = labelClass;
7291 if (typeof params.customClass === 'object') {
7292 addClass(label, params.customClass.inputLabel);
7293 }
7294 label.innerText = params.inputLabel;
7295 prependTo.insertAdjacentElement('beforebegin', label);
7296 }
7297 };
7298
7299 /**
7300 * @param {SweetAlertInput} inputType
7301 * @returns {HTMLElement | undefined}
7302 */
7303 const getInputContainer = inputType => {
7304 const popup = getPopup();
7305 if (!popup) {
7306 return;
7307 }
7308 return getDirectChildByClass(popup, swalClasses[(/** @type {SwalClass} */inputType)] || swalClasses.input);
7309 };
7310
7311 /**
7312 * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input
7313 * @param {SweetAlertOptions['inputValue']} inputValue
7314 */
7315 const checkAndSetInputValue = (input, inputValue) => {
7316 if (['string', 'number'].includes(typeof inputValue)) {
7317 input.value = `${inputValue}`;
7318 } else if (!isPromise(inputValue)) {
7319 warn(`Unexpected type of inputValue! Expected "string", "number" or "Promise", got "${typeof inputValue}"`);
7320 }
7321 };
7322
7323 /** @type {Record<SweetAlertInput, (input: Input | HTMLElement, params: SweetAlertOptions) => Input>} */
7324 const renderInputType = {};
7325
7326 /**
7327 * @param {Input | HTMLElement} input
7328 * @param {SweetAlertOptions} params
7329 * @returns {Input}
7330 */
7331 renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = renderInputType.search = renderInputType.date = renderInputType['datetime-local'] = renderInputType.time = renderInputType.week = renderInputType.month = /** @type {(input: Input | HTMLElement, params: SweetAlertOptions) => Input} */
7332 (input, params) => {
7333 const inputElement = /** @type {HTMLInputElement} */input;
7334 checkAndSetInputValue(inputElement, params.inputValue);
7335 setInputLabel(inputElement, inputElement, params);
7336 setInputPlaceholder(inputElement, params);
7337 inputElement.type = /** @type {string} */params.input;
7338 return inputElement;
7339 };
7340
7341 /**
7342 * @param {Input | HTMLElement} input
7343 * @param {SweetAlertOptions} params
7344 * @returns {Input}
7345 */
7346 renderInputType.file = (input, params) => {
7347 const inputElement = /** @type {HTMLInputElement} */input;
7348 setInputLabel(inputElement, inputElement, params);
7349 setInputPlaceholder(inputElement, params);
7350 return inputElement;
7351 };
7352
7353 /**
7354 * @param {Input | HTMLElement} range
7355 * @param {SweetAlertOptions} params
7356 * @returns {Input}
7357 */
7358 renderInputType.range = (range, params) => {
7359 const rangeContainer = /** @type {HTMLElement} */range;
7360 const rangeInput = rangeContainer.querySelector('input');
7361 const rangeOutput = rangeContainer.querySelector('output');
7362 if (rangeInput) {
7363 checkAndSetInputValue(rangeInput, params.inputValue);
7364 rangeInput.type = /** @type {string} */params.input;
7365 setInputLabel(rangeInput, /** @type {Input} */range, params);
7366 }
7367 if (rangeOutput) {
7368 checkAndSetInputValue(rangeOutput, params.inputValue);
7369 }
7370 return /** @type {Input} */range;
7371 };
7372
7373 /**
7374 * @param {Input | HTMLElement} select
7375 * @param {SweetAlertOptions} params
7376 * @returns {Input}
7377 */
7378 renderInputType.select = (select, params) => {
7379 const selectElement = /** @type {HTMLSelectElement} */select;
7380 selectElement.textContent = '';
7381 if (params.inputPlaceholder) {
7382 const placeholder = document.createElement('option');
7383 setInnerHtml(placeholder, params.inputPlaceholder);
7384 placeholder.value = '';
7385 placeholder.disabled = true;
7386 placeholder.selected = true;
7387 selectElement.appendChild(placeholder);
7388 }
7389 setInputLabel(selectElement, selectElement, params);
7390 return selectElement;
7391 };
7392
7393 /**
7394 * @param {Input | HTMLElement} radio
7395 * @returns {Input}
7396 */
7397 renderInputType.radio = radio => {
7398 const radioElement = /** @type {HTMLElement} */radio;
7399 radioElement.textContent = '';
7400 return /** @type {Input} */radio;
7401 };
7402
7403 /**
7404 * @param {Input | HTMLElement} checkboxContainer
7405 * @param {SweetAlertOptions} params
7406 * @returns {Input}
7407 */
7408 renderInputType.checkbox = (checkboxContainer, params) => {
7409 const popup = getPopup();
7410 if (!popup) {
7411 throw new Error('Popup not found');
7412 }
7413 const checkbox = getInput$1(popup, 'checkbox');
7414 if (!checkbox) {
7415 throw new Error('Checkbox input not found');
7416 }
7417 checkbox.value = '1';
7418 checkbox.checked = Boolean(params.inputValue);
7419 const containerElement = /** @type {HTMLElement} */checkboxContainer;
7420 const label = containerElement.querySelector('span');
7421 if (label) {
7422 const placeholderOrLabel = params.inputPlaceholder || params.inputLabel;
7423 if (placeholderOrLabel) {
7424 setInnerHtml(label, placeholderOrLabel);
7425 }
7426 }
7427 return checkbox;
7428 };
7429
7430 /**
7431 * @param {Input | HTMLElement} textarea
7432 * @param {SweetAlertOptions} params
7433 * @returns {Input}
7434 */
7435 renderInputType.textarea = (textarea, params) => {
7436 const textareaElement = /** @type {HTMLTextAreaElement} */textarea;
7437 checkAndSetInputValue(textareaElement, params.inputValue);
7438 setInputPlaceholder(textareaElement, params);
7439 setInputLabel(textareaElement, textareaElement, params);
7440
7441 /**
7442 * @param {HTMLElement} el
7443 * @returns {number}
7444 */
7445 const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);
7446
7447 // https://github.com/sweetalert2/sweetalert2/issues/2291
7448 setTimeout(() => {
7449 // https://github.com/sweetalert2/sweetalert2/issues/1699
7450 if ('MutationObserver' in window) {
7451 const popup = getPopup();
7452 if (!popup) {
7453 return;
7454 }
7455 const initialPopupWidth = parseInt(window.getComputedStyle(popup).width);
7456 const textareaResizeHandler = () => {
7457 // check if texarea is still in document (i.e. popup wasn't closed in the meantime)
7458 if (!document.body.contains(textareaElement)) {
7459 return;
7460 }
7461 const textareaWidth = textareaElement.offsetWidth + getMargin(textareaElement);
7462 const popupElement = getPopup();
7463 if (popupElement) {
7464 if (textareaWidth > initialPopupWidth) {
7465 popupElement.style.width = `${textareaWidth}px`;
7466 } else {
7467 applyNumericalStyle(popupElement, 'width', params.width);
7468 }
7469 }
7470 };
7471 new MutationObserver(textareaResizeHandler).observe(textareaElement, {
7472 attributes: true,
7473 attributeFilter: ['style']
7474 });
7475 }
7476 });
7477 return textareaElement;
7478 };
7479
7480 /**
7481 * @param {SweetAlert} instance
7482 * @param {SweetAlertOptions} params
7483 */
7484 const renderContent = (instance, params) => {
7485 const htmlContainer = getHtmlContainer();
7486 if (!htmlContainer) {
7487 return;
7488 }
7489 showWhenInnerHtmlPresent(htmlContainer);
7490 applyCustomClass(htmlContainer, params, 'htmlContainer');
7491
7492 // Content as HTML
7493 if (params.html) {
7494 parseHtmlToContainer(params.html, htmlContainer);
7495 show(htmlContainer, 'block');
7496 }
7497
7498 // Content as plain text
7499 else if (params.text) {
7500 htmlContainer.textContent = params.text;
7501 show(htmlContainer, 'block');
7502 }
7503
7504 // No content
7505 else {
7506 hide(htmlContainer);
7507 }
7508 renderInput(instance, params);
7509 };
7510
7511 /**
7512 * @param {SweetAlert} instance
7513 * @param {SweetAlertOptions} params
7514 */
7515 const renderFooter = (instance, params) => {
7516 const footer = getFooter();
7517 if (!footer) {
7518 return;
7519 }
7520 showWhenInnerHtmlPresent(footer);
7521 toggle(footer, Boolean(params.footer), 'block');
7522 if (params.footer) {
7523 parseHtmlToContainer(params.footer, footer);
7524 }
7525
7526 // Custom class
7527 applyCustomClass(footer, params, 'footer');
7528 };
7529
7530 /**
7531 * @param {SweetAlert} instance
7532 * @param {SweetAlertOptions} params
7533 */
7534 const renderIcon = (instance, params) => {
7535 const innerParams = privateProps.innerParams.get(instance);
7536 const icon = getIcon();
7537 if (!icon) {
7538 return;
7539 }
7540
7541 // if the given icon already rendered, apply the styling without re-rendering the icon
7542 if (innerParams && params.icon === innerParams.icon) {
7543 // Custom or default content
7544 setContent(icon, params);
7545 applyStyles(icon, params);
7546 return;
7547 }
7548 if (!params.icon && !params.iconHtml) {
7549 hide(icon);
7550 return;
7551 }
7552 if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
7553 error(`Unknown icon! Expected "success", "error", "warning", "info" or "question", got "${params.icon}"`);
7554 hide(icon);
7555 return;
7556 }
7557 show(icon);
7558
7559 // Custom or default content
7560 setContent(icon, params);
7561 applyStyles(icon, params);
7562
7563 // Animate icon
7564 addClass(icon, params.showClass && params.showClass.icon);
7565
7566 // Re-adjust the success icon on system theme change
7567 const colorSchemeQueryList = window.matchMedia('(prefers-color-scheme: dark)');
7568 colorSchemeQueryList.addEventListener('change', adjustSuccessIconBackgroundColor);
7569 };
7570
7571 /**
7572 * @param {HTMLElement} icon
7573 * @param {SweetAlertOptions} params
7574 */
7575 const applyStyles = (icon, params) => {
7576 for (const [iconType, iconClassName] of Object.entries(iconTypes)) {
7577 if (params.icon !== iconType) {
7578 removeClass(icon, iconClassName);
7579 }
7580 }
7581 addClass(icon, params.icon && iconTypes[params.icon]);
7582
7583 // Icon color
7584 setColor(icon, params);
7585
7586 // Success icon background color
7587 adjustSuccessIconBackgroundColor();
7588
7589 // Custom class
7590 applyCustomClass(icon, params, 'icon');
7591 };
7592
7593 // Adjust success icon background color to match the popup background color
7594 const adjustSuccessIconBackgroundColor = () => {
7595 const popup = getPopup();
7596 if (!popup) {
7597 return;
7598 }
7599 const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
7600 /** @type {NodeListOf<HTMLElement>} */
7601 const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
7602 for (let i = 0; i < successIconParts.length; i++) {
7603 successIconParts[i].style.backgroundColor = popupBackgroundColor;
7604 }
7605 };
7606
7607 /**
7608 *
7609 * @param {SweetAlertOptions} params
7610 * @returns {string}
7611 */
7612 const successIconHtml = params => `
7613 ${params.animation ? '<div class="swal2-success-circular-line-left"></div>' : ''}
7614 <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>
7615 <div class="swal2-success-ring"></div>
7616 ${params.animation ? '<div class="swal2-success-fix"></div>' : ''}
7617 ${params.animation ? '<div class="swal2-success-circular-line-right"></div>' : ''}
7618 `;
7619 const errorIconHtml = `
7620 <span class="swal2-x-mark">
7621 <span class="swal2-x-mark-line-left"></span>
7622 <span class="swal2-x-mark-line-right"></span>
7623 </span>
7624 `;
7625
7626 /**
7627 * @param {HTMLElement} icon
7628 * @param {SweetAlertOptions} params
7629 */
7630 const setContent = (icon, params) => {
7631 if (!params.icon && !params.iconHtml) {
7632 return;
7633 }
7634 let oldContent = icon.innerHTML;
7635 let newContent = '';
7636 if (params.iconHtml) {
7637 newContent = iconContent(params.iconHtml);
7638 } else if (params.icon === 'success') {
7639 newContent = successIconHtml(params);
7640 oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor()
7641 } else if (params.icon === 'error') {
7642 newContent = errorIconHtml;
7643 } else if (params.icon) {
7644 const defaultIconHtml = {
7645 question: '?',
7646 warning: '!',
7647 info: 'i'
7648 };
7649 newContent = iconContent(defaultIconHtml[params.icon]);
7650 }
7651 if (oldContent.trim() !== newContent.trim()) {
7652 setInnerHtml(icon, newContent);
7653 }
7654 };
7655
7656 /**
7657 * @param {HTMLElement} icon
7658 * @param {SweetAlertOptions} params
7659 */
7660 const setColor = (icon, params) => {
7661 if (!params.iconColor) {
7662 return;
7663 }
7664 icon.style.color = params.iconColor;
7665 icon.style.borderColor = params.iconColor;
7666 for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
7667 setStyle(icon, sel, 'background-color', params.iconColor);
7668 }
7669 setStyle(icon, '.swal2-success-ring', 'border-color', params.iconColor);
7670 };
7671
7672 /**
7673 * @param {string} content
7674 * @returns {string}
7675 */
7676 const iconContent = content => `<div class="${swalClasses['icon-content']}">${content}</div>`;
7677
7678 /**
7679 * @param {SweetAlert} instance
7680 * @param {SweetAlertOptions} params
7681 */
7682 const renderImage = (instance, params) => {
7683 const image = getImage();
7684 if (!image) {
7685 return;
7686 }
7687 if (!params.imageUrl) {
7688 hide(image);
7689 return;
7690 }
7691 show(image, '');
7692
7693 // Src, alt
7694 image.setAttribute('src', params.imageUrl);
7695 image.setAttribute('alt', params.imageAlt || '');
7696
7697 // Width, height
7698 applyNumericalStyle(image, 'width', params.imageWidth);
7699 applyNumericalStyle(image, 'height', params.imageHeight);
7700
7701 // Class
7702 image.className = swalClasses.image;
7703 applyCustomClass(image, params, 'image');
7704 };
7705
7706 let dragging = false;
7707 let mousedownX = 0;
7708 let mousedownY = 0;
7709 let initialX = 0;
7710 let initialY = 0;
7711
7712 /**
7713 * @param {HTMLElement} popup
7714 */
7715 const addDraggableListeners = popup => {
7716 popup.addEventListener('mousedown', down);
7717 document.body.addEventListener('mousemove', move);
7718 popup.addEventListener('mouseup', up);
7719 popup.addEventListener('touchstart', down);
7720 document.body.addEventListener('touchmove', move);
7721 popup.addEventListener('touchend', up);
7722 };
7723
7724 /**
7725 * @param {HTMLElement} popup
7726 */
7727 const removeDraggableListeners = popup => {
7728 popup.removeEventListener('mousedown', down);
7729 document.body.removeEventListener('mousemove', move);
7730 popup.removeEventListener('mouseup', up);
7731 popup.removeEventListener('touchstart', down);
7732 document.body.removeEventListener('touchmove', move);
7733 popup.removeEventListener('touchend', up);
7734 };
7735
7736 /**
7737 * @param {MouseEvent | TouchEvent} event
7738 */
7739 const down = event => {
7740 const popup = getPopup();
7741 if (!popup) {
7742 return;
7743 }
7744 const icon = getIcon();
7745 if (event.target === popup || icon && icon.contains(/** @type {HTMLElement} */event.target)) {
7746 dragging = true;
7747 const clientXY = getClientXY(event);
7748 mousedownX = clientXY.clientX;
7749 mousedownY = clientXY.clientY;
7750 initialX = parseInt(popup.style.insetInlineStart) || 0;
7751 initialY = parseInt(popup.style.insetBlockStart) || 0;
7752 addClass(popup, 'swal2-dragging');
7753 }
7754 };
7755
7756 /**
7757 * @param {MouseEvent | TouchEvent} event
7758 */
7759 const move = event => {
7760 const popup = getPopup();
7761 if (!popup) {
7762 return;
7763 }
7764 if (dragging) {
7765 let {
7766 clientX,
7767 clientY
7768 } = getClientXY(event);
7769 const deltaX = clientX - mousedownX;
7770 // In RTL mode, negate the horizontal delta since insetInlineStart refers to the right edge
7771 popup.style.insetInlineStart = `${initialX + (globalState.isRTL ? -deltaX : deltaX)}px`;
7772 popup.style.insetBlockStart = `${initialY + (clientY - mousedownY)}px`;
7773 }
7774 };
7775 const up = () => {
7776 const popup = getPopup();
7777 dragging = false;
7778 removeClass(popup, 'swal2-dragging');
7779 };
7780
7781 /**
7782 * @param {MouseEvent | TouchEvent} event
7783 * @returns {{ clientX: number, clientY: number }}
7784 */
7785 const getClientXY = event => {
7786 let clientX = 0,
7787 clientY = 0;
7788 if (event.type.startsWith('mouse')) {
7789 clientX = /** @type {MouseEvent} */event.clientX;
7790 clientY = /** @type {MouseEvent} */event.clientY;
7791 } else if (event.type.startsWith('touch')) {
7792 clientX = /** @type {TouchEvent} */event.touches[0].clientX;
7793 clientY = /** @type {TouchEvent} */event.touches[0].clientY;
7794 }
7795 return {
7796 clientX,
7797 clientY
7798 };
7799 };
7800
7801 /**
7802 * @param {SweetAlert} instance
7803 * @param {SweetAlertOptions} params
7804 */
7805 const renderPopup = (instance, params) => {
7806 const container = getContainer();
7807 const popup = getPopup();
7808 if (!container || !popup) {
7809 return;
7810 }
7811
7812 // Width
7813 // https://github.com/sweetalert2/sweetalert2/issues/2170
7814 if (params.toast) {
7815 applyNumericalStyle(container, 'width', params.width);
7816 popup.style.width = '100%';
7817 const loader = getLoader();
7818 if (loader) {
7819 popup.insertBefore(loader, getIcon());
7820 }
7821 } else {
7822 applyNumericalStyle(popup, 'width', params.width);
7823 }
7824
7825 // Padding
7826 applyNumericalStyle(popup, 'padding', params.padding);
7827
7828 // Color
7829 if (params.color) {
7830 popup.style.color = params.color;
7831 }
7832
7833 // Background
7834 if (params.background) {
7835 popup.style.background = params.background;
7836 }
7837 hide(getValidationMessage());
7838
7839 // Classes
7840 addClasses$1(popup, params);
7841 if (params.draggable && !params.toast) {
7842 addClass(popup, swalClasses.draggable);
7843 addDraggableListeners(popup);
7844 } else {
7845 removeClass(popup, swalClasses.draggable);
7846 removeDraggableListeners(popup);
7847 }
7848 };
7849
7850 /**
7851 * @param {HTMLElement} popup
7852 * @param {SweetAlertOptions} params
7853 */
7854 const addClasses$1 = (popup, params) => {
7855 const showClass = params.showClass || {};
7856 // Default Class + showClass when updating Swal.update({})
7857 popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? showClass.popup : ''}`;
7858 if (params.toast) {
7859 addClass([document.documentElement, document.body], swalClasses['toast-shown']);
7860 addClass(popup, swalClasses.toast);
7861 } else {
7862 addClass(popup, swalClasses.modal);
7863 }
7864
7865 // Custom class
7866 applyCustomClass(popup, params, 'popup');
7867 // TODO: remove in the next major
7868 if (typeof params.customClass === 'string') {
7869 addClass(popup, params.customClass);
7870 }
7871
7872 // Icon class (#1842)
7873 if (params.icon) {
7874 addClass(popup, swalClasses[`icon-${params.icon}`]);
7875 }
7876 };
7877
7878 /**
7879 * @param {SweetAlert} instance
7880 * @param {SweetAlertOptions} params
7881 */
7882 const renderProgressSteps = (instance, params) => {
7883 const progressStepsContainer = getProgressSteps();
7884 if (!progressStepsContainer) {
7885 return;
7886 }
7887 const {
7888 progressSteps,
7889 currentProgressStep
7890 } = params;
7891 if (!progressSteps || progressSteps.length === 0 || currentProgressStep === undefined) {
7892 hide(progressStepsContainer);
7893 return;
7894 }
7895 show(progressStepsContainer);
7896 progressStepsContainer.textContent = '';
7897 if (currentProgressStep >= progressSteps.length) {
7898 warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
7899 }
7900 progressSteps.forEach((step, index) => {
7901 const stepEl = createStepElement(step);
7902 progressStepsContainer.appendChild(stepEl);
7903 if (index === currentProgressStep) {
7904 addClass(stepEl, swalClasses['active-progress-step']);
7905 }
7906 if (index !== progressSteps.length - 1) {
7907 const lineEl = createLineElement(params);
7908 progressStepsContainer.appendChild(lineEl);
7909 }
7910 });
7911 };
7912
7913 /**
7914 * @param {string} step
7915 * @returns {HTMLLIElement}
7916 */
7917 const createStepElement = step => {
7918 const stepEl = document.createElement('li');
7919 addClass(stepEl, swalClasses['progress-step']);
7920 setInnerHtml(stepEl, step);
7921 return stepEl;
7922 };
7923
7924 /**
7925 * @param {SweetAlertOptions} params
7926 * @returns {HTMLLIElement}
7927 */
7928 const createLineElement = params => {
7929 const lineEl = document.createElement('li');
7930 addClass(lineEl, swalClasses['progress-step-line']);
7931 if (params.progressStepsDistance) {
7932 applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);
7933 }
7934 return lineEl;
7935 };
7936
7937 /**
7938 * @param {SweetAlert} instance
7939 * @param {SweetAlertOptions} params
7940 */
7941 const renderTitle = (instance, params) => {
7942 const title = getTitle();
7943 if (!title) {
7944 return;
7945 }
7946 showWhenInnerHtmlPresent(title);
7947 toggle(title, Boolean(params.title || params.titleText), 'block');
7948 if (params.title) {
7949 parseHtmlToContainer(params.title, title);
7950 }
7951 if (params.titleText) {
7952 title.innerText = params.titleText;
7953 }
7954
7955 // Custom class
7956 applyCustomClass(title, params, 'title');
7957 };
7958
7959 /**
7960 * @param {SweetAlert} instance
7961 * @param {SweetAlertOptions} params
7962 */
7963 const render = (instance, params) => {
7964 var _globalState$eventEmi;
7965 renderPopup(instance, params);
7966 renderContainer(instance, params);
7967 renderProgressSteps(instance, params);
7968 renderIcon(instance, params);
7969 renderImage(instance, params);
7970 renderTitle(instance, params);
7971 renderCloseButton(instance, params);
7972 renderContent(instance, params);
7973 renderActions(instance, params);
7974 renderFooter(instance, params);
7975 const popup = getPopup();
7976 if (typeof params.didRender === 'function' && popup) {
7977 params.didRender(popup);
7978 }
7979 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('didRender', popup);
7980 };
7981
7982 /*
7983 * Global function to determine if SweetAlert2 popup is shown
7984 */
7985 const isVisible = () => {
7986 return isVisible$1(getPopup());
7987 };
7988
7989 /*
7990 * Global function to click 'Confirm' button
7991 */
7992 const clickConfirm = () => {
7993 var _dom$getConfirmButton;
7994 return (_dom$getConfirmButton = getConfirmButton()) === null || _dom$getConfirmButton === void 0 ? void 0 : _dom$getConfirmButton.click();
7995 };
7996
7997 /*
7998 * Global function to click 'Deny' button
7999 */
8000 const clickDeny = () => {
8001 var _dom$getDenyButton;
8002 return (_dom$getDenyButton = getDenyButton()) === null || _dom$getDenyButton === void 0 ? void 0 : _dom$getDenyButton.click();
8003 };
8004
8005 /*
8006 * Global function to click 'Cancel' button
8007 */
8008 const clickCancel = () => {
8009 var _dom$getCancelButton;
8010 return (_dom$getCancelButton = getCancelButton()) === null || _dom$getCancelButton === void 0 ? void 0 : _dom$getCancelButton.click();
8011 };
8012
8013 /** @type {Record<DismissReason, DismissReason>} */
8014 const DismissReason = Object.freeze({
8015 cancel: 'cancel',
8016 backdrop: 'backdrop',
8017 close: 'close',
8018 esc: 'esc',
8019 timer: 'timer'
8020 });
8021
8022 /**
8023 * @param {GlobalState} globalState
8024 */
8025 const removeKeydownHandler = globalState => {
8026 if (globalState.keydownTarget && globalState.keydownHandlerAdded && globalState.keydownHandler) {
8027 const handler = /** @type {EventListenerOrEventListenerObject} */ /** @type {unknown} */globalState.keydownHandler;
8028 globalState.keydownTarget.removeEventListener('keydown', handler, {
8029 capture: globalState.keydownListenerCapture
8030 });
8031 globalState.keydownHandlerAdded = false;
8032 }
8033 };
8034
8035 /**
8036 * @param {GlobalState} globalState
8037 * @param {SweetAlertOptions} innerParams
8038 * @param {(dismiss: DismissReason) => void} dismissWith
8039 */
8040 const addKeydownHandler = (globalState, innerParams, dismissWith) => {
8041 removeKeydownHandler(globalState);
8042 if (!innerParams.toast) {
8043 /** @type {(this: HTMLElement, event: KeyboardEvent) => void} */
8044 const handler = e => keydownHandler(innerParams, e, dismissWith);
8045 globalState.keydownHandler = handler;
8046 const target = innerParams.keydownListenerCapture ? window : getPopup();
8047 if (target) {
8048 globalState.keydownTarget = target;
8049 globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
8050 const eventHandler = /** @type {EventListenerOrEventListenerObject} */ /** @type {unknown} */handler;
8051 globalState.keydownTarget.addEventListener('keydown', eventHandler, {
8052 capture: globalState.keydownListenerCapture
8053 });
8054 globalState.keydownHandlerAdded = true;
8055 }
8056 }
8057 };
8058
8059 /**
8060 * @param {number} index
8061 * @param {number} increment
8062 */
8063 const setFocus = (index, increment) => {
8064 var _dom$getPopup;
8065 const focusableElements = getFocusableElements();
8066 // search for visible elements and select the next possible match
8067 if (focusableElements.length) {
8068 index = index + increment;
8069
8070 // shift + tab when .swal2-popup is focused
8071 if (index === -2) {
8072 index = focusableElements.length - 1;
8073 }
8074
8075 // rollover to first item
8076 if (index === focusableElements.length) {
8077 index = 0;
8078
8079 // go to last item
8080 } else if (index === -1) {
8081 index = focusableElements.length - 1;
8082 }
8083 focusableElements[index].focus();
8084 return;
8085 }
8086 // no visible focusable elements, focus the popup
8087 (_dom$getPopup = getPopup()) === null || _dom$getPopup === void 0 || _dom$getPopup.focus();
8088 };
8089 const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
8090 const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
8091
8092 /**
8093 * @param {SweetAlertOptions} innerParams
8094 * @param {KeyboardEvent} event
8095 * @param {(dismiss: DismissReason) => void} dismissWith
8096 */
8097 const keydownHandler = (innerParams, event, dismissWith) => {
8098 if (!innerParams) {
8099 return; // This instance has already been destroyed
8100 }
8101
8102 // Ignore keydown during IME composition
8103 // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition
8104 // https://github.com/sweetalert2/sweetalert2/issues/720
8105 // https://github.com/sweetalert2/sweetalert2/issues/2406
8106 if (event.isComposing || event.keyCode === 229) {
8107 return;
8108 }
8109 if (innerParams.stopKeydownPropagation) {
8110 event.stopPropagation();
8111 }
8112
8113 // ENTER
8114 if (event.key === 'Enter') {
8115 handleEnter(event, innerParams);
8116 }
8117
8118 // TAB
8119 else if (event.key === 'Tab') {
8120 handleTab(event);
8121 }
8122
8123 // ARROWS - switch focus between buttons
8124 else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) {
8125 handleArrows(event.key);
8126 }
8127
8128 // ESC
8129 else if (event.key === 'Escape') {
8130 handleEsc(event, innerParams, dismissWith);
8131 }
8132 };
8133
8134 /**
8135 * @param {KeyboardEvent} event
8136 * @param {SweetAlertOptions} innerParams
8137 */
8138 const handleEnter = (event, innerParams) => {
8139 // https://github.com/sweetalert2/sweetalert2/issues/2386
8140 if (!callIfFunction(innerParams.allowEnterKey)) {
8141 return;
8142 }
8143 const popup = getPopup();
8144 if (!popup || !innerParams.input) {
8145 return;
8146 }
8147 const input = getInput$1(popup, innerParams.input);
8148 if (event.target && input && event.target instanceof HTMLElement && event.target.outerHTML === input.outerHTML) {
8149 if (['textarea', 'file'].includes(innerParams.input)) {
8150 return; // do not submit
8151 }
8152 clickConfirm();
8153 event.preventDefault();
8154 }
8155 };
8156
8157 /**
8158 * @param {KeyboardEvent} event
8159 */
8160 const handleTab = event => {
8161 const targetElement = event.target;
8162 const focusableElements = getFocusableElements();
8163 let btnIndex = -1;
8164 for (let i = 0; i < focusableElements.length; i++) {
8165 if (targetElement === focusableElements[i]) {
8166 btnIndex = i;
8167 break;
8168 }
8169 }
8170
8171 // Cycle to the next button
8172 if (!event.shiftKey) {
8173 setFocus(btnIndex, 1);
8174 }
8175
8176 // Cycle to the prev button
8177 else {
8178 setFocus(btnIndex, -1);
8179 }
8180 event.stopPropagation();
8181 event.preventDefault();
8182 };
8183
8184 /**
8185 * @param {string} key
8186 */
8187 const handleArrows = key => {
8188 const actions = getActions();
8189 const confirmButton = getConfirmButton();
8190 const denyButton = getDenyButton();
8191 const cancelButton = getCancelButton();
8192 if (!actions || !confirmButton || !denyButton || !cancelButton) {
8193 return;
8194 }
8195 /** @type HTMLElement[] */
8196 const buttons = [confirmButton, denyButton, cancelButton];
8197 if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) {
8198 return;
8199 }
8200 const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
8201 let buttonToFocus = document.activeElement;
8202 if (!buttonToFocus) {
8203 return;
8204 }
8205 for (let i = 0; i < actions.children.length; i++) {
8206 buttonToFocus = buttonToFocus[sibling];
8207 if (!buttonToFocus) {
8208 return;
8209 }
8210 if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) {
8211 break;
8212 }
8213 }
8214 if (buttonToFocus instanceof HTMLButtonElement) {
8215 buttonToFocus.focus();
8216 }
8217 };
8218
8219 /**
8220 * @param {KeyboardEvent} event
8221 * @param {SweetAlertOptions} innerParams
8222 * @param {(dismiss: DismissReason) => void} dismissWith
8223 */
8224 const handleEsc = (event, innerParams, dismissWith) => {
8225 event.preventDefault();
8226 if (callIfFunction(innerParams.allowEscapeKey)) {
8227 dismissWith(DismissReason.esc);
8228 }
8229 };
8230
8231 /**
8232 * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
8233 * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
8234 * This is the approach that Babel will probably take to implement private methods/fields
8235 * https://github.com/tc39/proposal-private-methods
8236 * https://github.com/babel/babel/pull/7555
8237 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
8238 * then we can use that language feature.
8239 */
8240
8241 var privateMethods = {
8242 swalPromiseResolve: new WeakMap(),
8243 swalPromiseReject: new WeakMap()
8244 };
8245
8246 // From https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/
8247 // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
8248 // elements not within the active modal dialog will not be surfaced if a user opens a screen
8249 // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
8250
8251 const setAriaHidden = () => {
8252 const container = getContainer();
8253 const bodyChildren = Array.from(document.body.children);
8254 bodyChildren.forEach(el => {
8255 if (el.contains(container)) {
8256 return;
8257 }
8258 if (el.hasAttribute('aria-hidden')) {
8259 el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden') || '');
8260 }
8261 el.setAttribute('aria-hidden', 'true');
8262 });
8263 };
8264 const unsetAriaHidden = () => {
8265 const bodyChildren = Array.from(document.body.children);
8266 bodyChildren.forEach(el => {
8267 if (el.hasAttribute('data-previous-aria-hidden')) {
8268 el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden') || '');
8269 el.removeAttribute('data-previous-aria-hidden');
8270 } else {
8271 el.removeAttribute('aria-hidden');
8272 }
8273 });
8274 };
8275
8276 // @ts-ignore
8277 const isSafariOrIOS = typeof window !== 'undefined' && Boolean(window.GestureEvent); // true for Safari desktop + all iOS browsers https://stackoverflow.com/a/70585394
8278
8279 /**
8280 * Fix iOS scrolling
8281 * http://stackoverflow.com/q/39626302
8282 */
8283 const iOSfix = () => {
8284 if (isSafariOrIOS && !hasClass(document.body, swalClasses.iosfix)) {
8285 const offset = document.body.scrollTop;
8286 document.body.style.top = `${offset * -1}px`;
8287 addClass(document.body, swalClasses.iosfix);
8288 lockBodyScroll();
8289 }
8290 };
8291
8292 /**
8293 * https://github.com/sweetalert2/sweetalert2/issues/1246
8294 */
8295 const lockBodyScroll = () => {
8296 const container = getContainer();
8297 if (!container) {
8298 return;
8299 }
8300 /** @type {boolean} */
8301 let preventTouchMove;
8302 /**
8303 * @param {TouchEvent} event
8304 */
8305 container.ontouchstart = event => {
8306 preventTouchMove = shouldPreventTouchMove(event);
8307 };
8308 /**
8309 * @param {TouchEvent} event
8310 */
8311 container.ontouchmove = event => {
8312 if (preventTouchMove) {
8313 event.preventDefault();
8314 event.stopPropagation();
8315 }
8316 };
8317 };
8318
8319 /**
8320 * @param {TouchEvent} event
8321 * @returns {boolean}
8322 */
8323 const shouldPreventTouchMove = event => {
8324 const target = event.target;
8325 const container = getContainer();
8326 const htmlContainer = getHtmlContainer();
8327 if (!container || !htmlContainer) {
8328 return false;
8329 }
8330 if (isStylus(event) || isZoom(event)) {
8331 return false;
8332 }
8333 if (target === container) {
8334 return true;
8335 }
8336 if (!isScrollable(container) && target instanceof HTMLElement && !selfOrParentIsScrollable(target, htmlContainer) &&
8337 // #2823
8338 target.tagName !== 'INPUT' &&
8339 // #1603
8340 target.tagName !== 'TEXTAREA' &&
8341 // #2266
8342 !(isScrollable(htmlContainer) &&
8343 // #1944
8344 htmlContainer.contains(target))) {
8345 return true;
8346 }
8347 return false;
8348 };
8349
8350 /**
8351 * https://github.com/sweetalert2/sweetalert2/issues/1786
8352 *
8353 * @param {TouchEvent} event
8354 * @returns {boolean}
8355 */
8356 const isStylus = event => {
8357 return Boolean(event.touches && event.touches.length &&
8358 // @ts-ignore - touchType is not a standard property
8359 event.touches[0].touchType === 'stylus');
8360 };
8361
8362 /**
8363 * https://github.com/sweetalert2/sweetalert2/issues/1891
8364 *
8365 * @param {TouchEvent} event
8366 * @returns {boolean}
8367 */
8368 const isZoom = event => {
8369 return event.touches && event.touches.length > 1;
8370 };
8371 const undoIOSfix = () => {
8372 if (hasClass(document.body, swalClasses.iosfix)) {
8373 const offset = parseInt(document.body.style.top, 10);
8374 removeClass(document.body, swalClasses.iosfix);
8375 document.body.style.top = '';
8376 document.body.scrollTop = offset * -1;
8377 }
8378 };
8379
8380 /**
8381 * Measure scrollbar width for padding body during modal show/hide
8382 * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
8383 *
8384 * @returns {number}
8385 */
8386 const measureScrollbar = () => {
8387 const scrollDiv = document.createElement('div');
8388 scrollDiv.className = swalClasses['scrollbar-measure'];
8389 document.body.appendChild(scrollDiv);
8390 const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
8391 document.body.removeChild(scrollDiv);
8392 return scrollbarWidth;
8393 };
8394
8395 /**
8396 * Remember state in cases where opening and handling a modal will fiddle with it.
8397 * @type {number | null}
8398 */
8399 let previousBodyPadding = null;
8400
8401 /**
8402 * @param {string} initialBodyOverflow
8403 */
8404 const replaceScrollbarWithPadding = initialBodyOverflow => {
8405 // for queues, do not do this more than once
8406 if (previousBodyPadding !== null) {
8407 return;
8408 }
8409 // if the body has overflow
8410 if (document.body.scrollHeight > window.innerHeight || initialBodyOverflow === 'scroll' // https://github.com/sweetalert2/sweetalert2/issues/2663
8411 ) {
8412 // add padding so the content doesn't shift after removal of scrollbar
8413 previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
8414 document.body.style.paddingRight = `${previousBodyPadding + measureScrollbar()}px`;
8415 }
8416 };
8417 const undoReplaceScrollbarWithPadding = () => {
8418 if (previousBodyPadding !== null) {
8419 document.body.style.paddingRight = `${previousBodyPadding}px`;
8420 previousBodyPadding = null;
8421 }
8422 };
8423
8424 /**
8425 * @param {SweetAlert} instance
8426 * @param {HTMLElement} container
8427 * @param {boolean} returnFocus
8428 * @param {(() => void) | undefined} didClose
8429 */
8430 function removePopupAndResetState(instance, container, returnFocus, didClose) {
8431 if (isToast()) {
8432 triggerDidCloseAndDispose(instance, didClose);
8433 } else {
8434 restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
8435 removeKeydownHandler(globalState);
8436 }
8437
8438 // workaround for https://github.com/sweetalert2/sweetalert2/issues/2088
8439 // for some reason removing the container in Safari will scroll the document to bottom
8440 if (isSafariOrIOS) {
8441 container.setAttribute('style', 'display:none !important');
8442 container.removeAttribute('class');
8443 container.innerHTML = '';
8444 } else {
8445 container.remove();
8446 }
8447 if (isModal()) {
8448 undoReplaceScrollbarWithPadding();
8449 undoIOSfix();
8450 unsetAriaHidden();
8451 }
8452 removeBodyClasses();
8453 }
8454
8455 /**
8456 * Remove SweetAlert2 classes from body
8457 */
8458 function removeBodyClasses() {
8459 removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
8460 }
8461
8462 /**
8463 * Instance method to close sweetAlert
8464 *
8465 * @param {SweetAlertResult | undefined} resolveValue
8466 * @this {SweetAlert}
8467 */
8468 function close(resolveValue) {
8469 resolveValue = prepareResolveValue(resolveValue);
8470 const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
8471 const didClose = triggerClosePopup(this);
8472 if (this.isAwaitingPromise) {
8473 // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
8474 if (!resolveValue.isDismissed) {
8475 handleAwaitingPromise(this);
8476 swalPromiseResolve(resolveValue);
8477 }
8478 } else if (didClose) {
8479 // Resolve Swal promise
8480 swalPromiseResolve(resolveValue);
8481 }
8482 }
8483
8484 /**
8485 * @param {SweetAlert} instance
8486 * @returns {boolean}
8487 */
8488 const triggerClosePopup = instance => {
8489 const popup = getPopup();
8490 if (!popup) {
8491 return false;
8492 }
8493 const innerParams = privateProps.innerParams.get(instance);
8494 if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
8495 return false;
8496 }
8497 removeClass(popup, innerParams.showClass.popup);
8498 addClass(popup, innerParams.hideClass.popup);
8499 const backdrop = getContainer();
8500 removeClass(backdrop, innerParams.showClass.backdrop);
8501 addClass(backdrop, innerParams.hideClass.backdrop);
8502 handlePopupAnimation(instance, popup, innerParams);
8503 return true;
8504 };
8505
8506 /**
8507 * @param {Error | string} error
8508 * @this {SweetAlert}
8509 */
8510 function rejectPromise(error) {
8511 const rejectPromise = privateMethods.swalPromiseReject.get(this);
8512 handleAwaitingPromise(this);
8513 if (rejectPromise) {
8514 // Reject Swal promise
8515 rejectPromise(error);
8516 }
8517 }
8518
8519 /**
8520 * @param {SweetAlert} instance
8521 */
8522 const handleAwaitingPromise = instance => {
8523 if (instance.isAwaitingPromise) {
8524 // @ts-ignore
8525 delete instance.isAwaitingPromise;
8526 // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
8527 if (!privateProps.innerParams.get(instance)) {
8528 instance._destroy();
8529 }
8530 }
8531 };
8532
8533 /**
8534 * @param {SweetAlertResult | undefined} resolveValue
8535 * @returns {SweetAlertResult}
8536 */
8537 const prepareResolveValue = resolveValue => {
8538 // When user calls Swal.close()
8539 if (typeof resolveValue === 'undefined') {
8540 return {
8541 isConfirmed: false,
8542 isDenied: false,
8543 isDismissed: true
8544 };
8545 }
8546 return Object.assign({
8547 isConfirmed: false,
8548 isDenied: false,
8549 isDismissed: false
8550 }, resolveValue);
8551 };
8552
8553 /**
8554 * @param {SweetAlert} instance
8555 * @param {HTMLElement} popup
8556 * @param {SweetAlertOptions} innerParams
8557 */
8558 const handlePopupAnimation = (instance, popup, innerParams) => {
8559 var _globalState$eventEmi;
8560 const container = getContainer();
8561 // If animation is supported, animate
8562 const animationIsSupported = hasCssAnimation(popup);
8563 if (typeof innerParams.willClose === 'function') {
8564 innerParams.willClose(popup);
8565 }
8566 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('willClose', popup);
8567 if (animationIsSupported && container) {
8568 animatePopup(instance, popup, container, Boolean(innerParams.returnFocus), innerParams.didClose);
8569 } else if (container) {
8570 // Otherwise, remove immediately
8571 removePopupAndResetState(instance, container, Boolean(innerParams.returnFocus), innerParams.didClose);
8572 }
8573 };
8574
8575 /**
8576 * @param {SweetAlert} instance
8577 * @param {HTMLElement} popup
8578 * @param {HTMLElement} container
8579 * @param {boolean} returnFocus
8580 * @param {(() => void) | undefined} didClose
8581 */
8582 const animatePopup = (instance, popup, container, returnFocus, didClose) => {
8583 globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
8584 /**
8585 * @param {AnimationEvent | TransitionEvent} e
8586 */
8587 const swalCloseAnimationFinished = function (e) {
8588 if (e.target === popup) {
8589 var _globalState$swalClos;
8590 (_globalState$swalClos = globalState.swalCloseEventFinishedCallback) === null || _globalState$swalClos === void 0 || _globalState$swalClos.call(globalState);
8591 delete globalState.swalCloseEventFinishedCallback;
8592 popup.removeEventListener('animationend', swalCloseAnimationFinished);
8593 popup.removeEventListener('transitionend', swalCloseAnimationFinished);
8594 }
8595 };
8596 popup.addEventListener('animationend', swalCloseAnimationFinished);
8597 popup.addEventListener('transitionend', swalCloseAnimationFinished);
8598 };
8599
8600 /**
8601 * @param {SweetAlert} instance
8602 * @param {(() => void) | undefined} didClose
8603 */
8604 const triggerDidCloseAndDispose = (instance, didClose) => {
8605 setTimeout(() => {
8606 var _globalState$eventEmi2;
8607 if (typeof didClose === 'function') {
8608 didClose.bind(instance.params)();
8609 }
8610 (_globalState$eventEmi2 = globalState.eventEmitter) === null || _globalState$eventEmi2 === void 0 || _globalState$eventEmi2.emit('didClose');
8611 // instance might have been destroyed already
8612 if (instance._destroy) {
8613 instance._destroy();
8614 }
8615 });
8616 };
8617
8618 /**
8619 * Shows loader (spinner), this is useful with AJAX requests.
8620 * By default the loader be shown instead of the "Confirm" button.
8621 *
8622 * @param {HTMLButtonElement | null} [buttonToReplace]
8623 */
8624 const showLoading = buttonToReplace => {
8625 let popup = getPopup();
8626 if (!popup) {
8627 new Swal();
8628 }
8629 popup = getPopup();
8630 if (!popup) {
8631 return;
8632 }
8633 const loader = getLoader();
8634 if (isToast()) {
8635 hide(getIcon());
8636 } else {
8637 replaceButton(popup, buttonToReplace);
8638 }
8639 show(loader);
8640 popup.setAttribute('data-loading', 'true');
8641 popup.setAttribute('aria-busy', 'true');
8642 popup.focus();
8643 };
8644
8645 /**
8646 * @param {HTMLElement} popup
8647 * @param {HTMLButtonElement | null} [buttonToReplace]
8648 */
8649 const replaceButton = (popup, buttonToReplace) => {
8650 const actions = getActions();
8651 const loader = getLoader();
8652 if (!actions || !loader) {
8653 return;
8654 }
8655 if (!buttonToReplace && isVisible$1(getConfirmButton())) {
8656 buttonToReplace = getConfirmButton();
8657 }
8658 show(actions);
8659 if (buttonToReplace) {
8660 hide(buttonToReplace);
8661 loader.setAttribute('data-button-to-replace', buttonToReplace.className);
8662 actions.insertBefore(loader, buttonToReplace);
8663 }
8664 addClass([popup, actions], swalClasses.loading);
8665 };
8666
8667 /**
8668 * @param {SweetAlert} instance
8669 * @param {SweetAlertOptions} params
8670 */
8671 const handleInputOptionsAndValue = (instance, params) => {
8672 if (params.input === 'select' || params.input === 'radio') {
8673 handleInputOptions(instance, params);
8674 } else if (['text', 'email', 'number', 'tel', 'textarea'].some(i => i === params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
8675 showLoading(getConfirmButton());
8676 handleInputValue(instance, params);
8677 }
8678 };
8679
8680 /**
8681 * @param {SweetAlert} instance
8682 * @param {SweetAlertOptions} innerParams
8683 * @returns {SweetAlertInputValue}
8684 */
8685 const getInputValue = (instance, innerParams) => {
8686 const input = instance.getInput();
8687 if (!input) {
8688 return null;
8689 }
8690 switch (innerParams.input) {
8691 case 'checkbox':
8692 return getCheckboxValue(input);
8693 case 'radio':
8694 return getRadioValue(input);
8695 case 'file':
8696 return getFileValue(input);
8697 default:
8698 return innerParams.inputAutoTrim ? input.value.trim() : input.value;
8699 }
8700 };
8701
8702 /**
8703 * @param {HTMLInputElement} input
8704 * @returns {number}
8705 */
8706 const getCheckboxValue = input => input.checked ? 1 : 0;
8707
8708 /**
8709 * @param {HTMLInputElement} input
8710 * @returns {string | null}
8711 */
8712 const getRadioValue = input => input.checked ? input.value : null;
8713
8714 /**
8715 * @param {HTMLInputElement} input
8716 * @returns {FileList | File | null}
8717 */
8718 const getFileValue = input => input.files && input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
8719
8720 /**
8721 * @param {SweetAlert} instance
8722 * @param {SweetAlertOptions} params
8723 */
8724 const handleInputOptions = (instance, params) => {
8725 const popup = getPopup();
8726 if (!popup) {
8727 return;
8728 }
8729 /**
8730 * @param {*} inputOptions
8731 */
8732 const processInputOptions = inputOptions => {
8733 if (params.input === 'select') {
8734 populateSelectOptions(popup, formatInputOptions(inputOptions), params);
8735 } else if (params.input === 'radio') {
8736 populateRadioOptions(popup, formatInputOptions(inputOptions), params);
8737 }
8738 };
8739 if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
8740 showLoading(getConfirmButton());
8741 asPromise(params.inputOptions).then(inputOptions => {
8742 instance.hideLoading();
8743 processInputOptions(inputOptions);
8744 });
8745 } else if (typeof params.inputOptions === 'object') {
8746 processInputOptions(params.inputOptions);
8747 } else {
8748 error(`Unexpected type of inputOptions! Expected object, Map or Promise, got ${typeof params.inputOptions}`);
8749 }
8750 };
8751
8752 /**
8753 * @param {SweetAlert} instance
8754 * @param {SweetAlertOptions} params
8755 */
8756 const handleInputValue = (instance, params) => {
8757 const input = instance.getInput();
8758 if (!input) {
8759 return;
8760 }
8761 hide(input);
8762 asPromise(params.inputValue).then(inputValue => {
8763 input.value = params.input === 'number' ? `${parseFloat(inputValue) || 0}` : `${inputValue}`;
8764 show(input);
8765 input.focus();
8766 instance.hideLoading();
8767 }).catch(err => {
8768 error(`Error in inputValue promise: ${err}`);
8769 input.value = '';
8770 show(input);
8771 input.focus();
8772 instance.hideLoading();
8773 });
8774 };
8775
8776 /**
8777 * @param {HTMLElement} popup
8778 * @param {InputOptionFlattened[]} inputOptions
8779 * @param {SweetAlertOptions} params
8780 */
8781 function populateSelectOptions(popup, inputOptions, params) {
8782 const select = getDirectChildByClass(popup, swalClasses.select);
8783 if (!select) {
8784 return;
8785 }
8786 /**
8787 * @param {HTMLElement} parent
8788 * @param {string} optionLabel
8789 * @param {string} optionValue
8790 */
8791 const renderOption = (parent, optionLabel, optionValue) => {
8792 const option = document.createElement('option');
8793 option.value = optionValue;
8794 setInnerHtml(option, optionLabel);
8795 option.selected = isSelected(optionValue, params.inputValue);
8796 parent.appendChild(option);
8797 };
8798 inputOptions.forEach(inputOption => {
8799 const optionValue = inputOption[0];
8800 const optionLabel = inputOption[1];
8801 // <optgroup> spec:
8802 // https://www.w3.org/TR/html401/interact/forms.html#h-17.6
8803 // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
8804 // check whether this is a <optgroup>
8805 if (Array.isArray(optionLabel)) {
8806 // if it is an array, then it is an <optgroup>
8807 const optgroup = document.createElement('optgroup');
8808 optgroup.label = optionValue;
8809 optgroup.disabled = false; // not configurable for now
8810 select.appendChild(optgroup);
8811 optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
8812 } else {
8813 // case of <option>
8814 renderOption(select, optionLabel, optionValue);
8815 }
8816 });
8817 select.focus();
8818 }
8819
8820 /**
8821 * @param {HTMLElement} popup
8822 * @param {InputOptionFlattened[]} inputOptions
8823 * @param {SweetAlertOptions} params
8824 */
8825 function populateRadioOptions(popup, inputOptions, params) {
8826 const radio = getDirectChildByClass(popup, swalClasses.radio);
8827 if (!radio) {
8828 return;
8829 }
8830 inputOptions.forEach(inputOption => {
8831 const radioValue = inputOption[0];
8832 const radioLabel = inputOption[1];
8833 const radioInput = document.createElement('input');
8834 const radioLabelElement = document.createElement('label');
8835 radioInput.type = 'radio';
8836 radioInput.name = swalClasses.radio;
8837 radioInput.value = radioValue;
8838 if (isSelected(radioValue, params.inputValue)) {
8839 radioInput.checked = true;
8840 }
8841 const label = document.createElement('span');
8842 setInnerHtml(label, radioLabel);
8843 label.className = swalClasses.label;
8844 radioLabelElement.appendChild(radioInput);
8845 radioLabelElement.appendChild(label);
8846 radio.appendChild(radioLabelElement);
8847 });
8848 const radios = radio.querySelectorAll('input');
8849 if (radios.length) {
8850 radios[0].focus();
8851 }
8852 }
8853
8854 /**
8855 * Converts `inputOptions` into an array of `[value, label]`s
8856 *
8857 * @param {*} inputOptions
8858 * @typedef {string[]} InputOptionFlattened
8859 * @returns {InputOptionFlattened[]}
8860 */
8861 const formatInputOptions = inputOptions => {
8862 /** @type {InputOptionFlattened[]} */
8863 const result = [];
8864 if (inputOptions instanceof Map) {
8865 inputOptions.forEach((value, key) => {
8866 let valueFormatted = value;
8867 if (typeof valueFormatted === 'object') {
8868 // case of <optgroup>
8869 valueFormatted = formatInputOptions(valueFormatted);
8870 }
8871 result.push([key, valueFormatted]);
8872 });
8873 } else {
8874 Object.keys(inputOptions).forEach(key => {
8875 let valueFormatted = inputOptions[key];
8876 if (typeof valueFormatted === 'object') {
8877 // case of <optgroup>
8878 valueFormatted = formatInputOptions(valueFormatted);
8879 }
8880 result.push([key, valueFormatted]);
8881 });
8882 }
8883 return result;
8884 };
8885
8886 /**
8887 * @param {string} optionValue
8888 * @param {SweetAlertInputValue} inputValue
8889 * @returns {boolean}
8890 */
8891 const isSelected = (optionValue, inputValue) => {
8892 return Boolean(inputValue) && inputValue !== null && inputValue !== undefined && inputValue.toString() === optionValue.toString();
8893 };
8894
8895 /**
8896 * @param {SweetAlert} instance
8897 */
8898 const handleConfirmButtonClick = instance => {
8899 const innerParams = privateProps.innerParams.get(instance);
8900 instance.disableButtons();
8901 if (innerParams.input) {
8902 handleConfirmOrDenyWithInput(instance, 'confirm');
8903 } else {
8904 confirm(instance, true);
8905 }
8906 };
8907
8908 /**
8909 * @param {SweetAlert} instance
8910 */
8911 const handleDenyButtonClick = instance => {
8912 const innerParams = privateProps.innerParams.get(instance);
8913 instance.disableButtons();
8914 if (innerParams.returnInputValueOnDeny) {
8915 handleConfirmOrDenyWithInput(instance, 'deny');
8916 } else {
8917 deny(instance, false);
8918 }
8919 };
8920
8921 /**
8922 * @param {SweetAlert} instance
8923 * @param {(dismiss: DismissReason) => void} dismissWith
8924 */
8925 const handleCancelButtonClick = (instance, dismissWith) => {
8926 instance.disableButtons();
8927 dismissWith(DismissReason.cancel);
8928 };
8929
8930 /**
8931 * @param {SweetAlert} instance
8932 * @param {'confirm' | 'deny'} type
8933 */
8934 const handleConfirmOrDenyWithInput = (instance, type) => {
8935 const innerParams = privateProps.innerParams.get(instance);
8936 if (!innerParams.input) {
8937 error(`The "input" parameter is needed to be set when using returnInputValueOn${capitalizeFirstLetter(type)}`);
8938 return;
8939 }
8940 const input = instance.getInput();
8941 const inputValue = getInputValue(instance, innerParams);
8942 if (innerParams.inputValidator) {
8943 handleInputValidator(instance, inputValue, type);
8944 } else if (input && !input.checkValidity()) {
8945 instance.enableButtons();
8946 instance.showValidationMessage(innerParams.validationMessage || input.validationMessage);
8947 } else if (type === 'deny') {
8948 deny(instance, inputValue);
8949 } else {
8950 confirm(instance, inputValue);
8951 }
8952 };
8953
8954 /**
8955 * @param {SweetAlert} instance
8956 * @param {SweetAlertInputValue} inputValue
8957 * @param {'confirm' | 'deny'} type
8958 */
8959 const handleInputValidator = (instance, inputValue, type) => {
8960 const innerParams = privateProps.innerParams.get(instance);
8961 instance.disableInput();
8962 const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
8963 validationPromise.then(validationMessage => {
8964 instance.enableButtons();
8965 instance.enableInput();
8966 if (validationMessage) {
8967 instance.showValidationMessage(validationMessage);
8968 } else if (type === 'deny') {
8969 deny(instance, inputValue);
8970 } else {
8971 confirm(instance, inputValue);
8972 }
8973 });
8974 };
8975
8976 /**
8977 * @param {SweetAlert} instance
8978 * @param {*} value
8979 */
8980 const deny = (instance, value) => {
8981 const innerParams = privateProps.innerParams.get(instance);
8982 if (innerParams.showLoaderOnDeny) {
8983 showLoading(getDenyButton());
8984 }
8985 if (innerParams.preDeny) {
8986 instance.isAwaitingPromise = 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
8987 const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
8988 preDenyPromise.then(preDenyValue => {
8989 if (preDenyValue === false) {
8990 instance.hideLoading();
8991 handleAwaitingPromise(instance);
8992 } else {
8993 instance.close(/** @type SweetAlertResult */{
8994 isDenied: true,
8995 value: typeof preDenyValue === 'undefined' ? value : preDenyValue
8996 });
8997 }
8998 }).catch(error => rejectWith(instance, error));
8999 } else {
9000 instance.close(/** @type SweetAlertResult */{
9001 isDenied: true,
9002 value
9003 });
9004 }
9005 };
9006
9007 /**
9008 * @param {SweetAlert} instance
9009 * @param {*} value
9010 */
9011 const succeedWith = (instance, value) => {
9012 instance.close(/** @type SweetAlertResult */{
9013 isConfirmed: true,
9014 value
9015 });
9016 };
9017
9018 /**
9019 *
9020 * @param {SweetAlert} instance
9021 * @param {string} error
9022 */
9023 const rejectWith = (instance, error) => {
9024 instance.rejectPromise(error);
9025 };
9026
9027 /**
9028 *
9029 * @param {SweetAlert} instance
9030 * @param {*} value
9031 */
9032 const confirm = (instance, value) => {
9033 const innerParams = privateProps.innerParams.get(instance);
9034 if (innerParams.showLoaderOnConfirm) {
9035 showLoading();
9036 }
9037 if (innerParams.preConfirm) {
9038 instance.resetValidationMessage();
9039 instance.isAwaitingPromise = 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
9040 const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
9041 preConfirmPromise.then(preConfirmValue => {
9042 if (isVisible$1(getValidationMessage()) || preConfirmValue === false) {
9043 instance.hideLoading();
9044 handleAwaitingPromise(instance);
9045 } else {
9046 succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
9047 }
9048 }).catch(error => rejectWith(instance, error));
9049 } else {
9050 succeedWith(instance, value);
9051 }
9052 };
9053
9054 /**
9055 * Hides loader and shows back the button which was hidden by .showLoading()
9056 * @this {SweetAlert}
9057 */
9058 function hideLoading() {
9059 // do nothing if popup is closed
9060 const innerParams = privateProps.innerParams.get(this);
9061 if (!innerParams) {
9062 return;
9063 }
9064 const domCache = privateProps.domCache.get(this);
9065 hide(domCache.loader);
9066 if (isToast()) {
9067 if (innerParams.icon) {
9068 show(getIcon());
9069 }
9070 } else {
9071 showRelatedButton(domCache);
9072 }
9073 removeClass([domCache.popup, domCache.actions], swalClasses.loading);
9074 domCache.popup.removeAttribute('aria-busy');
9075 domCache.popup.removeAttribute('data-loading');
9076 domCache.confirmButton.disabled = false;
9077 domCache.denyButton.disabled = false;
9078 domCache.cancelButton.disabled = false;
9079 }
9080
9081 /**
9082 * @param {DomCache} domCache
9083 */
9084 const showRelatedButton = domCache => {
9085 const dataButtonToReplace = domCache.loader.getAttribute('data-button-to-replace');
9086 const buttonToReplace = dataButtonToReplace ? domCache.popup.getElementsByClassName(dataButtonToReplace) : [];
9087 if (buttonToReplace.length) {
9088 show(/** @type {HTMLElement} */buttonToReplace[0], 'inline-block');
9089 } else if (allButtonsAreHidden()) {
9090 hide(domCache.actions);
9091 }
9092 };
9093
9094 /**
9095 * Gets the input DOM node, this method works with input parameter.
9096 *
9097 * @returns {HTMLInputElement | null}
9098 * @this {SweetAlert}
9099 */
9100 function getInput() {
9101 const innerParams = privateProps.innerParams.get(this);
9102 const domCache = privateProps.domCache.get(this);
9103 if (!domCache) {
9104 return null;
9105 }
9106 return getInput$1(domCache.popup, innerParams.input);
9107 }
9108
9109 /**
9110 * @param {SweetAlert} instance
9111 * @param {string[]} buttons
9112 * @param {boolean} disabled
9113 */
9114 function setButtonsDisabled(instance, buttons, disabled) {
9115 const domCache = privateProps.domCache.get(instance);
9116 buttons.forEach(button => {
9117 domCache[button].disabled = disabled;
9118 });
9119 }
9120
9121 /**
9122 * @param {HTMLInputElement | null} input
9123 * @param {boolean} disabled
9124 */
9125 function setInputDisabled(input, disabled) {
9126 const popup = getPopup();
9127 if (!popup || !input) {
9128 return;
9129 }
9130 if (input.type === 'radio') {
9131 /** @type {NodeListOf<HTMLInputElement>} */
9132 const radios = popup.querySelectorAll(`[name="${swalClasses.radio}"]`);
9133 for (let i = 0; i < radios.length; i++) {
9134 radios[i].disabled = disabled;
9135 }
9136 } else {
9137 input.disabled = disabled;
9138 }
9139 }
9140
9141 /**
9142 * Enable all the buttons
9143 * @this {SweetAlert}
9144 */
9145 function enableButtons() {
9146 setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
9147 }
9148
9149 /**
9150 * Disable all the buttons
9151 * @this {SweetAlert}
9152 */
9153 function disableButtons() {
9154 setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
9155 }
9156
9157 /**
9158 * Enable the input field
9159 * @this {SweetAlert}
9160 */
9161 function enableInput() {
9162 setInputDisabled(this.getInput(), false);
9163 }
9164
9165 /**
9166 * Disable the input field
9167 * @this {SweetAlert}
9168 */
9169 function disableInput() {
9170 setInputDisabled(this.getInput(), true);
9171 }
9172
9173 /**
9174 * Show block with validation message
9175 *
9176 * @param {string} error
9177 * @this {SweetAlert}
9178 */
9179 function showValidationMessage(error) {
9180 const domCache = privateProps.domCache.get(this);
9181 const params = privateProps.innerParams.get(this);
9182 setInnerHtml(domCache.validationMessage, error);
9183 domCache.validationMessage.className = swalClasses['validation-message'];
9184 if (params.customClass && params.customClass.validationMessage) {
9185 addClass(domCache.validationMessage, params.customClass.validationMessage);
9186 }
9187 show(domCache.validationMessage);
9188 const input = this.getInput();
9189 if (input) {
9190 input.setAttribute('aria-invalid', 'true');
9191 input.setAttribute('aria-describedby', swalClasses['validation-message']);
9192 focusInput(input);
9193 addClass(input, swalClasses.inputerror);
9194 }
9195 }
9196
9197 /**
9198 * Hide block with validation message
9199 *
9200 * @this {SweetAlert}
9201 */
9202 function resetValidationMessage() {
9203 const domCache = privateProps.domCache.get(this);
9204 if (domCache.validationMessage) {
9205 hide(domCache.validationMessage);
9206 }
9207 const input = this.getInput();
9208 if (input) {
9209 input.removeAttribute('aria-invalid');
9210 input.removeAttribute('aria-describedby');
9211 removeClass(input, swalClasses.inputerror);
9212 }
9213 }
9214
9215 const defaultParams = {
9216 title: '',
9217 titleText: '',
9218 text: '',
9219 html: '',
9220 footer: '',
9221 icon: undefined,
9222 iconColor: undefined,
9223 iconHtml: undefined,
9224 template: undefined,
9225 toast: false,
9226 draggable: false,
9227 animation: true,
9228 theme: 'light',
9229 showClass: {
9230 popup: 'swal2-show',
9231 backdrop: 'swal2-backdrop-show',
9232 icon: 'swal2-icon-show'
9233 },
9234 hideClass: {
9235 popup: 'swal2-hide',
9236 backdrop: 'swal2-backdrop-hide',
9237 icon: 'swal2-icon-hide'
9238 },
9239 customClass: {},
9240 target: 'body',
9241 color: undefined,
9242 backdrop: true,
9243 heightAuto: true,
9244 allowOutsideClick: true,
9245 allowEscapeKey: true,
9246 allowEnterKey: true,
9247 stopKeydownPropagation: true,
9248 keydownListenerCapture: false,
9249 showConfirmButton: true,
9250 showDenyButton: false,
9251 showCancelButton: false,
9252 preConfirm: undefined,
9253 preDeny: undefined,
9254 confirmButtonText: 'OK',
9255 confirmButtonAriaLabel: '',
9256 confirmButtonColor: undefined,
9257 denyButtonText: 'No',
9258 denyButtonAriaLabel: '',
9259 denyButtonColor: undefined,
9260 cancelButtonText: 'Cancel',
9261 cancelButtonAriaLabel: '',
9262 cancelButtonColor: undefined,
9263 buttonsStyling: true,
9264 reverseButtons: false,
9265 focusConfirm: true,
9266 focusDeny: false,
9267 focusCancel: false,
9268 returnFocus: true,
9269 showCloseButton: false,
9270 closeButtonHtml: '&times;',
9271 closeButtonAriaLabel: 'Close this dialog',
9272 loaderHtml: '',
9273 showLoaderOnConfirm: false,
9274 showLoaderOnDeny: false,
9275 imageUrl: undefined,
9276 imageWidth: undefined,
9277 imageHeight: undefined,
9278 imageAlt: '',
9279 timer: undefined,
9280 timerProgressBar: false,
9281 width: undefined,
9282 padding: undefined,
9283 background: undefined,
9284 input: undefined,
9285 inputPlaceholder: '',
9286 inputLabel: '',
9287 inputValue: '',
9288 inputOptions: {},
9289 inputAutoFocus: true,
9290 inputAutoTrim: true,
9291 inputAttributes: {},
9292 inputValidator: undefined,
9293 returnInputValueOnDeny: false,
9294 validationMessage: undefined,
9295 grow: false,
9296 position: 'center',
9297 progressSteps: [],
9298 currentProgressStep: undefined,
9299 progressStepsDistance: undefined,
9300 willOpen: undefined,
9301 didOpen: undefined,
9302 didRender: undefined,
9303 willClose: undefined,
9304 didClose: undefined,
9305 didDestroy: undefined,
9306 scrollbarPadding: true,
9307 topLayer: false
9308 };
9309 const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'draggable', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'theme', 'willClose'];
9310
9311 /** @type {Record<string, string | undefined>} */
9312 const deprecatedParams = {
9313 allowEnterKey: undefined
9314 };
9315 const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'draggable', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
9316
9317 /**
9318 * Is valid parameter
9319 *
9320 * @param {string} paramName
9321 * @returns {boolean}
9322 */
9323 const isValidParameter = paramName => {
9324 return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
9325 };
9326
9327 /**
9328 * Is valid parameter for Swal.update() method
9329 *
9330 * @param {string} paramName
9331 * @returns {boolean}
9332 */
9333 const isUpdatableParameter = paramName => {
9334 return updatableParams.indexOf(paramName) !== -1;
9335 };
9336
9337 /**
9338 * Is deprecated parameter
9339 *
9340 * @param {string} paramName
9341 * @returns {string | undefined}
9342 */
9343 const isDeprecatedParameter = paramName => {
9344 return deprecatedParams[paramName];
9345 };
9346
9347 /**
9348 * @param {string} param
9349 */
9350 const checkIfParamIsValid = param => {
9351 if (!isValidParameter(param)) {
9352 warn(`Unknown parameter "${param}"`);
9353 }
9354 };
9355
9356 /**
9357 * @param {string} param
9358 */
9359 const checkIfToastParamIsValid = param => {
9360 if (toastIncompatibleParams.includes(param)) {
9361 warn(`The parameter "${param}" is incompatible with toasts`);
9362 }
9363 };
9364
9365 /**
9366 * @param {string} param
9367 */
9368 const checkIfParamIsDeprecated = param => {
9369 const isDeprecated = isDeprecatedParameter(param);
9370 if (isDeprecated) {
9371 warnAboutDeprecation(param, isDeprecated);
9372 }
9373 };
9374
9375 /**
9376 * Show relevant warnings for given params
9377 *
9378 * @param {SweetAlertOptions} params
9379 */
9380 const showWarningsForParams = params => {
9381 if (params.backdrop === false && params.allowOutsideClick) {
9382 warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
9383 }
9384 if (params.theme && !['light', 'dark', 'auto', 'minimal', 'borderless', 'bootstrap-4', 'bootstrap-4-light', 'bootstrap-4-dark', 'bootstrap-5', 'bootstrap-5-light', 'bootstrap-5-dark', 'material-ui', 'material-ui-light', 'material-ui-dark', 'embed-iframe', 'bulma', 'bulma-light', 'bulma-dark'].includes(params.theme)) {
9385 warn(`Invalid theme "${params.theme}"`);
9386 }
9387 for (const param in params) {
9388 checkIfParamIsValid(param);
9389 if (params.toast) {
9390 checkIfToastParamIsValid(param);
9391 }
9392 checkIfParamIsDeprecated(param);
9393 }
9394 };
9395
9396 /**
9397 * Updates popup parameters.
9398 *
9399 * @this {any}
9400 * @param {SweetAlertOptions} params
9401 */
9402 function update(params) {
9403 const container = getContainer();
9404 const popup = getPopup();
9405 const innerParams = privateProps.innerParams.get(this);
9406 if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
9407 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.`);
9408 return;
9409 }
9410 const validUpdatableParams = filterValidParams(params);
9411 const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
9412 showWarningsForParams(updatedParams);
9413 if (container) {
9414 container.dataset['swal2Theme'] = updatedParams.theme;
9415 }
9416 render(this, updatedParams);
9417 privateProps.innerParams.set(this, updatedParams);
9418 Object.defineProperties(this, {
9419 params: {
9420 value: Object.assign({}, this.params, params),
9421 writable: false,
9422 enumerable: true
9423 }
9424 });
9425 }
9426
9427 /**
9428 * @param {SweetAlertOptions} params
9429 * @returns {SweetAlertOptions}
9430 */
9431 const filterValidParams = params => {
9432 /** @type {Record<string, any>} */
9433 const validUpdatableParams = {};
9434 Object.keys(params).forEach(param => {
9435 if (isUpdatableParameter(param)) {
9436 const typedParams = /** @type {Record<string, any>} */params;
9437 validUpdatableParams[param] = typedParams[param];
9438 } else {
9439 warn(`Invalid parameter to update: ${param}`);
9440 }
9441 });
9442 return validUpdatableParams;
9443 };
9444
9445 /**
9446 * Dispose the current SweetAlert2 instance
9447 * @this {SweetAlert}
9448 */
9449 function _destroy() {
9450 var _globalState$eventEmi;
9451 const domCache = privateProps.domCache.get(this);
9452 const innerParams = privateProps.innerParams.get(this);
9453 if (!innerParams) {
9454 disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
9455 return; // This instance has already been destroyed
9456 }
9457
9458 // Check if there is another Swal closing
9459 if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
9460 globalState.swalCloseEventFinishedCallback();
9461 delete globalState.swalCloseEventFinishedCallback;
9462 }
9463 if (typeof innerParams.didDestroy === 'function') {
9464 innerParams.didDestroy();
9465 }
9466 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('didDestroy');
9467 disposeSwal(this);
9468 }
9469
9470 /**
9471 * @param {SweetAlert} instance
9472 */
9473 const disposeSwal = instance => {
9474 disposeWeakMaps(instance);
9475 // Unset this.params so GC will dispose it (#1569)
9476 // @ts-ignore
9477 delete instance.params;
9478 // Unset globalState props so GC will dispose globalState (#1569)
9479 delete globalState.keydownHandler;
9480 delete globalState.keydownTarget;
9481 // Unset currentInstance
9482 delete globalState.currentInstance;
9483 };
9484
9485 /**
9486 * @param {SweetAlert} instance
9487 */
9488 const disposeWeakMaps = instance => {
9489 // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
9490 if (instance.isAwaitingPromise) {
9491 unsetWeakMaps(privateProps, instance);
9492 instance.isAwaitingPromise = true;
9493 } else {
9494 unsetWeakMaps(privateMethods, instance);
9495 unsetWeakMaps(privateProps, instance);
9496
9497 // @ts-ignore
9498 delete instance.isAwaitingPromise;
9499 // Unset instance methods
9500 // @ts-ignore
9501 delete instance.disableButtons;
9502 // @ts-ignore
9503 delete instance.enableButtons;
9504 // @ts-ignore
9505 delete instance.getInput;
9506 // @ts-ignore
9507 delete instance.disableInput;
9508 // @ts-ignore
9509 delete instance.enableInput;
9510 // @ts-ignore
9511 delete instance.hideLoading;
9512 // @ts-ignore
9513 delete instance.disableLoading;
9514 // @ts-ignore
9515 delete instance.showValidationMessage;
9516 // @ts-ignore
9517 delete instance.resetValidationMessage;
9518 // @ts-ignore
9519 delete instance.close;
9520 // @ts-ignore
9521 delete instance.closePopup;
9522 // @ts-ignore
9523 delete instance.closeModal;
9524 // @ts-ignore
9525 delete instance.closeToast;
9526 // @ts-ignore
9527 delete instance.rejectPromise;
9528 // @ts-ignore
9529 delete instance.update;
9530 // @ts-ignore
9531 delete instance._destroy;
9532 }
9533 };
9534
9535 /**
9536 * @param {Record<string, WeakMap<any, any>>} obj
9537 * @param {SweetAlert} instance
9538 */
9539 const unsetWeakMaps = (obj, instance) => {
9540 for (const i in obj) {
9541 obj[i].delete(instance);
9542 }
9543 };
9544
9545 var instanceMethods = /*#__PURE__*/Object.freeze({
9546 __proto__: null,
9547 _destroy: _destroy,
9548 close: close,
9549 closeModal: close,
9550 closePopup: close,
9551 closeToast: close,
9552 disableButtons: disableButtons,
9553 disableInput: disableInput,
9554 disableLoading: hideLoading,
9555 enableButtons: enableButtons,
9556 enableInput: enableInput,
9557 getInput: getInput,
9558 handleAwaitingPromise: handleAwaitingPromise,
9559 hideLoading: hideLoading,
9560 rejectPromise: rejectPromise,
9561 resetValidationMessage: resetValidationMessage,
9562 showValidationMessage: showValidationMessage,
9563 update: update
9564 });
9565
9566 /**
9567 * @param {SweetAlertOptions} innerParams
9568 * @param {DomCache} domCache
9569 * @param {(dismiss: DismissReason) => void} dismissWith
9570 */
9571 const handlePopupClick = (innerParams, domCache, dismissWith) => {
9572 if (innerParams.toast) {
9573 handleToastClick(innerParams, domCache, dismissWith);
9574 } else {
9575 // Ignore click events that had mousedown on the popup but mouseup on the container
9576 // This can happen when the user drags a slider
9577 handleModalMousedown(domCache);
9578
9579 // Ignore click events that had mousedown on the container but mouseup on the popup
9580 handleContainerMousedown(domCache);
9581 handleModalClick(innerParams, domCache, dismissWith);
9582 }
9583 };
9584
9585 /**
9586 * @param {SweetAlertOptions} innerParams
9587 * @param {DomCache} domCache
9588 * @param {(dismiss: DismissReason) => void} dismissWith
9589 */
9590 const handleToastClick = (innerParams, domCache, dismissWith) => {
9591 // Closing toast by internal click
9592 domCache.popup.onclick = () => {
9593 if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
9594 return;
9595 }
9596 dismissWith(DismissReason.close);
9597 };
9598 };
9599
9600 /**
9601 * @param {SweetAlertOptions} innerParams
9602 * @returns {boolean}
9603 */
9604 const isAnyButtonShown = innerParams => {
9605 return Boolean(innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton);
9606 };
9607 let ignoreOutsideClick = false;
9608
9609 /**
9610 * @param {DomCache} domCache
9611 */
9612 const handleModalMousedown = domCache => {
9613 domCache.popup.onmousedown = () => {
9614 domCache.container.onmouseup = function (e) {
9615 domCache.container.onmouseup = () => {};
9616 // We only check if the mouseup target is the container because usually it doesn't
9617 // have any other direct children aside of the popup
9618 if (e.target === domCache.container) {
9619 ignoreOutsideClick = true;
9620 }
9621 };
9622 };
9623 };
9624
9625 /**
9626 * @param {DomCache} domCache
9627 */
9628 const handleContainerMousedown = domCache => {
9629 domCache.container.onmousedown = e => {
9630 // prevent the modal text from being selected on double click on the container (allowOutsideClick: false)
9631 if (e.target === domCache.container) {
9632 e.preventDefault();
9633 }
9634 domCache.popup.onmouseup = function (e) {
9635 domCache.popup.onmouseup = () => {};
9636 // We also need to check if the mouseup target is a child of the popup
9637 if (e.target === domCache.popup || e.target instanceof HTMLElement && domCache.popup.contains(e.target)) {
9638 ignoreOutsideClick = true;
9639 }
9640 };
9641 };
9642 };
9643
9644 /**
9645 * @param {SweetAlertOptions} innerParams
9646 * @param {DomCache} domCache
9647 * @param {(dismiss: DismissReason) => void} dismissWith
9648 */
9649 const handleModalClick = (innerParams, domCache, dismissWith) => {
9650 domCache.container.onclick = e => {
9651 if (ignoreOutsideClick) {
9652 ignoreOutsideClick = false;
9653 return;
9654 }
9655 if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
9656 dismissWith(DismissReason.backdrop);
9657 }
9658 };
9659 };
9660
9661 /**
9662 * @param {any} elem
9663 * @returns {boolean}
9664 */
9665 const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
9666
9667 /**
9668 * @param {any} elem
9669 * @returns {boolean}
9670 */
9671 const isElement = elem => elem instanceof Element || isJqueryElement(elem);
9672
9673 /**
9674 * @param {any[]} args
9675 * @returns {SweetAlertOptions}
9676 */
9677 const argsToParams = args => {
9678 /** @type {Record<string, any>} */
9679 const params = {};
9680 if (typeof args[0] === 'object' && !isElement(args[0])) {
9681 Object.assign(params, args[0]);
9682 } else {
9683 ['title', 'html', 'icon'].forEach((name, index) => {
9684 const arg = args[index];
9685 if (typeof arg === 'string' || isElement(arg)) {
9686 params[name] = arg;
9687 } else if (arg !== undefined) {
9688 error(`Unexpected type of ${name}! Expected "string" or "Element", got ${typeof arg}`);
9689 }
9690 });
9691 }
9692 return params;
9693 };
9694
9695 /**
9696 * Main method to create a new SweetAlert2 popup
9697 *
9698 * @this {new (...args: any[]) => any}
9699 * @param {...SweetAlertOptions} args
9700 * @returns {Promise<SweetAlertResult>}
9701 */
9702 function fire(...args) {
9703 return new this(...args);
9704 }
9705
9706 /**
9707 * Returns an extended version of `Swal` containing `params` as defaults.
9708 * Useful for reusing Swal configuration.
9709 *
9710 * For example:
9711 *
9712 * Before:
9713 * const textPromptOptions = { input: 'text', showCancelButton: true }
9714 * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
9715 * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
9716 *
9717 * After:
9718 * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
9719 * const {value: firstName} = await TextPrompt('What is your first name?')
9720 * const {value: lastName} = await TextPrompt('What is your last name?')
9721 *
9722 * @param {SweetAlertOptions} mixinParams
9723 * @returns {SweetAlert}
9724 * @this {typeof import('../SweetAlert.js').SweetAlert}
9725 */
9726 function mixin(mixinParams) {
9727 // @ts-ignore: 'this' refers to the SweetAlert constructor
9728 class MixinSwal extends this {
9729 /**
9730 * @param {any} params
9731 * @param {any} priorityMixinParams
9732 */
9733 _main(params, priorityMixinParams) {
9734 return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
9735 }
9736 }
9737 // @ts-ignore
9738 return MixinSwal;
9739 }
9740
9741 /**
9742 * If `timer` parameter is set, returns number of milliseconds of timer remained.
9743 * Otherwise, returns undefined.
9744 *
9745 * @returns {number | undefined}
9746 */
9747 const getTimerLeft = () => {
9748 return globalState.timeout && globalState.timeout.getTimerLeft();
9749 };
9750
9751 /**
9752 * Stop timer. Returns number of milliseconds of timer remained.
9753 * If `timer` parameter isn't set, returns undefined.
9754 *
9755 * @returns {number | undefined}
9756 */
9757 const stopTimer = () => {
9758 if (globalState.timeout) {
9759 stopTimerProgressBar();
9760 return globalState.timeout.stop();
9761 }
9762 };
9763
9764 /**
9765 * Resume timer. Returns number of milliseconds of timer remained.
9766 * If `timer` parameter isn't set, returns undefined.
9767 *
9768 * @returns {number | undefined}
9769 */
9770 const resumeTimer = () => {
9771 if (globalState.timeout) {
9772 const remaining = globalState.timeout.start();
9773 animateTimerProgressBar(remaining);
9774 return remaining;
9775 }
9776 };
9777
9778 /**
9779 * Resume timer. Returns number of milliseconds of timer remained.
9780 * If `timer` parameter isn't set, returns undefined.
9781 *
9782 * @returns {number | undefined}
9783 */
9784 const toggleTimer = () => {
9785 const timer = globalState.timeout;
9786 return timer && (timer.running ? stopTimer() : resumeTimer());
9787 };
9788
9789 /**
9790 * Increase timer. Returns number of milliseconds of an updated timer.
9791 * If `timer` parameter isn't set, returns undefined.
9792 *
9793 * @param {number} ms
9794 * @returns {number | undefined}
9795 */
9796 const increaseTimer = ms => {
9797 if (globalState.timeout) {
9798 const remaining = globalState.timeout.increase(ms);
9799 animateTimerProgressBar(remaining, true);
9800 return remaining;
9801 }
9802 };
9803
9804 /**
9805 * Check if timer is running. Returns true if timer is running
9806 * or false if timer is paused or stopped.
9807 * If `timer` parameter isn't set, returns undefined
9808 *
9809 * @returns {boolean}
9810 */
9811 const isTimerRunning = () => {
9812 return Boolean(globalState.timeout && globalState.timeout.isRunning());
9813 };
9814
9815 let bodyClickListenerAdded = false;
9816 /** @type {Record<string, any>} */
9817 const clickHandlers = {};
9818
9819 /**
9820 * @this {any}
9821 * @param {string} attr
9822 */
9823 function bindClickHandler(attr = 'data-swal-template') {
9824 clickHandlers[attr] = this;
9825 if (!bodyClickListenerAdded) {
9826 document.body.addEventListener('click', bodyClickListener);
9827 bodyClickListenerAdded = true;
9828 }
9829 }
9830
9831 /**
9832 * @param {MouseEvent} event
9833 */
9834 const bodyClickListener = event => {
9835 for (let el = /** @type {any} */event.target; el && el !== document; el = el.parentNode) {
9836 for (const attr in clickHandlers) {
9837 const template = el.getAttribute && el.getAttribute(attr);
9838 if (template) {
9839 clickHandlers[attr].fire({
9840 template
9841 });
9842 return;
9843 }
9844 }
9845 }
9846 };
9847
9848 // Source: https://gist.github.com/mudge/5830382?permalink_comment_id=2691957#gistcomment-2691957
9849
9850 class EventEmitter {
9851 constructor() {
9852 /** @type {Events} */
9853 this.events = {};
9854 }
9855
9856 /**
9857 * @param {string} eventName
9858 * @returns {EventHandlers}
9859 */
9860 _getHandlersByEventName(eventName) {
9861 if (typeof this.events[eventName] === 'undefined') {
9862 // not Set because we need to keep the FIFO order
9863 // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1748990334
9864 this.events[eventName] = [];
9865 }
9866 return this.events[eventName];
9867 }
9868
9869 /**
9870 * @param {string} eventName
9871 * @param {EventHandler} eventHandler
9872 */
9873 on(eventName, eventHandler) {
9874 const currentHandlers = this._getHandlersByEventName(eventName);
9875 if (!currentHandlers.includes(eventHandler)) {
9876 currentHandlers.push(eventHandler);
9877 }
9878 }
9879
9880 /**
9881 * @param {string} eventName
9882 * @param {EventHandler} eventHandler
9883 */
9884 once(eventName, eventHandler) {
9885 /**
9886 * @param {...any} args
9887 */
9888 const onceFn = (...args) => {
9889 this.removeListener(eventName, onceFn);
9890 // @ts-ignore
9891 eventHandler.apply(this, args);
9892 };
9893 this.on(eventName, onceFn);
9894 }
9895
9896 /**
9897 * @param {string} eventName
9898 * @param {...any} args
9899 */
9900 emit(eventName, ...args) {
9901 this._getHandlersByEventName(eventName).forEach(
9902 /**
9903 * @param {EventHandler} eventHandler
9904 */
9905 eventHandler => {
9906 try {
9907 // @ts-ignore
9908 eventHandler.apply(this, args);
9909 } catch (error) {
9910 console.error(error);
9911 }
9912 });
9913 }
9914
9915 /**
9916 * @param {string} eventName
9917 * @param {EventHandler} eventHandler
9918 */
9919 removeListener(eventName, eventHandler) {
9920 const currentHandlers = this._getHandlersByEventName(eventName);
9921 const index = currentHandlers.indexOf(eventHandler);
9922 if (index > -1) {
9923 currentHandlers.splice(index, 1);
9924 }
9925 }
9926
9927 /**
9928 * @param {string} eventName
9929 */
9930 removeAllListeners(eventName) {
9931 if (this.events[eventName] !== undefined) {
9932 // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1749239222
9933 this.events[eventName].length = 0;
9934 }
9935 }
9936 reset() {
9937 this.events = {};
9938 }
9939 }
9940
9941 globalState.eventEmitter = new EventEmitter();
9942
9943 /**
9944 * @param {string} eventName
9945 * @param {EventHandler} eventHandler
9946 */
9947 const on = (eventName, eventHandler) => {
9948 if (globalState.eventEmitter) {
9949 globalState.eventEmitter.on(eventName, eventHandler);
9950 }
9951 };
9952
9953 /**
9954 * @param {string} eventName
9955 * @param {EventHandler} eventHandler
9956 */
9957 const once = (eventName, eventHandler) => {
9958 if (globalState.eventEmitter) {
9959 globalState.eventEmitter.once(eventName, eventHandler);
9960 }
9961 };
9962
9963 /**
9964 * @param {string} [eventName]
9965 * @param {EventHandler} [eventHandler]
9966 */
9967 const off = (eventName, eventHandler) => {
9968 if (!globalState.eventEmitter) {
9969 return;
9970 }
9971
9972 // Remove all handlers for all events
9973 if (!eventName) {
9974 globalState.eventEmitter.reset();
9975 return;
9976 }
9977 if (eventHandler) {
9978 // Remove a specific handler
9979 globalState.eventEmitter.removeListener(eventName, eventHandler);
9980 } else {
9981 // Remove all handlers for a specific event
9982 globalState.eventEmitter.removeAllListeners(eventName);
9983 }
9984 };
9985
9986 var staticMethods = /*#__PURE__*/Object.freeze({
9987 __proto__: null,
9988 argsToParams: argsToParams,
9989 bindClickHandler: bindClickHandler,
9990 clickCancel: clickCancel,
9991 clickConfirm: clickConfirm,
9992 clickDeny: clickDeny,
9993 enableLoading: showLoading,
9994 fire: fire,
9995 getActions: getActions,
9996 getCancelButton: getCancelButton,
9997 getCloseButton: getCloseButton,
9998 getConfirmButton: getConfirmButton,
9999 getContainer: getContainer,
10000 getDenyButton: getDenyButton,
10001 getFocusableElements: getFocusableElements,
10002 getFooter: getFooter,
10003 getHtmlContainer: getHtmlContainer,
10004 getIcon: getIcon,
10005 getIconContent: getIconContent,
10006 getImage: getImage,
10007 getInputLabel: getInputLabel,
10008 getLoader: getLoader,
10009 getPopup: getPopup,
10010 getProgressSteps: getProgressSteps,
10011 getTimerLeft: getTimerLeft,
10012 getTimerProgressBar: getTimerProgressBar,
10013 getTitle: getTitle,
10014 getValidationMessage: getValidationMessage,
10015 increaseTimer: increaseTimer,
10016 isDeprecatedParameter: isDeprecatedParameter,
10017 isLoading: isLoading,
10018 isTimerRunning: isTimerRunning,
10019 isUpdatableParameter: isUpdatableParameter,
10020 isValidParameter: isValidParameter,
10021 isVisible: isVisible,
10022 mixin: mixin,
10023 off: off,
10024 on: on,
10025 once: once,
10026 resumeTimer: resumeTimer,
10027 showLoading: showLoading,
10028 stopTimer: stopTimer,
10029 toggleTimer: toggleTimer
10030 });
10031
10032 class Timer {
10033 /**
10034 * @param {() => void} callback
10035 * @param {number} delay
10036 */
10037 constructor(callback, delay) {
10038 this.callback = callback;
10039 this.remaining = delay;
10040 this.running = false;
10041 this.start();
10042 }
10043
10044 /**
10045 * @returns {number}
10046 */
10047 start() {
10048 if (!this.running) {
10049 this.running = true;
10050 this.started = new Date();
10051 this.id = setTimeout(this.callback, this.remaining);
10052 }
10053 return this.remaining;
10054 }
10055
10056 /**
10057 * @returns {number}
10058 */
10059 stop() {
10060 if (this.started && this.running) {
10061 this.running = false;
10062 clearTimeout(this.id);
10063 this.remaining -= new Date().getTime() - this.started.getTime();
10064 }
10065 return this.remaining;
10066 }
10067
10068 /**
10069 * @param {number} n
10070 * @returns {number}
10071 */
10072 increase(n) {
10073 const running = this.running;
10074 if (running) {
10075 this.stop();
10076 }
10077 this.remaining += n;
10078 if (running) {
10079 this.start();
10080 }
10081 return this.remaining;
10082 }
10083
10084 /**
10085 * @returns {number}
10086 */
10087 getTimerLeft() {
10088 if (this.running) {
10089 this.stop();
10090 this.start();
10091 }
10092 return this.remaining;
10093 }
10094
10095 /**
10096 * @returns {boolean}
10097 */
10098 isRunning() {
10099 return this.running;
10100 }
10101 }
10102
10103 const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
10104
10105 /**
10106 * @param {SweetAlertOptions} params
10107 * @returns {SweetAlertOptions}
10108 */
10109 const getTemplateParams = params => {
10110 const template = typeof params.template === 'string' ? (/** @type {HTMLTemplateElement} */document.querySelector(params.template)) : params.template;
10111 if (!template) {
10112 return {};
10113 }
10114 /** @type {DocumentFragment} */
10115 const templateContent = template.content;
10116 showWarningsForElements(templateContent);
10117 const result = Object.assign(getSwalParams(templateContent), getSwalFunctionParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
10118 return result;
10119 };
10120
10121 /**
10122 * @param {DocumentFragment} templateContent
10123 * @returns {Record<string, string | boolean | number>}
10124 */
10125 const getSwalParams = templateContent => {
10126 /** @type {Record<string, string | boolean | number>} */
10127 const result = {};
10128 /** @type {HTMLElement[]} */
10129 const swalParams = Array.from(templateContent.querySelectorAll('swal-param'));
10130 swalParams.forEach(param => {
10131 showWarningsForAttributes(param, ['name', 'value']);
10132 const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
10133 const value = param.getAttribute('value');
10134 if (!paramName || !value) {
10135 return;
10136 }
10137 if (paramName in defaultParams && typeof defaultParams[(/** @type {keyof typeof defaultParams} */paramName)] === 'boolean') {
10138 result[paramName] = value !== 'false';
10139 } else if (paramName in defaultParams && typeof defaultParams[(/** @type {keyof typeof defaultParams} */paramName)] === 'object') {
10140 result[paramName] = JSON.parse(value);
10141 } else {
10142 result[paramName] = value;
10143 }
10144 });
10145 return result;
10146 };
10147
10148 /**
10149 * @param {DocumentFragment} templateContent
10150 * @returns {Record<string, () => void>}
10151 */
10152 const getSwalFunctionParams = templateContent => {
10153 /** @type {Record<string, () => void>} */
10154 const result = {};
10155 /** @type {HTMLElement[]} */
10156 const swalFunctions = Array.from(templateContent.querySelectorAll('swal-function-param'));
10157 swalFunctions.forEach(param => {
10158 const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
10159 const value = param.getAttribute('value');
10160 if (!paramName || !value) {
10161 return;
10162 }
10163 result[paramName] = new Function(`return ${value}`)();
10164 });
10165 return result;
10166 };
10167
10168 /**
10169 * @param {DocumentFragment} templateContent
10170 * @returns {Record<string, string | boolean>}
10171 */
10172 const getSwalButtons = templateContent => {
10173 /** @type {Record<string, string | boolean>} */
10174 const result = {};
10175 /** @type {HTMLElement[]} */
10176 const swalButtons = Array.from(templateContent.querySelectorAll('swal-button'));
10177 swalButtons.forEach(button => {
10178 showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
10179 const type = button.getAttribute('type');
10180 if (!type || !['confirm', 'cancel', 'deny'].includes(type)) {
10181 return;
10182 }
10183 result[`${type}ButtonText`] = button.innerHTML;
10184 result[`show${capitalizeFirstLetter(type)}Button`] = true;
10185 if (button.hasAttribute('color')) {
10186 const color = button.getAttribute('color');
10187 if (color !== null) {
10188 result[`${type}ButtonColor`] = color;
10189 }
10190 }
10191 if (button.hasAttribute('aria-label')) {
10192 const ariaLabel = button.getAttribute('aria-label');
10193 if (ariaLabel !== null) {
10194 result[`${type}ButtonAriaLabel`] = ariaLabel;
10195 }
10196 }
10197 });
10198 return result;
10199 };
10200
10201 /**
10202 * @param {DocumentFragment} templateContent
10203 * @returns {Pick<SweetAlertOptions, 'imageUrl' | 'imageWidth' | 'imageHeight' | 'imageAlt'>}
10204 */
10205 const getSwalImage = templateContent => {
10206 const result = {};
10207 /** @type {HTMLElement | null} */
10208 const image = templateContent.querySelector('swal-image');
10209 if (image) {
10210 showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
10211 if (image.hasAttribute('src')) {
10212 result.imageUrl = image.getAttribute('src') || undefined;
10213 }
10214 if (image.hasAttribute('width')) {
10215 result.imageWidth = image.getAttribute('width') || undefined;
10216 }
10217 if (image.hasAttribute('height')) {
10218 result.imageHeight = image.getAttribute('height') || undefined;
10219 }
10220 if (image.hasAttribute('alt')) {
10221 result.imageAlt = image.getAttribute('alt') || undefined;
10222 }
10223 }
10224 return result;
10225 };
10226
10227 /**
10228 * @param {DocumentFragment} templateContent
10229 * @returns {object}
10230 */
10231 const getSwalIcon = templateContent => {
10232 const result = {};
10233 /** @type {HTMLElement | null} */
10234 const icon = templateContent.querySelector('swal-icon');
10235 if (icon) {
10236 showWarningsForAttributes(icon, ['type', 'color']);
10237 if (icon.hasAttribute('type')) {
10238 result.icon = icon.getAttribute('type');
10239 }
10240 if (icon.hasAttribute('color')) {
10241 result.iconColor = icon.getAttribute('color');
10242 }
10243 result.iconHtml = icon.innerHTML;
10244 }
10245 return result;
10246 };
10247
10248 /**
10249 * @param {DocumentFragment} templateContent
10250 * @returns {object}
10251 */
10252 const getSwalInput = templateContent => {
10253 /** @type {Record<string, any>} */
10254 const result = {};
10255 /** @type {HTMLElement | null} */
10256 const input = templateContent.querySelector('swal-input');
10257 if (input) {
10258 showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
10259 result.input = input.getAttribute('type') || 'text';
10260 if (input.hasAttribute('label')) {
10261 result.inputLabel = input.getAttribute('label');
10262 }
10263 if (input.hasAttribute('placeholder')) {
10264 result.inputPlaceholder = input.getAttribute('placeholder');
10265 }
10266 if (input.hasAttribute('value')) {
10267 result.inputValue = input.getAttribute('value');
10268 }
10269 }
10270 /** @type {HTMLElement[]} */
10271 const inputOptions = Array.from(templateContent.querySelectorAll('swal-input-option'));
10272 if (inputOptions.length) {
10273 result.inputOptions = {};
10274 inputOptions.forEach(option => {
10275 showWarningsForAttributes(option, ['value']);
10276 const optionValue = option.getAttribute('value');
10277 if (!optionValue) {
10278 return;
10279 }
10280 const optionName = option.innerHTML;
10281 result.inputOptions[optionValue] = optionName;
10282 });
10283 }
10284 return result;
10285 };
10286
10287 /**
10288 * @param {DocumentFragment} templateContent
10289 * @param {string[]} paramNames
10290 * @returns {Record<string, string>}
10291 */
10292 const getSwalStringParams = (templateContent, paramNames) => {
10293 /** @type {Record<string, string>} */
10294 const result = {};
10295 for (const i in paramNames) {
10296 const paramName = paramNames[i];
10297 /** @type {HTMLElement | null} */
10298 const tag = templateContent.querySelector(paramName);
10299 if (tag) {
10300 showWarningsForAttributes(tag, []);
10301 result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
10302 }
10303 }
10304 return result;
10305 };
10306
10307 /**
10308 * @param {DocumentFragment} templateContent
10309 */
10310 const showWarningsForElements = templateContent => {
10311 const allowedElements = swalStringParams.concat(['swal-param', 'swal-function-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
10312 Array.from(templateContent.children).forEach(el => {
10313 const tagName = el.tagName.toLowerCase();
10314 if (!allowedElements.includes(tagName)) {
10315 warn(`Unrecognized element <${tagName}>`);
10316 }
10317 });
10318 };
10319
10320 /**
10321 * @param {HTMLElement} el
10322 * @param {string[]} allowedAttributes
10323 */
10324 const showWarningsForAttributes = (el, allowedAttributes) => {
10325 Array.from(el.attributes).forEach(attribute => {
10326 if (allowedAttributes.indexOf(attribute.name) === -1) {
10327 warn([`Unrecognized attribute "${attribute.name}" on <${el.tagName.toLowerCase()}>.`, `${allowedAttributes.length ? `Allowed attributes are: ${allowedAttributes.join(', ')}` : 'To set the value, use HTML within the element.'}`]);
10328 }
10329 });
10330 };
10331
10332 const SHOW_CLASS_TIMEOUT = 10;
10333
10334 /**
10335 * Open popup, add necessary classes and styles, fix scrollbar
10336 *
10337 * @param {SweetAlertOptions} params
10338 */
10339 const openPopup = params => {
10340 var _globalState$eventEmi, _globalState$eventEmi2;
10341 const container = getContainer();
10342 const popup = getPopup();
10343 if (!container || !popup) {
10344 return;
10345 }
10346 if (typeof params.willOpen === 'function') {
10347 params.willOpen(popup);
10348 }
10349 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('willOpen', popup);
10350 const bodyStyles = window.getComputedStyle(document.body);
10351 const initialBodyOverflow = bodyStyles.overflowY;
10352 addClasses(container, popup, params);
10353
10354 // scrolling is 'hidden' until animation is done, after that 'auto'
10355 setTimeout(() => {
10356 setScrollingVisibility(container, popup);
10357 }, SHOW_CLASS_TIMEOUT);
10358 if (isModal()) {
10359 // Using ternary instead of ?? operator for Webpack 4 compatibility
10360 fixScrollContainer(container, params.scrollbarPadding !== undefined ? params.scrollbarPadding : false, initialBodyOverflow);
10361 setAriaHidden();
10362 }
10363 if (!isToast() && !globalState.previousActiveElement) {
10364 globalState.previousActiveElement = document.activeElement;
10365 }
10366 if (typeof params.didOpen === 'function') {
10367 const didOpen = params.didOpen;
10368 setTimeout(() => didOpen(popup));
10369 }
10370 (_globalState$eventEmi2 = globalState.eventEmitter) === null || _globalState$eventEmi2 === void 0 || _globalState$eventEmi2.emit('didOpen', popup);
10371 };
10372
10373 /**
10374 * @param {Event} event
10375 */
10376 const swalOpenAnimationFinished = event => {
10377 const popup = getPopup();
10378 if (!popup || event.target !== popup) {
10379 return;
10380 }
10381 const container = getContainer();
10382 if (!container) {
10383 return;
10384 }
10385 popup.removeEventListener('animationend', swalOpenAnimationFinished);
10386 popup.removeEventListener('transitionend', swalOpenAnimationFinished);
10387 container.style.overflowY = 'auto';
10388
10389 // no-transition is added in init() in case one swal is opened right after another
10390 removeClass(container, swalClasses['no-transition']);
10391 };
10392
10393 /**
10394 * @param {HTMLElement} container
10395 * @param {HTMLElement} popup
10396 */
10397 const setScrollingVisibility = (container, popup) => {
10398 if (hasCssAnimation(popup)) {
10399 container.style.overflowY = 'hidden';
10400 popup.addEventListener('animationend', swalOpenAnimationFinished);
10401 popup.addEventListener('transitionend', swalOpenAnimationFinished);
10402 } else {
10403 container.style.overflowY = 'auto';
10404 }
10405 };
10406
10407 /**
10408 * @param {HTMLElement} container
10409 * @param {boolean} scrollbarPadding
10410 * @param {string} initialBodyOverflow
10411 */
10412 const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
10413 iOSfix();
10414 if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
10415 replaceScrollbarWithPadding(initialBodyOverflow);
10416 }
10417
10418 // sweetalert2/issues/1247
10419 setTimeout(() => {
10420 container.scrollTop = 0;
10421 });
10422 };
10423
10424 /**
10425 * @param {HTMLElement} container
10426 * @param {HTMLElement} popup
10427 * @param {SweetAlertOptions} params
10428 */
10429 const addClasses = (container, popup, params) => {
10430 var _params$showClass;
10431 if ((_params$showClass = params.showClass) !== null && _params$showClass !== void 0 && _params$showClass.backdrop) {
10432 addClass(container, params.showClass.backdrop);
10433 }
10434 if (params.animation) {
10435 // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
10436 popup.style.setProperty('opacity', '0', 'important');
10437 show(popup, 'grid');
10438 setTimeout(() => {
10439 var _params$showClass2;
10440 // Animate popup right after showing it
10441 if ((_params$showClass2 = params.showClass) !== null && _params$showClass2 !== void 0 && _params$showClass2.popup) {
10442 addClass(popup, params.showClass.popup);
10443 }
10444 // and remove the opacity workaround
10445 popup.style.removeProperty('opacity');
10446 }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
10447 } else {
10448 show(popup, 'grid');
10449 }
10450 addClass([document.documentElement, document.body], swalClasses.shown);
10451 if (params.heightAuto && params.backdrop && !params.toast) {
10452 addClass([document.documentElement, document.body], swalClasses['height-auto']);
10453 }
10454 };
10455
10456 var defaultInputValidators = {
10457 /**
10458 * @param {string} string
10459 * @param {string} [validationMessage]
10460 * @returns {Promise<string | void>}
10461 */
10462 email: (string, validationMessage) => {
10463 return /^[a-zA-Z0-9.+_'-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]+$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
10464 },
10465 /**
10466 * @param {string} string
10467 * @param {string} [validationMessage]
10468 * @returns {Promise<string | void>}
10469 */
10470 url: (string, validationMessage) => {
10471 // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
10472 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');
10473 }
10474 };
10475
10476 /**
10477 * @param {SweetAlertOptions} params
10478 */
10479 function setDefaultInputValidators(params) {
10480 // Use default `inputValidator` for supported input types if not provided
10481 if (params.inputValidator) {
10482 return;
10483 }
10484 if (params.input === 'email') {
10485 params.inputValidator = defaultInputValidators['email'];
10486 }
10487 if (params.input === 'url') {
10488 params.inputValidator = defaultInputValidators['url'];
10489 }
10490 }
10491
10492 /**
10493 * @param {SweetAlertOptions} params
10494 */
10495 function validateCustomTargetElement(params) {
10496 // Determine if the custom target element is valid
10497 if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
10498 warn('Target parameter is not valid, defaulting to "body"');
10499 params.target = 'body';
10500 }
10501 }
10502
10503 /**
10504 * Set type, text and actions on popup
10505 *
10506 * @param {SweetAlertOptions} params
10507 */
10508 function setParameters(params) {
10509 setDefaultInputValidators(params);
10510
10511 // showLoaderOnConfirm && preConfirm
10512 if (params.showLoaderOnConfirm && !params.preConfirm) {
10513 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');
10514 }
10515 validateCustomTargetElement(params);
10516
10517 // Replace newlines with <br> in title
10518 if (typeof params.title === 'string') {
10519 params.title = params.title.split('\n').join('<br />');
10520 }
10521 init(params);
10522 }
10523
10524 /** @type {SweetAlert} */
10525 let currentInstance;
10526 var _promise = /*#__PURE__*/new WeakMap();
10527 class SweetAlert {
10528 /**
10529 * @param {...(SweetAlertOptions | string)} args
10530 * @this {SweetAlert}
10531 */
10532 constructor(...args) {
10533 /**
10534 * @type {Promise<SweetAlertResult>}
10535 */
10536 _classPrivateFieldInitSpec(this, _promise, /** @type {Promise<SweetAlertResult>} */Promise.resolve({
10537 isConfirmed: false,
10538 isDenied: false,
10539 isDismissed: true
10540 }));
10541 // Prevent run in Node env
10542 if (typeof window === 'undefined') {
10543 return;
10544 }
10545 currentInstance = this;
10546
10547 // @ts-ignore
10548 const outerParams = Object.freeze(this.constructor.argsToParams(args));
10549
10550 /** @type {Readonly<SweetAlertOptions>} */
10551 this.params = outerParams;
10552
10553 /** @type {boolean} */
10554 this.isAwaitingPromise = false;
10555 _classPrivateFieldSet2(_promise, this, this._main(currentInstance.params));
10556 }
10557
10558 /**
10559 * @param {any} userParams
10560 * @param {any} mixinParams
10561 */
10562 _main(userParams, mixinParams = {}) {
10563 showWarningsForParams(Object.assign({}, mixinParams, userParams));
10564 if (globalState.currentInstance) {
10565 const swalPromiseResolve = privateMethods.swalPromiseResolve.get(globalState.currentInstance);
10566 const {
10567 isAwaitingPromise
10568 } = globalState.currentInstance;
10569 globalState.currentInstance._destroy();
10570 if (!isAwaitingPromise) {
10571 swalPromiseResolve({
10572 isDismissed: true
10573 });
10574 }
10575 if (isModal()) {
10576 unsetAriaHidden();
10577 }
10578 }
10579 globalState.currentInstance = currentInstance;
10580 const innerParams = prepareParams(userParams, mixinParams);
10581 setParameters(innerParams);
10582 Object.freeze(innerParams);
10583
10584 // clear the previous timer
10585 if (globalState.timeout) {
10586 globalState.timeout.stop();
10587 delete globalState.timeout;
10588 }
10589
10590 // clear the restore focus timeout
10591 clearTimeout(globalState.restoreFocusTimeout);
10592 const domCache = populateDomCache(currentInstance);
10593 render(currentInstance, innerParams);
10594 privateProps.innerParams.set(currentInstance, innerParams);
10595 return swalPromise(currentInstance, domCache, innerParams);
10596 }
10597
10598 // `catch` cannot be the name of a module export, so we define our thenable methods here instead
10599 /**
10600 * @param {any} onFulfilled
10601 */
10602 then(onFulfilled) {
10603 return _classPrivateFieldGet2(_promise, this).then(onFulfilled);
10604 }
10605
10606 /**
10607 * @param {any} onFinally
10608 */
10609 finally(onFinally) {
10610 return _classPrivateFieldGet2(_promise, this).finally(onFinally);
10611 }
10612 }
10613
10614 /**
10615 * @param {SweetAlert} instance
10616 * @param {DomCache} domCache
10617 * @param {SweetAlertOptions} innerParams
10618 * @returns {Promise<SweetAlertResult>}
10619 */
10620 const swalPromise = (instance, domCache, innerParams) => {
10621 return new Promise((resolve, reject) => {
10622 // functions to handle all closings/dismissals
10623 /**
10624 * @param {DismissReason} dismiss
10625 */
10626 const dismissWith = dismiss => {
10627 instance.close({
10628 isDismissed: true,
10629 dismiss,
10630 isConfirmed: false,
10631 isDenied: false
10632 });
10633 };
10634 privateMethods.swalPromiseResolve.set(instance, resolve);
10635 privateMethods.swalPromiseReject.set(instance, reject);
10636 domCache.confirmButton.onclick = () => {
10637 handleConfirmButtonClick(instance);
10638 };
10639 domCache.denyButton.onclick = () => {
10640 handleDenyButtonClick(instance);
10641 };
10642 domCache.cancelButton.onclick = () => {
10643 handleCancelButtonClick(instance, dismissWith);
10644 };
10645 domCache.closeButton.onclick = () => {
10646 dismissWith(DismissReason.close);
10647 };
10648 handlePopupClick(innerParams, domCache, dismissWith);
10649 addKeydownHandler(globalState, innerParams, dismissWith);
10650 handleInputOptionsAndValue(instance, innerParams);
10651 openPopup(innerParams);
10652 setupTimer(globalState, innerParams, dismissWith);
10653 initFocus(domCache, innerParams);
10654
10655 // Scroll container to top on open (#1247, #1946)
10656 setTimeout(() => {
10657 domCache.container.scrollTop = 0;
10658 });
10659 });
10660 };
10661
10662 /**
10663 * @param {SweetAlertOptions} userParams
10664 * @param {SweetAlertOptions} mixinParams
10665 * @returns {SweetAlertOptions}
10666 */
10667 const prepareParams = (userParams, mixinParams) => {
10668 const templateParams = getTemplateParams(userParams);
10669 const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
10670 params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
10671 params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
10672 if (params.animation === false) {
10673 params.showClass = {
10674 backdrop: 'swal2-noanimation'
10675 };
10676 params.hideClass = {};
10677 }
10678 return params;
10679 };
10680
10681 /**
10682 * @param {SweetAlert} instance
10683 * @returns {DomCache}
10684 */
10685 const populateDomCache = instance => {
10686 const domCache = /** @type {DomCache} */{
10687 popup: (/** @type {HTMLElement} */getPopup()),
10688 container: (/** @type {HTMLElement} */getContainer()),
10689 actions: (/** @type {HTMLElement} */getActions()),
10690 confirmButton: (/** @type {HTMLElement} */getConfirmButton()),
10691 denyButton: (/** @type {HTMLElement} */getDenyButton()),
10692 cancelButton: (/** @type {HTMLElement} */getCancelButton()),
10693 loader: (/** @type {HTMLElement} */getLoader()),
10694 closeButton: (/** @type {HTMLElement} */getCloseButton()),
10695 validationMessage: (/** @type {HTMLElement} */getValidationMessage()),
10696 progressSteps: (/** @type {HTMLElement} */getProgressSteps())
10697 };
10698 privateProps.domCache.set(instance, domCache);
10699 return domCache;
10700 };
10701
10702 /**
10703 * @param {GlobalState} globalState
10704 * @param {SweetAlertOptions} innerParams
10705 * @param {(dismiss: DismissReason) => void} dismissWith
10706 */
10707 const setupTimer = (globalState, innerParams, dismissWith) => {
10708 const timerProgressBar = getTimerProgressBar();
10709 hide(timerProgressBar);
10710 if (innerParams.timer) {
10711 globalState.timeout = new Timer(() => {
10712 dismissWith('timer');
10713 delete globalState.timeout;
10714 }, innerParams.timer);
10715 if (innerParams.timerProgressBar && timerProgressBar) {
10716 show(timerProgressBar);
10717 applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
10718 setTimeout(() => {
10719 if (globalState.timeout && globalState.timeout.running) {
10720 // timer can be already stopped or unset at this point
10721 animateTimerProgressBar(/** @type {number} */innerParams.timer);
10722 }
10723 });
10724 }
10725 }
10726 };
10727
10728 /**
10729 * Initialize focus in the popup:
10730 *
10731 * 1. If `toast` is `true`, don't steal focus from the document.
10732 * 2. Else if there is an [autofocus] element, focus it.
10733 * 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.
10734 * 4. Else if `focusDeny` is `true` and deny button is visible, focus it.
10735 * 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.
10736 * 6. Else focus the first focusable element in a popup (if any).
10737 *
10738 * @param {DomCache} domCache
10739 * @param {SweetAlertOptions} innerParams
10740 */
10741 const initFocus = (domCache, innerParams) => {
10742 if (innerParams.toast) {
10743 return;
10744 }
10745 // TODO: this is dumb, remove `allowEnterKey` param in the next major version
10746 if (!callIfFunction(innerParams.allowEnterKey)) {
10747 warnAboutDeprecation('allowEnterKey');
10748 blurActiveElement();
10749 return;
10750 }
10751 if (focusAutofocus(domCache)) {
10752 return;
10753 }
10754 if (focusButton(domCache, innerParams)) {
10755 return;
10756 }
10757 setFocus(-1, 1);
10758 };
10759
10760 /**
10761 * @param {DomCache} domCache
10762 * @returns {boolean}
10763 */
10764 const focusAutofocus = domCache => {
10765 const autofocusElements = Array.from(domCache.popup.querySelectorAll('[autofocus]'));
10766 for (const autofocusElement of autofocusElements) {
10767 if (autofocusElement instanceof HTMLElement && isVisible$1(autofocusElement)) {
10768 autofocusElement.focus();
10769 return true;
10770 }
10771 }
10772 return false;
10773 };
10774
10775 /**
10776 * @param {DomCache} domCache
10777 * @param {SweetAlertOptions} innerParams
10778 * @returns {boolean}
10779 */
10780 const focusButton = (domCache, innerParams) => {
10781 if (innerParams.focusDeny && isVisible$1(domCache.denyButton)) {
10782 domCache.denyButton.focus();
10783 return true;
10784 }
10785 if (innerParams.focusCancel && isVisible$1(domCache.cancelButton)) {
10786 domCache.cancelButton.focus();
10787 return true;
10788 }
10789 if (innerParams.focusConfirm && isVisible$1(domCache.confirmButton)) {
10790 domCache.confirmButton.focus();
10791 return true;
10792 }
10793 return false;
10794 };
10795 const blurActiveElement = () => {
10796 if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
10797 document.activeElement.blur();
10798 }
10799 };
10800
10801 // Assign instance methods from src/instanceMethods/*.js to prototype
10802 SweetAlert.prototype.disableButtons = disableButtons;
10803 SweetAlert.prototype.enableButtons = enableButtons;
10804 SweetAlert.prototype.getInput = getInput;
10805 SweetAlert.prototype.disableInput = disableInput;
10806 SweetAlert.prototype.enableInput = enableInput;
10807 SweetAlert.prototype.hideLoading = hideLoading;
10808 SweetAlert.prototype.disableLoading = hideLoading;
10809 SweetAlert.prototype.showValidationMessage = showValidationMessage;
10810 SweetAlert.prototype.resetValidationMessage = resetValidationMessage;
10811 SweetAlert.prototype.close = close;
10812 SweetAlert.prototype.closePopup = close;
10813 SweetAlert.prototype.closeModal = close;
10814 SweetAlert.prototype.closeToast = close;
10815 SweetAlert.prototype.rejectPromise = rejectPromise;
10816 SweetAlert.prototype.update = update;
10817 SweetAlert.prototype._destroy = _destroy;
10818
10819 // Assign static methods from src/staticMethods/*.js to constructor
10820 Object.assign(SweetAlert, staticMethods);
10821
10822 // Proxy to instance methods to constructor, for now, for backwards compatibility
10823 Object.keys(instanceMethods).forEach(key => {
10824 /**
10825 * @param {...(SweetAlertOptions | string | undefined)} args
10826 * @returns {SweetAlertResult | Promise<SweetAlertResult> | undefined}
10827 */
10828 // @ts-ignore: Dynamic property assignment for backwards compatibility
10829 SweetAlert[key] = function (...args) {
10830 // @ts-ignore
10831 if (currentInstance && currentInstance[key]) {
10832 // @ts-ignore
10833 return currentInstance[key](...args);
10834 }
10835 return undefined;
10836 };
10837 });
10838 SweetAlert.DismissReason = DismissReason;
10839 SweetAlert.version = '11.26.17';
10840
10841 const Swal = SweetAlert;
10842 // @ts-ignore
10843 Swal.default = Swal;
10844
10845 return Swal;
10846
10847 }));
10848 if (typeof this !== 'undefined' && this.Sweetalert2){this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}
10849 "undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,":root{--swal2-outline: 0 0 0 3px rgba(100, 150, 200, 0.5);--swal2-container-padding: 0.625em;--swal2-backdrop: rgba(0, 0, 0, 0.4);--swal2-backdrop-transition: background-color 0.15s;--swal2-width: 32em;--swal2-padding: 0 0 1.25em;--swal2-border: none;--swal2-border-radius: 0.3125rem;--swal2-background: white;--swal2-color: #545454;--swal2-show-animation: swal2-show 0.3s;--swal2-hide-animation: swal2-hide 0.15s forwards;--swal2-icon-zoom: 1;--swal2-icon-animations: true;--swal2-title-padding: 0.8em 1em 0;--swal2-html-container-padding: 1em 1.6em 0.3em;--swal2-input-border: 1px solid #d9d9d9;--swal2-input-border-radius: 0.1875em;--swal2-input-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-background: transparent;--swal2-input-transition: border-color 0.2s, box-shadow 0.2s;--swal2-input-hover-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-focus-border: 1px solid #b4dbed;--swal2-input-focus-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px rgba(100, 150, 200, 0.5);--swal2-progress-step-background: #add8e6;--swal2-validation-message-background: #f0f0f0;--swal2-validation-message-color: #666;--swal2-footer-border-color: #eee;--swal2-footer-background: transparent;--swal2-footer-color: inherit;--swal2-timer-progress-bar-background: rgba(0, 0, 0, 0.3);--swal2-close-button-position: initial;--swal2-close-button-inset: auto;--swal2-close-button-font-size: 2.5em;--swal2-close-button-color: #ccc;--swal2-close-button-transition: color 0.2s, box-shadow 0.2s;--swal2-close-button-outline: initial;--swal2-close-button-box-shadow: inset 0 0 0 3px transparent;--swal2-close-button-focus-box-shadow: inset var(--swal2-outline);--swal2-close-button-hover-transform: none;--swal2-actions-justify-content: center;--swal2-actions-width: auto;--swal2-actions-margin: 1.25em auto 0;--swal2-actions-padding: 0;--swal2-actions-border-radius: 0;--swal2-actions-background: transparent;--swal2-action-button-transition: background-color 0.2s, box-shadow 0.2s;--swal2-action-button-hover: black 10%;--swal2-action-button-active: black 10%;--swal2-confirm-button-box-shadow: none;--swal2-confirm-button-border-radius: 0.25em;--swal2-confirm-button-background-color: #7066e0;--swal2-confirm-button-color: #fff;--swal2-deny-button-box-shadow: none;--swal2-deny-button-border-radius: 0.25em;--swal2-deny-button-background-color: #dc3741;--swal2-deny-button-color: #fff;--swal2-cancel-button-box-shadow: none;--swal2-cancel-button-border-radius: 0.25em;--swal2-cancel-button-background-color: #6e7881;--swal2-cancel-button-color: #fff;--swal2-toast-show-animation: swal2-toast-show 0.5s;--swal2-toast-hide-animation: swal2-toast-hide 0.1s forwards;--swal2-toast-border: none;--swal2-toast-box-shadow: 0 0 1px hsl(0deg 0% 0% / 0.075), 0 1px 2px hsl(0deg 0% 0% / 0.075), 1px 2px 4px hsl(0deg 0% 0% / 0.075), 1px 3px 8px hsl(0deg 0% 0% / 0.075), 2px 4px 16px hsl(0deg 0% 0% / 0.075)}[data-swal2-theme=dark]{--swal2-dark-theme-black: #19191a;--swal2-dark-theme-white: #e1e1e1;--swal2-background: var(--swal2-dark-theme-black);--swal2-color: var(--swal2-dark-theme-white);--swal2-footer-border-color: #555;--swal2-input-background: color-mix(in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10%);--swal2-validation-message-background: color-mix( in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10% );--swal2-validation-message-color: var(--swal2-dark-theme-white);--swal2-timer-progress-bar-background: rgba(255, 255, 255, 0.7)}@media(prefers-color-scheme: dark){[data-swal2-theme=auto]{--swal2-dark-theme-black: #19191a;--swal2-dark-theme-white: #e1e1e1;--swal2-background: var(--swal2-dark-theme-black);--swal2-color: var(--swal2-dark-theme-white);--swal2-footer-border-color: #555;--swal2-input-background: color-mix(in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10%);--swal2-validation-message-background: color-mix( in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10% );--swal2-validation-message-color: var(--swal2-dark-theme-white);--swal2-timer-progress-bar-background: rgba(255, 255, 255, 0.7)}}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto !important}body.swal2-no-backdrop .swal2-container{background-color:rgba(0,0,0,0) !important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px var(--swal2-backdrop)}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:rgba(0,0,0,0);pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{inset:0 auto auto 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{inset:0 0 auto auto}body.swal2-toast-shown .swal2-container.swal2-top-start,body.swal2-toast-shown .swal2-container.swal2-top-left{inset:0 auto auto 0}body.swal2-toast-shown .swal2-container.swal2-center-start,body.swal2-toast-shown .swal2-container.swal2-center-left{inset:50% auto auto 0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{inset:50% auto auto 50%;transform:translate(-50%, -50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{inset:50% 0 auto auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-start,body.swal2-toast-shown .swal2-container.swal2-bottom-left{inset:auto auto 0 0}body.swal2-toast-shown .swal2-container.swal2-bottom{inset:auto auto 0 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{inset:auto 0 0 auto}@media print{body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow-y:scroll !important}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown) .swal2-container{position:static !important}}div:where(.swal2-container){display:grid;position:fixed;z-index:1060;inset:0;box-sizing:border-box;grid-template-areas:\"top-start top top-end\" \"center-start center center-end\" \"bottom-start bottom-center bottom-end\";grid-template-rows:minmax(min-content, auto) minmax(min-content, auto) minmax(min-content, auto);height:100%;padding:var(--swal2-container-padding);overflow-x:hidden;transition:var(--swal2-backdrop-transition);-webkit-overflow-scrolling:touch}div:where(.swal2-container).swal2-backdrop-show,div:where(.swal2-container).swal2-noanimation{background:var(--swal2-backdrop)}div:where(.swal2-container).swal2-backdrop-hide{background:rgba(0,0,0,0) !important}div:where(.swal2-container).swal2-top-start,div:where(.swal2-container).swal2-center-start,div:where(.swal2-container).swal2-bottom-start{grid-template-columns:minmax(0, 1fr) auto auto}div:where(.swal2-container).swal2-top,div:where(.swal2-container).swal2-center,div:where(.swal2-container).swal2-bottom{grid-template-columns:auto minmax(0, 1fr) auto}div:where(.swal2-container).swal2-top-end,div:where(.swal2-container).swal2-center-end,div:where(.swal2-container).swal2-bottom-end{grid-template-columns:auto auto minmax(0, 1fr)}div:where(.swal2-container).swal2-top-start>.swal2-popup{align-self:start}div:where(.swal2-container).swal2-top>.swal2-popup{grid-column:2;place-self:start center}div:where(.swal2-container).swal2-top-end>.swal2-popup,div:where(.swal2-container).swal2-top-right>.swal2-popup{grid-column:3;place-self:start end}div:where(.swal2-container).swal2-center-start>.swal2-popup,div:where(.swal2-container).swal2-center-left>.swal2-popup{grid-row:2;align-self:center}div:where(.swal2-container).swal2-center>.swal2-popup{grid-column:2;grid-row:2;place-self:center center}div:where(.swal2-container).swal2-center-end>.swal2-popup,div:where(.swal2-container).swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;place-self:center end}div:where(.swal2-container).swal2-bottom-start>.swal2-popup,div:where(.swal2-container).swal2-bottom-left>.swal2-popup{grid-column:1;grid-row:3;align-self:end}div:where(.swal2-container).swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;place-self:end center}div:where(.swal2-container).swal2-bottom-end>.swal2-popup,div:where(.swal2-container).swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;place-self:end end}div:where(.swal2-container).swal2-grow-row>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-column:1/4;width:100%}div:where(.swal2-container).swal2-grow-column>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}div:where(.swal2-container).swal2-no-transition{transition:none !important}div:where(.swal2-container)[popover]{width:auto;border:0}div:where(.swal2-container) div:where(.swal2-popup){display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0, 100%);width:var(--swal2-width);max-width:100%;padding:var(--swal2-padding);border:var(--swal2-border);border-radius:var(--swal2-border-radius);background:var(--swal2-background);color:var(--swal2-color);font-family:inherit;font-size:1rem;container-name:swal2-popup}div:where(.swal2-container) div:where(.swal2-popup):focus{outline:none}div:where(.swal2-container) div:where(.swal2-popup).swal2-loading{overflow-y:hidden}div:where(.swal2-container) div:where(.swal2-popup).swal2-draggable{cursor:grab}div:where(.swal2-container) div:where(.swal2-popup).swal2-draggable div:where(.swal2-icon){cursor:grab}div:where(.swal2-container) div:where(.swal2-popup).swal2-dragging{cursor:grabbing}div:where(.swal2-container) div:where(.swal2-popup).swal2-dragging div:where(.swal2-icon){cursor:grabbing}div:where(.swal2-container) h2:where(.swal2-title){position:relative;max-width:100%;margin:0;padding:var(--swal2-title-padding);color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;overflow-wrap:break-word;cursor:initial}div:where(.swal2-container) div:where(.swal2-actions){display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:var(--swal2-actions-justify-content);width:var(--swal2-actions-width);margin:var(--swal2-actions-margin);padding:var(--swal2-actions-padding);border-radius:var(--swal2-actions-border-radius);background:var(--swal2-actions-background)}div:where(.swal2-container) div:where(.swal2-loader){display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 rgba(0,0,0,0) #2778c4 rgba(0,0,0,0)}div:where(.swal2-container) button:where(.swal2-styled){margin:.3125em;padding:.625em 1.1em;transition:var(--swal2-action-button-transition);border:none;box-shadow:0 0 0 3px rgba(0,0,0,0);font-weight:500}div:where(.swal2-container) button:where(.swal2-styled):not([disabled]){cursor:pointer}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm){border-radius:var(--swal2-confirm-button-border-radius);background:initial;background-color:var(--swal2-confirm-button-background-color);box-shadow:var(--swal2-confirm-button-box-shadow);color:var(--swal2-confirm-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm):hover{background-color:color-mix(in srgb, var(--swal2-confirm-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm):active{background-color:color-mix(in srgb, var(--swal2-confirm-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny){border-radius:var(--swal2-deny-button-border-radius);background:initial;background-color:var(--swal2-deny-button-background-color);box-shadow:var(--swal2-deny-button-box-shadow);color:var(--swal2-deny-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny):hover{background-color:color-mix(in srgb, var(--swal2-deny-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny):active{background-color:color-mix(in srgb, var(--swal2-deny-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel){border-radius:var(--swal2-cancel-button-border-radius);background:initial;background-color:var(--swal2-cancel-button-background-color);box-shadow:var(--swal2-cancel-button-box-shadow);color:var(--swal2-cancel-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel):hover{background-color:color-mix(in srgb, var(--swal2-cancel-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel):active{background-color:color-mix(in srgb, var(--swal2-cancel-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):focus-visible{outline:none;box-shadow:var(--swal2-action-button-focus-box-shadow)}div:where(.swal2-container) button:where(.swal2-styled)[disabled]:not(.swal2-loading){opacity:.4}div:where(.swal2-container) button:where(.swal2-styled)::-moz-focus-inner{border:0}div:where(.swal2-container) div:where(.swal2-footer){margin:1em 0 0;padding:1em 1em 0;border-top:1px solid var(--swal2-footer-border-color);background:var(--swal2-footer-background);color:var(--swal2-footer-color);font-size:1em;text-align:center;cursor:initial}div:where(.swal2-container) .swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto !important;overflow:hidden;border-bottom-right-radius:var(--swal2-border-radius);border-bottom-left-radius:var(--swal2-border-radius)}div:where(.swal2-container) div:where(.swal2-timer-progress-bar){width:100%;height:.25em;background:var(--swal2-timer-progress-bar-background)}div:where(.swal2-container) img:where(.swal2-image){max-width:100%;margin:2em auto 1em;cursor:initial}div:where(.swal2-container) button:where(.swal2-close){position:var(--swal2-close-button-position);inset:var(--swal2-close-button-inset);z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:var(--swal2-close-button-transition);border:none;border-radius:var(--swal2-border-radius);outline:var(--swal2-close-button-outline);background:rgba(0,0,0,0);color:var(--swal2-close-button-color);font-family:monospace;font-size:var(--swal2-close-button-font-size);cursor:pointer;justify-self:end}div:where(.swal2-container) button:where(.swal2-close):hover{transform:var(--swal2-close-button-hover-transform);background:rgba(0,0,0,0);color:#f27474}div:where(.swal2-container) button:where(.swal2-close):focus-visible{outline:none;box-shadow:var(--swal2-close-button-focus-box-shadow)}div:where(.swal2-container) button:where(.swal2-close)::-moz-focus-inner{border:0}div:where(.swal2-container) div:where(.swal2-html-container){z-index:1;justify-content:center;margin:0;padding:var(--swal2-html-container-padding);overflow:auto;color:inherit;font-size:1.125em;font-weight:normal;line-height:normal;text-align:center;overflow-wrap:break-word;word-break:break-word;cursor:initial}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea),div:where(.swal2-container) select:where(.swal2-select),div:where(.swal2-container) div:where(.swal2-radio),div:where(.swal2-container) label:where(.swal2-checkbox){margin:1em 2em 3px}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea){box-sizing:border-box;width:auto;transition:var(--swal2-input-transition);border:var(--swal2-input-border);border-radius:var(--swal2-input-border-radius);background:var(--swal2-input-background);box-shadow:var(--swal2-input-box-shadow);color:inherit;font-size:1.125em}div:where(.swal2-container) input:where(.swal2-input).swal2-inputerror,div:where(.swal2-container) input:where(.swal2-file).swal2-inputerror,div:where(.swal2-container) textarea:where(.swal2-textarea).swal2-inputerror{border-color:#f27474 !important;box-shadow:0 0 2px #f27474 !important}div:where(.swal2-container) input:where(.swal2-input):hover,div:where(.swal2-container) input:where(.swal2-file):hover,div:where(.swal2-container) textarea:where(.swal2-textarea):hover{box-shadow:var(--swal2-input-hover-box-shadow)}div:where(.swal2-container) input:where(.swal2-input):focus,div:where(.swal2-container) input:where(.swal2-file):focus,div:where(.swal2-container) textarea:where(.swal2-textarea):focus{border:var(--swal2-input-focus-border);outline:none;box-shadow:var(--swal2-input-focus-box-shadow)}div:where(.swal2-container) input:where(.swal2-input)::placeholder,div:where(.swal2-container) input:where(.swal2-file)::placeholder,div:where(.swal2-container) textarea:where(.swal2-textarea)::placeholder{color:#ccc}div:where(.swal2-container) .swal2-range{margin:1em 2em 3px;background:var(--swal2-background)}div:where(.swal2-container) .swal2-range input{width:80%}div:where(.swal2-container) .swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}div:where(.swal2-container) .swal2-range input,div:where(.swal2-container) .swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}div:where(.swal2-container) .swal2-input{height:2.625em;padding:0 .75em}div:where(.swal2-container) .swal2-file{width:75%;margin-right:auto;margin-left:auto;background:var(--swal2-input-background);font-size:1.125em}div:where(.swal2-container) .swal2-textarea{height:6.75em;padding:.75em}div:where(.swal2-container) .swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:var(--swal2-input-background);color:inherit;font-size:1.125em}div:where(.swal2-container) .swal2-radio,div:where(.swal2-container) .swal2-checkbox{align-items:center;justify-content:center;background:var(--swal2-background);color:inherit}div:where(.swal2-container) .swal2-radio label,div:where(.swal2-container) .swal2-checkbox label{margin:0 .6em;font-size:1.125em}div:where(.swal2-container) .swal2-radio input,div:where(.swal2-container) .swal2-checkbox input{flex-shrink:0;margin:0 .4em}div:where(.swal2-container) label:where(.swal2-input-label){display:flex;justify-content:center;margin:1em auto 0}div:where(.swal2-container) div:where(.swal2-validation-message){align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:var(--swal2-validation-message-background);color:var(--swal2-validation-message-color);font-size:1em;font-weight:300}div:where(.swal2-container) div:where(.swal2-validation-message)::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}div:where(.swal2-container) .swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:rgba(0,0,0,0);font-weight:600}div:where(.swal2-container) .swal2-progress-steps li{display:inline-block;position:relative}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:var(--swal2-progress-step-background);color:#fff}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:var(--swal2-progress-step-background)}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}div:where(.swal2-icon){position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;zoom:var(--swal2-icon-zoom);border:.25em solid rgba(0,0,0,0);border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;user-select:none}div:where(.swal2-icon) .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}div:where(.swal2-icon).swal2-error{border-color:#f27474;color:#f27474}div:where(.swal2-icon).swal2-error .swal2-x-mark{position:relative;flex-grow:1}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-error.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-error.swal2-icon-show .swal2-x-mark{animation:swal2-animate-error-x-mark .5s}}div:where(.swal2-icon).swal2-warning{border-color:#f8bb86;color:#f8bb86}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-warning.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-warning.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .5s}}div:where(.swal2-icon).swal2-info{border-color:#3fc3ee;color:#3fc3ee}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-info.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-info.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .8s}}div:where(.swal2-icon).swal2-question{border-color:#87adbd;color:#87adbd}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-question.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-question.swal2-icon-show .swal2-icon-content{animation:swal2-animate-question-mark .8s}}div:where(.swal2-icon).swal2-success{border-color:#a5dc86;color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;border-radius:50%}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}div:where(.swal2-icon).swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-0.25em;left:-0.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}div:where(.swal2-icon).swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-animate-success-line-tip .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-animate-success-line-long .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-circular-line-right{animation:swal2-rotate-success-circular-line 4.25s ease-in}}[class^=swal2]{-webkit-tap-highlight-color:rgba(0,0,0,0)}.swal2-show{animation:var(--swal2-show-animation)}.swal2-hide{animation:var(--swal2-hide-animation)}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}.swal2-toast{box-sizing:border-box;grid-column:1/4 !important;grid-row:1/4 !important;grid-template-columns:min-content auto min-content;padding:1em;overflow-y:hidden;border:var(--swal2-toast-border);background:var(--swal2-background);box-shadow:var(--swal2-toast-box-shadow);pointer-events:all}.swal2-toast>*{grid-column:2}.swal2-toast h2:where(.swal2-title){margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-toast .swal2-loading{justify-content:center}.swal2-toast input:where(.swal2-input){height:2em;margin:.5em;font-size:1em}.swal2-toast .swal2-validation-message{font-size:1em}.swal2-toast div:where(.swal2-footer){margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-toast button:where(.swal2-close){grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-toast div:where(.swal2-html-container){margin:.5em 1em;padding:0;overflow:initial;font-size:1em;text-align:initial}.swal2-toast div:where(.swal2-html-container):empty{padding:0}.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:bold}.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-toast div:where(.swal2-actions){justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-toast button:where(.swal2-styled){margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;border-radius:50%}.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.8em;left:-0.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}@container swal2-popup style(--swal2-icon-animations:true){.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-toast-animate-success-line-tip .75s}.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-toast-animate-success-line-long .75s}}.swal2-toast.swal2-show{animation:var(--swal2-toast-show-animation)}.swal2-toast.swal2-hide{animation:var(--swal2-toast-hide-animation)}@keyframes swal2-show{0%{transform:translate3d(0, -50px, 0) scale(0.9);opacity:0}100%{transform:translate3d(0, 0, 0) scale(1);opacity:1}}@keyframes swal2-hide{0%{transform:translate3d(0, 0, 0) scale(1);opacity:1}100%{transform:translate3d(0, -50px, 0) scale(0.9);opacity:0}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-0.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(0.4);opacity:0}50%{margin-top:1.625em;transform:scale(0.4);opacity:0}80%{margin-top:-0.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0deg);opacity:1}}@keyframes swal2-rotate-loading{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-toast-show{0%{transform:translateY(-0.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(0.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0deg)}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-0.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}");
10850
10851 /***/ },
10852
10853 /***/ "./node_modules/toastify-js/src/toastify.js"
10854 /*!**************************************************!*\
10855 !*** ./node_modules/toastify-js/src/toastify.js ***!
10856 \**************************************************/
10857 (module) {
10858
10859 /*!
10860 * Toastify js 1.12.0
10861 * https://github.com/apvarun/toastify-js
10862 * @license MIT licensed
10863 *
10864 * Copyright (C) 2018 Varun A P
10865 */
10866 (function(root, factory) {
10867 if ( true && module.exports) {
10868 module.exports = factory();
10869 } else {
10870 root.Toastify = factory();
10871 }
10872 })(this, function(global) {
10873 // Object initialization
10874 var Toastify = function(options) {
10875 // Returning a new init object
10876 return new Toastify.lib.init(options);
10877 },
10878 // Library version
10879 version = "1.12.0";
10880
10881 // Set the default global options
10882 Toastify.defaults = {
10883 oldestFirst: true,
10884 text: "Toastify is awesome!",
10885 node: undefined,
10886 duration: 3000,
10887 selector: undefined,
10888 callback: function () {
10889 },
10890 destination: undefined,
10891 newWindow: false,
10892 close: false,
10893 gravity: "toastify-top",
10894 positionLeft: false,
10895 position: '',
10896 backgroundColor: '',
10897 avatar: "",
10898 className: "",
10899 stopOnFocus: true,
10900 onClick: function () {
10901 },
10902 offset: {x: 0, y: 0},
10903 escapeMarkup: true,
10904 ariaLive: 'polite',
10905 style: {background: ''}
10906 };
10907
10908 // Defining the prototype of the object
10909 Toastify.lib = Toastify.prototype = {
10910 toastify: version,
10911
10912 constructor: Toastify,
10913
10914 // Initializing the object with required parameters
10915 init: function(options) {
10916 // Verifying and validating the input object
10917 if (!options) {
10918 options = {};
10919 }
10920
10921 // Creating the options object
10922 this.options = {};
10923
10924 this.toastElement = null;
10925
10926 // Validating the options
10927 this.options.text = options.text || Toastify.defaults.text; // Display message
10928 this.options.node = options.node || Toastify.defaults.node; // Display content as node
10929 this.options.duration = options.duration === 0 ? 0 : options.duration || Toastify.defaults.duration; // Display duration
10930 this.options.selector = options.selector || Toastify.defaults.selector; // Parent selector
10931 this.options.callback = options.callback || Toastify.defaults.callback; // Callback after display
10932 this.options.destination = options.destination || Toastify.defaults.destination; // On-click destination
10933 this.options.newWindow = options.newWindow || Toastify.defaults.newWindow; // Open destination in new window
10934 this.options.close = options.close || Toastify.defaults.close; // Show toast close icon
10935 this.options.gravity = options.gravity === "bottom" ? "toastify-bottom" : Toastify.defaults.gravity; // toast position - top or bottom
10936 this.options.positionLeft = options.positionLeft || Toastify.defaults.positionLeft; // toast position - left or right
10937 this.options.position = options.position || Toastify.defaults.position; // toast position - left or right
10938 this.options.backgroundColor = options.backgroundColor || Toastify.defaults.backgroundColor; // toast background color
10939 this.options.avatar = options.avatar || Toastify.defaults.avatar; // img element src - url or a path
10940 this.options.className = options.className || Toastify.defaults.className; // additional class names for the toast
10941 this.options.stopOnFocus = options.stopOnFocus === undefined ? Toastify.defaults.stopOnFocus : options.stopOnFocus; // stop timeout on focus
10942 this.options.onClick = options.onClick || Toastify.defaults.onClick; // Callback after click
10943 this.options.offset = options.offset || Toastify.defaults.offset; // toast offset
10944 this.options.escapeMarkup = options.escapeMarkup !== undefined ? options.escapeMarkup : Toastify.defaults.escapeMarkup;
10945 this.options.ariaLive = options.ariaLive || Toastify.defaults.ariaLive;
10946 this.options.style = options.style || Toastify.defaults.style;
10947 if(options.backgroundColor) {
10948 this.options.style.background = options.backgroundColor;
10949 }
10950
10951 // Returning the current object for chaining functions
10952 return this;
10953 },
10954
10955 // Building the DOM element
10956 buildToast: function() {
10957 // Validating if the options are defined
10958 if (!this.options) {
10959 throw "Toastify is not initialized";
10960 }
10961
10962 // Creating the DOM object
10963 var divElement = document.createElement("div");
10964 divElement.className = "toastify on " + this.options.className;
10965
10966 // Positioning toast to left or right or center
10967 if (!!this.options.position) {
10968 divElement.className += " toastify-" + this.options.position;
10969 } else {
10970 // To be depreciated in further versions
10971 if (this.options.positionLeft === true) {
10972 divElement.className += " toastify-left";
10973 console.warn('Property `positionLeft` will be depreciated in further versions. Please use `position` instead.')
10974 } else {
10975 // Default position
10976 divElement.className += " toastify-right";
10977 }
10978 }
10979
10980 // Assigning gravity of element
10981 divElement.className += " " + this.options.gravity;
10982
10983 if (this.options.backgroundColor) {
10984 // This is being deprecated in favor of using the style HTML DOM property
10985 console.warn('DEPRECATION NOTICE: "backgroundColor" is being deprecated. Please use the "style.background" property.');
10986 }
10987
10988 // Loop through our style object and apply styles to divElement
10989 for (var property in this.options.style) {
10990 divElement.style[property] = this.options.style[property];
10991 }
10992
10993 // Announce the toast to screen readers
10994 if (this.options.ariaLive) {
10995 divElement.setAttribute('aria-live', this.options.ariaLive)
10996 }
10997
10998 // Adding the toast message/node
10999 if (this.options.node && this.options.node.nodeType === Node.ELEMENT_NODE) {
11000 // If we have a valid node, we insert it
11001 divElement.appendChild(this.options.node)
11002 } else {
11003 if (this.options.escapeMarkup) {
11004 divElement.innerText = this.options.text;
11005 } else {
11006 divElement.innerHTML = this.options.text;
11007 }
11008
11009 if (this.options.avatar !== "") {
11010 var avatarElement = document.createElement("img");
11011 avatarElement.src = this.options.avatar;
11012
11013 avatarElement.className = "toastify-avatar";
11014
11015 if (this.options.position == "left" || this.options.positionLeft === true) {
11016 // Adding close icon on the left of content
11017 divElement.appendChild(avatarElement);
11018 } else {
11019 // Adding close icon on the right of content
11020 divElement.insertAdjacentElement("afterbegin", avatarElement);
11021 }
11022 }
11023 }
11024
11025 // Adding a close icon to the toast
11026 if (this.options.close === true) {
11027 // Create a span for close element
11028 var closeElement = document.createElement("button");
11029 closeElement.type = "button";
11030 closeElement.setAttribute("aria-label", "Close");
11031 closeElement.className = "toast-close";
11032 closeElement.innerHTML = "&#10006;";
11033
11034 // Triggering the removal of toast from DOM on close click
11035 closeElement.addEventListener(
11036 "click",
11037 function(event) {
11038 event.stopPropagation();
11039 this.removeElement(this.toastElement);
11040 window.clearTimeout(this.toastElement.timeOutValue);
11041 }.bind(this)
11042 );
11043
11044 //Calculating screen width
11045 var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
11046
11047 // Adding the close icon to the toast element
11048 // Display on the right if screen width is less than or equal to 360px
11049 if ((this.options.position == "left" || this.options.positionLeft === true) && width > 360) {
11050 // Adding close icon on the left of content
11051 divElement.insertAdjacentElement("afterbegin", closeElement);
11052 } else {
11053 // Adding close icon on the right of content
11054 divElement.appendChild(closeElement);
11055 }
11056 }
11057
11058 // Clear timeout while toast is focused
11059 if (this.options.stopOnFocus && this.options.duration > 0) {
11060 var self = this;
11061 // stop countdown
11062 divElement.addEventListener(
11063 "mouseover",
11064 function(event) {
11065 window.clearTimeout(divElement.timeOutValue);
11066 }
11067 )
11068 // add back the timeout
11069 divElement.addEventListener(
11070 "mouseleave",
11071 function() {
11072 divElement.timeOutValue = window.setTimeout(
11073 function() {
11074 // Remove the toast from DOM
11075 self.removeElement(divElement);
11076 },
11077 self.options.duration
11078 )
11079 }
11080 )
11081 }
11082
11083 // Adding an on-click destination path
11084 if (typeof this.options.destination !== "undefined") {
11085 divElement.addEventListener(
11086 "click",
11087 function(event) {
11088 event.stopPropagation();
11089 if (this.options.newWindow === true) {
11090 window.open(this.options.destination, "_blank");
11091 } else {
11092 window.location = this.options.destination;
11093 }
11094 }.bind(this)
11095 );
11096 }
11097
11098 if (typeof this.options.onClick === "function" && typeof this.options.destination === "undefined") {
11099 divElement.addEventListener(
11100 "click",
11101 function(event) {
11102 event.stopPropagation();
11103 this.options.onClick();
11104 }.bind(this)
11105 );
11106 }
11107
11108 // Adding offset
11109 if(typeof this.options.offset === "object") {
11110
11111 var x = getAxisOffsetAValue("x", this.options);
11112 var y = getAxisOffsetAValue("y", this.options);
11113
11114 var xOffset = this.options.position == "left" ? x : "-" + x;
11115 var yOffset = this.options.gravity == "toastify-top" ? y : "-" + y;
11116
11117 divElement.style.transform = "translate(" + xOffset + "," + yOffset + ")";
11118
11119 }
11120
11121 // Returning the generated element
11122 return divElement;
11123 },
11124
11125 // Displaying the toast
11126 showToast: function() {
11127 // Creating the DOM object for the toast
11128 this.toastElement = this.buildToast();
11129
11130 // Getting the root element to with the toast needs to be added
11131 var rootElement;
11132 if (typeof this.options.selector === "string") {
11133 rootElement = document.getElementById(this.options.selector);
11134 } else if (this.options.selector instanceof HTMLElement || (typeof ShadowRoot !== 'undefined' && this.options.selector instanceof ShadowRoot)) {
11135 rootElement = this.options.selector;
11136 } else {
11137 rootElement = document.body;
11138 }
11139
11140 // Validating if root element is present in DOM
11141 if (!rootElement) {
11142 throw "Root element is not defined";
11143 }
11144
11145 // Adding the DOM element
11146 var elementToInsert = Toastify.defaults.oldestFirst ? rootElement.firstChild : rootElement.lastChild;
11147 rootElement.insertBefore(this.toastElement, elementToInsert);
11148
11149 // Repositioning the toasts in case multiple toasts are present
11150 Toastify.reposition();
11151
11152 if (this.options.duration > 0) {
11153 this.toastElement.timeOutValue = window.setTimeout(
11154 function() {
11155 // Remove the toast from DOM
11156 this.removeElement(this.toastElement);
11157 }.bind(this),
11158 this.options.duration
11159 ); // Binding `this` for function invocation
11160 }
11161
11162 // Supporting function chaining
11163 return this;
11164 },
11165
11166 hideToast: function() {
11167 if (this.toastElement.timeOutValue) {
11168 clearTimeout(this.toastElement.timeOutValue);
11169 }
11170 this.removeElement(this.toastElement);
11171 },
11172
11173 // Removing the element from the DOM
11174 removeElement: function(toastElement) {
11175 // Hiding the element
11176 // toastElement.classList.remove("on");
11177 toastElement.className = toastElement.className.replace(" on", "");
11178
11179 // Removing the element from DOM after transition end
11180 window.setTimeout(
11181 function() {
11182 // remove options node if any
11183 if (this.options.node && this.options.node.parentNode) {
11184 this.options.node.parentNode.removeChild(this.options.node);
11185 }
11186
11187 // Remove the element from the DOM, only when the parent node was not removed before.
11188 if (toastElement.parentNode) {
11189 toastElement.parentNode.removeChild(toastElement);
11190 }
11191
11192 // Calling the callback function
11193 this.options.callback.call(toastElement);
11194
11195 // Repositioning the toasts again
11196 Toastify.reposition();
11197 }.bind(this),
11198 400
11199 ); // Binding `this` for function invocation
11200 },
11201 };
11202
11203 // Positioning the toasts on the DOM
11204 Toastify.reposition = function() {
11205
11206 // Top margins with gravity
11207 var topLeftOffsetSize = {
11208 top: 15,
11209 bottom: 15,
11210 };
11211 var topRightOffsetSize = {
11212 top: 15,
11213 bottom: 15,
11214 };
11215 var offsetSize = {
11216 top: 15,
11217 bottom: 15,
11218 };
11219
11220 // Get all toast messages on the DOM
11221 var allToasts = document.getElementsByClassName("toastify");
11222
11223 var classUsed;
11224
11225 // Modifying the position of each toast element
11226 for (var i = 0; i < allToasts.length; i++) {
11227 // Getting the applied gravity
11228 if (containsClass(allToasts[i], "toastify-top") === true) {
11229 classUsed = "toastify-top";
11230 } else {
11231 classUsed = "toastify-bottom";
11232 }
11233
11234 var height = allToasts[i].offsetHeight;
11235 classUsed = classUsed.substr(9, classUsed.length-1)
11236 // Spacing between toasts
11237 var offset = 15;
11238
11239 var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
11240
11241 // Show toast in center if screen with less than or equal to 360px
11242 if (width <= 360) {
11243 // Setting the position
11244 allToasts[i].style[classUsed] = offsetSize[classUsed] + "px";
11245
11246 offsetSize[classUsed] += height + offset;
11247 } else {
11248 if (containsClass(allToasts[i], "toastify-left") === true) {
11249 // Setting the position
11250 allToasts[i].style[classUsed] = topLeftOffsetSize[classUsed] + "px";
11251
11252 topLeftOffsetSize[classUsed] += height + offset;
11253 } else {
11254 // Setting the position
11255 allToasts[i].style[classUsed] = topRightOffsetSize[classUsed] + "px";
11256
11257 topRightOffsetSize[classUsed] += height + offset;
11258 }
11259 }
11260 }
11261
11262 // Supporting function chaining
11263 return this;
11264 };
11265
11266 // Helper function to get offset.
11267 function getAxisOffsetAValue(axis, options) {
11268
11269 if(options.offset[axis]) {
11270 if(isNaN(options.offset[axis])) {
11271 return options.offset[axis];
11272 }
11273 else {
11274 return options.offset[axis] + 'px';
11275 }
11276 }
11277
11278 return '0px';
11279
11280 }
11281
11282 function containsClass(elem, yourClass) {
11283 if (!elem || typeof yourClass !== "string") {
11284 return false;
11285 } else if (
11286 elem.className &&
11287 elem.className
11288 .trim()
11289 .split(/\s+/gi)
11290 .indexOf(yourClass) > -1
11291 ) {
11292 return true;
11293 } else {
11294 return false;
11295 }
11296 }
11297
11298 // Setting up the prototype for the init object
11299 Toastify.lib.init.prototype = Toastify.lib;
11300
11301 // Returning the Toastify function to be assigned to the window object/module
11302 return Toastify;
11303 });
11304
11305
11306 /***/ },
11307
11308 /***/ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC"
11309 /*!**************************************************************************************************************************************************************************************************************************************************************!*\
11310 !*** data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC ***!
11311 \**************************************************************************************************************************************************************************************************************************************************************/
11312 (module) {
11313
11314 "use strict";
11315 module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC";
11316
11317 /***/ }
11318
11319 /******/ });
11320 /************************************************************************/
11321 /******/ // The module cache
11322 /******/ var __webpack_module_cache__ = {};
11323 /******/
11324 /******/ // The require function
11325 /******/ function __webpack_require__(moduleId) {
11326 /******/ // Check if module is in cache
11327 /******/ var cachedModule = __webpack_module_cache__[moduleId];
11328 /******/ if (cachedModule !== undefined) {
11329 /******/ return cachedModule.exports;
11330 /******/ }
11331 /******/ // Create a new module (and put it into the cache)
11332 /******/ var module = __webpack_module_cache__[moduleId] = {
11333 /******/ id: moduleId,
11334 /******/ // no module.loaded needed
11335 /******/ exports: {}
11336 /******/ };
11337 /******/
11338 /******/ // Execute the module function
11339 /******/ if (!(moduleId in __webpack_modules__)) {
11340 /******/ delete __webpack_module_cache__[moduleId];
11341 /******/ var e = new Error("Cannot find module '" + moduleId + "'");
11342 /******/ e.code = 'MODULE_NOT_FOUND';
11343 /******/ throw e;
11344 /******/ }
11345 /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
11346 /******/
11347 /******/ // Return the exports of the module
11348 /******/ return module.exports;
11349 /******/ }
11350 /******/
11351 /******/ // expose the modules object (__webpack_modules__)
11352 /******/ __webpack_require__.m = __webpack_modules__;
11353 /******/
11354 /************************************************************************/
11355 /******/ /* webpack/runtime/compat get default export */
11356 /******/ (() => {
11357 /******/ // getDefaultExport function for compatibility with non-harmony modules
11358 /******/ __webpack_require__.n = (module) => {
11359 /******/ var getter = module && module.__esModule ?
11360 /******/ () => (module['default']) :
11361 /******/ () => (module);
11362 /******/ __webpack_require__.d(getter, { a: getter });
11363 /******/ return getter;
11364 /******/ };
11365 /******/ })();
11366 /******/
11367 /******/ /* webpack/runtime/define property getters */
11368 /******/ (() => {
11369 /******/ // define getter functions for harmony exports
11370 /******/ __webpack_require__.d = (exports, definition) => {
11371 /******/ for(var key in definition) {
11372 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
11373 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
11374 /******/ }
11375 /******/ }
11376 /******/ };
11377 /******/ })();
11378 /******/
11379 /******/ /* webpack/runtime/hasOwnProperty shorthand */
11380 /******/ (() => {
11381 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
11382 /******/ })();
11383 /******/
11384 /******/ /* webpack/runtime/make namespace object */
11385 /******/ (() => {
11386 /******/ // define __esModule on exports
11387 /******/ __webpack_require__.r = (exports) => {
11388 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
11389 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
11390 /******/ }
11391 /******/ Object.defineProperty(exports, '__esModule', { value: true });
11392 /******/ };
11393 /******/ })();
11394 /******/
11395 /******/ /* webpack/runtime/jsonp chunk loading */
11396 /******/ (() => {
11397 /******/ __webpack_require__.b = (typeof document !== 'undefined' && document.baseURI) || self.location.href;
11398 /******/
11399 /******/ // object to store loaded and loading chunks
11400 /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
11401 /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
11402 /******/ var installedChunks = {
11403 /******/ "./assets/js/dist/frontend/profile": 0
11404 /******/ };
11405 /******/
11406 /******/ // no chunk on demand loading
11407 /******/
11408 /******/ // no prefetching
11409 /******/
11410 /******/ // no preloaded
11411 /******/
11412 /******/ // no HMR
11413 /******/
11414 /******/ // no HMR manifest
11415 /******/
11416 /******/ // no on chunks loaded
11417 /******/
11418 /******/ // no jsonp function
11419 /******/ })();
11420 /******/
11421 /******/ /* webpack/runtime/nonce */
11422 /******/ (() => {
11423 /******/ __webpack_require__.nc = undefined;
11424 /******/ })();
11425 /******/
11426 /************************************************************************/
11427 var __webpack_exports__ = {};
11428 // This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
11429 (() => {
11430 "use strict";
11431 /*!*******************************************!*\
11432 !*** ./assets/src/js/frontend/profile.js ***!
11433 \*******************************************/
11434 __webpack_require__.r(__webpack_exports__);
11435 /* harmony import */ var _profile_course_tab__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./profile/course-tab */ "./assets/src/js/frontend/profile/course-tab.js");
11436 /* harmony import */ var _profile_statistic__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./profile/statistic */ "./assets/src/js/frontend/profile/statistic.js");
11437 /* harmony import */ var _profile_order_recover__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./profile/order-recover */ "./assets/src/js/frontend/profile/order-recover.js");
11438 /* harmony import */ var _profile_cover_image__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./profile/cover-image */ "./assets/src/js/frontend/profile/cover-image.js");
11439 /* harmony import */ var _profile_avatar__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./profile/avatar */ "./assets/src/js/frontend/profile/avatar.js");
11440 /* harmony import */ var _profile_quiz__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./profile/quiz */ "./assets/src/js/frontend/profile/quiz.js");
11441 /* harmony import */ var _profile_order_refund__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./profile/order-refund */ "./assets/src/js/frontend/profile/order-refund.js");
11442 /* harmony import */ var _admin_courses_view_students_modal__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../admin/courses/view-students-modal */ "./assets/src/js/admin/courses/view-students-modal.js");
11443
11444
11445
11446
11447
11448
11449
11450
11451 (0,_profile_cover_image__WEBPACK_IMPORTED_MODULE_3__["default"])();
11452 (0,_profile_quiz__WEBPACK_IMPORTED_MODULE_5__["default"])();
11453 (0,_profile_statistic__WEBPACK_IMPORTED_MODULE_1__["default"])();
11454 (0,_profile_order_recover__WEBPACK_IMPORTED_MODULE_2__["default"])();
11455 (0,_profile_order_refund__WEBPACK_IMPORTED_MODULE_6__["default"])();
11456 new _admin_courses_view_students_modal__WEBPACK_IMPORTED_MODULE_7__.ViewStudentsModal();
11457 document.addEventListener('DOMContentLoaded', function (event) {
11458 (0,_profile_course_tab__WEBPACK_IMPORTED_MODULE_0__["default"])();
11459 });
11460 if (document.getElementById('learnpress-avatar-upload')) {
11461 (0,_profile_avatar__WEBPACK_IMPORTED_MODULE_4__["default"])();
11462 }
11463 })();
11464
11465 /******/ })()
11466 ;
11467 //# sourceMappingURL=profile.js.map