PluginProbe
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses / 4.4.5
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses v4.4.5
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 / dist / js / admin / edit-quiz.js

edit-quiz.js in LearnPress – WordPress LMS Plugin for Create and Sell Online Courses 4.4.5, at assets/dist/js/admin/edit-quiz.js

12,075 lines 433.7 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/edit-question.js"
5 /*!**********************************************!*\
6 !*** ./assets/src/js/admin/edit-question.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 */ EditQuestion: () => (/* binding */ EditQuestion)
14 /* harmony export */ });
15 /* harmony import */ var lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lpAssetsJsPath/utils.js */ "./assets/src/js/utils.js");
16 /* harmony import */ var lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lpAssetsJsPath/lpToastify */ "./assets/src/js/lpToastify.js");
17 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! sweetalert2 */ "./node_modules/sweetalert2/dist/sweetalert2.all.js");
18 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(sweetalert2__WEBPACK_IMPORTED_MODULE_2__);
19 /* harmony import */ var sortablejs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! sortablejs */ "./node_modules/sortablejs/modular/sortable.esm.js");
20 /**
21 * Edit question JS handler.
22 *
23 * @since 4.2.9
24 * @version 1.0.0
25 */
26
27
28
29
30
31 const idUrlHandle = 'edit-question';
32 let fibSelection;
33 let timeoutAutoUpdateAnswer, timeoutAutoUpdateFib, timeoutAutoUpdateQuestion;
34
35 // EditQuestion class
36 class EditQuestion {
37 static selectors = {
38 elEditQuestionWrap: '.lp-edit-question-wrap',
39 elQuestionEditMain: '.lp-question-edit-main',
40 elQuestionToggleAll: '.lp-question-toggle-all',
41 elEditListQuestions: '.lp-edit-list-questions',
42 elQuestionToggle: '.lp-question-toggle',
43 elBtnShowPopupItemsToSelect: '.lp-btn-show-popup-items-to-select',
44 elPopupItemsToSelectClone: '.lp-popup-items-to-select.clone',
45 elBtnAddQuestion: '.lp-btn-add-question',
46 elBtnRemoveQuestion: '.lp-btn-remove-question',
47 elBtnUpdateQuestionTitle: '.lp-btn-update-question-title',
48 elBtnUpdateQuestionDes: '.lp-btn-update-question-des',
49 elBtnUpdateQuestionHint: '.lp-btn-update-question-hint',
50 elBtnUpdateQuestionExplain: '.lp-btn-update-question-explanation',
51 elQuestionTitleNewInput: '.lp-question-title-new-input',
52 elQuestionTitleInput: '.lp-question-title-input',
53 elQuestionTypeLabel: '.lp-question-type-label',
54 elQuestionTypeNew: '.lp-question-type-new',
55 elAddNewQuestion: 'add-new-question',
56 elQuestionClone: '.lp-question-item.clone',
57 elAnswersConfig: '.lp-answers-config',
58 elBtnAddAnswer: '.lp-btn-add-question-answer',
59 elQuestionAnswerItemAddNew: '.lp-question-answer-item-add-new',
60 elQuestionAnswerTitleNewInput: '.lp-question-answer-title-new-input',
61 elQuestionAnswerTitleInput: '.lp-question-answer-title-input',
62 elBtnDeleteAnswer: '.lp-btn-delete-question-answer',
63 elQuestionByType: '.lp-question-by-type',
64 elInputAnswerSetTrue: '.lp-input-answer-set-true',
65 elQuestionAnswerItem: '.lp-question-answer-item',
66 elBtnUpdateQuestionAnswer: '.lp-btn-update-question-answer',
67 elBtnFibInsertBlank: '.lp-btn-fib-insert-blank',
68 elBtnFibDeleteAllBlanks: '.lp-btn-fib-delete-all-blanks',
69 elBtnFibSaveContent: '.lp-btn-fib-save-content',
70 elBtnFibClearAllContent: '.lp-btn-fib-clear-all-content',
71 elFibOptionTitleInput: '.lp-question-fib-option-title-input',
72 elFibBlankOptions: '.lp-question-fib-blank-options',
73 elFibBlankOptionItem: '.lp-question-fib-blank-option-item',
74 elFibBlankOptionItemClone: '.lp-question-fib-blank-option-item.clone',
75 elFibBlankOptionIndex: '.lp-question-fib-option-index',
76 elBtnFibOptionDelete: '.lp-btn-fib-option-delete',
77 elFibOptionMatchCaseWrap: '.lp-question-fib-option-match-case-wrap',
78 elFibOptionMatchCaseInput: '.lp-question-fib-option-match-case-input',
79 elQuestionFibOptionDetail: '.lp-question-fib-option-detail',
80 elFibOptionComparisonInput: '.lp-question-fib-option-comparison-input',
81 elAutoSaveFib: '.lp-auto-save-fib',
82 LPTarget: '.lp-target',
83 elCollapse: 'lp-collapse',
84 elSectionToggle: '.lp-section-toggle',
85 elTriggerToggle: '.lp-trigger-toggle',
86 elAutoSaveQuestion: '.lp-auto-save-question',
87 elAutoSaveAnswer: '.lp-auto-save-question-answer',
88 elQuestionFibInput: 'lp-question-fib-input',
89 elBtnQuestionCreateType: '.lp-btn-question-create-type'
90 };
91 constructor() {}
92 init() {
93 this.events();
94 this.initTinyMCE().then();
95 }
96 events() {
97 if (EditQuestion._loadedEvents) {
98 return;
99 }
100 EditQuestion._loadedEvents = true;
101
102 // Sortable answers's question
103 const elQuestionEditMains = document.querySelectorAll(`${EditQuestion.selectors.elQuestionEditMain}`);
104 elQuestionEditMains.forEach(elQuestionEditMain => {
105 this.sortAbleQuestionAnswer(elQuestionEditMain);
106 });
107 // End sortable
108
109 // Event click
110 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('click', [{
111 selector: EditQuestion.selectors.elBtnQuestionCreateType,
112 callBack: this.createQuestionType.name,
113 class: this
114 }, {
115 selector: EditQuestion.selectors.elBtnAddAnswer,
116 callBack: this.addQuestionAnswer.name,
117 class: this
118 }, {
119 selector: EditQuestion.selectors.elBtnDeleteAnswer,
120 callBack: this.deleteQuestionAnswer.name,
121 class: this
122 }, {
123 selector: EditQuestion.selectors.elBtnFibInsertBlank,
124 callBack: this.fibInsertBlank.name,
125 class: this
126 }, {
127 selector: EditQuestion.selectors.elBtnFibDeleteAllBlanks,
128 callBack: this.fibDeleteAllBlanks.name,
129 class: this
130 }, {
131 selector: EditQuestion.selectors.elBtnFibSaveContent,
132 callBack: this.fibSaveContent.name,
133 class: this
134 }, {
135 selector: EditQuestion.selectors.elBtnFibClearAllContent,
136 callBack: this.fibClearContent.name,
137 class: this
138 }, {
139 selector: EditQuestion.selectors.elBtnFibOptionDelete,
140 callBack: this.fibDeleteBlank.name,
141 class: this
142 }, {
143 selector: EditQuestion.selectors.elFibOptionMatchCaseInput,
144 callBack: this.fibShowHideMatchCaseOption.name,
145 class: this
146 }, {
147 selector: EditQuestion.selectors.elFibOptionComparisonInput,
148 callBack: args => {
149 const {
150 e,
151 target
152 } = args;
153 const elQuestionEditMain = target.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
154 const elBtnFibSaveContent = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elBtnFibSaveContent}`);
155 elBtnFibSaveContent.click();
156 }
157 }]);
158
159 // Toggle collapse
160 document.addEventListener('click', e => {
161 const target = e.target;
162 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.toggleCollapse(e, target, EditQuestion.selectors.elTriggerToggle);
163 });
164
165 // Event keyup
166 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('keyup', [{
167 selector: EditQuestion.selectors.elQuestionAnswerTitleNewInput,
168 callBack: this.checkCanAddAnswer.name,
169 class: this
170 }, {
171 selector: EditQuestion.selectors.elFibOptionTitleInput,
172 callBack: this.fibOptionTitleInputChange.name,
173 class: this
174 }, {
175 selector: EditQuestion.selectors.elAutoSaveQuestion,
176 callBack: this.autoUpdateQuestion.name,
177 class: this
178 }]);
179
180 // Event keydown
181 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('keydown', [{
182 selector: EditQuestion.selectors.elQuestionAnswerTitleNewInput,
183 callBack: this.addQuestionAnswer.name,
184 class: this,
185 checkIsEventEnter: true
186 }]);
187
188 // Event change
189 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('change', [{
190 selector: EditQuestion.selectors.elAutoSaveAnswer,
191 callBack: this.autoUpdateAnswer.name,
192 class: this
193 }]);
194
195 // TinyMCE events
196 this.eventEditorTinymce();
197 }
198
199 // Run async to re-init all TinyMCE editors, because it slow if have many editors
200 async initTinyMCE() {
201 const elTextareas = document.querySelectorAll('.lp-editor-tinymce');
202 elTextareas.forEach(elTextarea => {
203 const idTextarea = elTextarea.id;
204 this.reInitTinymce(idTextarea);
205 });
206 }
207 reInitTinymce(id) {
208 window.tinymce.execCommand('mceRemoveEditor', true, id);
209 window.tinymce.execCommand('mceAddEditor', true, id);
210 }
211 reInitQuickTags(id) {
212 const toolbar = document.getElementById(`qt_${id}_toolbar`);
213 if (!toolbar || toolbar.children.length || !window.quicktags) {
214 return;
215 }
216 const settings = window.tinyMCEPreInit?.qtInit?.[id] || {
217 id
218 };
219 window.quicktags(settings);
220 if (window.QTags?._buttonsInit) {
221 window.QTags._buttonsInit();
222 }
223 }
224 setDefaultEditorTab(id) {
225 const wrapEditor = document.getElementById(`wp-${id}-wrap`);
226 if (!wrapEditor) {
227 return;
228 }
229 if (wrapEditor.classList.contains('html-active') && window.switchEditors?.go) {
230 window.switchEditors.go(id, 'tmce');
231 const elTextarea = document.getElementById(id);
232 if (elTextarea) {
233 elTextarea.style.visibility = '';
234 }
235 }
236 wrapEditor.classList.add('tmce-active');
237 wrapEditor.classList.remove('html-active');
238 const visualTab = document.getElementById(`${id}-tmce`);
239 const codeTab = document.getElementById(`${id}-html`);
240 visualTab?.setAttribute('aria-pressed', 'true');
241 codeTab?.setAttribute('aria-pressed', 'false');
242 }
243
244 // Events for TinyMCE editor
245 eventEditorTinymce() {
246 window.tinymce.on('AddEditor', eEditor => {
247 const id = eEditor.editor.id;
248 const editor = window.tinymce.get(id);
249 if (!editor) {
250 return;
251 }
252 if (id === 'content') {
253 return;
254 }
255 const elTextarea = document.getElementById(id);
256 if (!elTextarea) {
257 return;
258 }
259 const elQuestionEditMain = elTextarea.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
260
261 // Skip if not in question edit context
262 if (!elQuestionEditMain) {
263 return;
264 }
265 const questionId = elQuestionEditMain.dataset.questionId;
266 editor.settings.force_p_newlines = false;
267 editor.settings.forced_root_block = '';
268 editor.settings.force_br_newlines = true;
269
270 // Config use absolute url
271 editor.settings.relative_urls = false;
272 editor.settings.remove_script_host = false;
273 editor.settings.convert_urls = true;
274 editor.settings.document_base_url = lpData.site_url;
275 // End config use absolute url
276
277 // Add quick tags
278 this.reInitQuickTags(id);
279
280 // Events focus in TinyMCE editor
281 editor.on('change keyup', e => {
282 // Auto save if it has class lp-auto-save
283 elTextarea.value = editor.getContent();
284 this.autoUpdateQuestion({
285 e,
286 target: elTextarea
287 });
288 });
289 editor.on('blur', e => {
290 //console.log( 'Editor blurred:', e.target.id );
291 });
292 editor.on('focusin', e => {});
293 editor.on('init', () => {
294 // Add style
295 editor.dom.addStyle(`
296 body {
297 line-height: 2.2 !important;
298 }
299 .${EditQuestion.selectors.elQuestionFibInput} {
300 border: 1px dashed rebeccapurple;
301 padding: 5px;
302 }
303 `);
304
305 // Set default tab visual
306 this.setDefaultEditorTab(id);
307 });
308 editor.on('setcontent', e => {
309 const uniquid = this.randomString();
310 const elementg = editor.dom.select(`.${EditQuestion.selectors.elQuestionFibInput}[data-id="${uniquid}"]`);
311 if (elementg[0]) {
312 elementg[0].focus();
313 }
314 editor.dom.bind(elementg[0], 'input', e => {
315 //console.log( 'Input changed:', e.target.value );
316 });
317 });
318 editor.on('selectionchange', e => {
319 fibSelection = editor.selection;
320
321 // Check selection is blank, check empty blank content
322 if (fibSelection.getNode().classList.contains(`${EditQuestion.selectors.elQuestionFibInput}`)) {
323 const blankId = fibSelection.getNode().dataset.id;
324 const textBlank = fibSelection.getNode().textContent.trim();
325 if (textBlank.length === 0) {
326 const editorId = editor.id;
327 const questionId = editorId.replace(`${EditQuestion.selectors.elQuestionFibInput}-`, '');
328 const elQuestionEditMain = document.querySelector(`${EditQuestion.selectors.elQuestionEditMain}[data-question-id="${questionId}"]`);
329 const elQuestionBlankOptions = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elFibBlankOptions}`);
330 const elFibBlankOptionItem = elQuestionBlankOptions.querySelector(`${EditQuestion.selectors.elFibBlankOptionItem}[data-id="${blankId}"]`);
331 if (elFibBlankOptionItem) {
332 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elFibBlankOptionItem, 0);
333 }
334 } else {
335 const elTextarea = document.getElementById(id);
336 const elAnswersConfig = elTextarea.closest(`${EditQuestion.selectors.elAnswersConfig}`);
337 const elFibBlankOptionItem = elAnswersConfig.querySelector(`${EditQuestion.selectors.elFibBlankOptionItem}[data-id="${blankId}"]`);
338 if (elFibBlankOptionItem) {
339 const elFibOptionTitleInput = elFibBlankOptionItem.querySelector(`${EditQuestion.selectors.elFibOptionTitleInput}`);
340 if (elFibOptionTitleInput) {
341 elFibOptionTitleInput.value = textBlank;
342 }
343 }
344 }
345 }
346 });
347 editor.on('Undo', e => {
348 const contentUndo = editor.getContent();
349 const selection = editor.selection;
350 const nodeUndo = selection.getNode();
351 if (nodeUndo.classList.contains(`${EditQuestion.selectors.elQuestionFibInput}`)) {
352 const blankId = nodeUndo.dataset.id;
353 const elFibBlankOptionItem = document.querySelector(`${EditQuestion.selectors.elFibBlankOptionItem}[data-id="${blankId}"]`);
354 if (elFibBlankOptionItem) {
355 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elFibBlankOptionItem, 1);
356 }
357 }
358 });
359 editor.on('Redo', e => {});
360 });
361 }
362 autoUpdateQuestion(args) {
363 let {
364 e,
365 target,
366 key,
367 value
368 } = args;
369 const elAutoSave = target.closest(`${EditQuestion.selectors.elAutoSaveQuestion}`);
370 if (!elAutoSave) {
371 return;
372 }
373 const elQuestionEditMain = elAutoSave.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
374 const questionId = elQuestionEditMain.dataset.questionId;
375 clearTimeout(timeoutAutoUpdateQuestion);
376 timeoutAutoUpdateQuestion = setTimeout(() => {
377 // Call ajax to update question description
378 const callBack = {
379 success: response => {
380 const {
381 message,
382 status
383 } = response;
384 if (status === 'success') {
385 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, status);
386 } else {
387 throw `Error: ${message}`;
388 }
389 },
390 error: error => {
391 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
392 },
393 completed: () => {}
394 };
395 const dataSend = {
396 action: 'update_question',
397 question_id: questionId,
398 args: {
399 id_url: idUrlHandle
400 }
401 };
402 if (undefined === key) {
403 key = elAutoSave.dataset.keyAutoSave;
404 if (!key) {
405 if (!elAutoSave.classList.contains('lp-editor-tinymce')) {
406 return;
407 }
408 const textAreaId = elAutoSave.id;
409 key = textAreaId.replace(/lp-/g, '').replace(`-${questionId}`, '').replace(/-/g, '_');
410 if (!key) {
411 return;
412 }
413 }
414 value = elAutoSave.value;
415 }
416 dataSend[key] = value;
417 window.lpAJAXG.fetchAJAX(dataSend, callBack);
418 }, 700);
419 }
420 // Create question type
421 createQuestionType(args) {
422 const {
423 e,
424 target
425 } = args;
426 const elBtnQuestionCreateType = target.closest(`${EditQuestion.selectors.elBtnQuestionCreateType}`);
427 if (!elBtnQuestionCreateType) {
428 return;
429 }
430 const elQuestionEditMain = elBtnQuestionCreateType.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
431 if (!elQuestionEditMain) {
432 return;
433 }
434 const questionId = elQuestionEditMain.dataset.questionId;
435 const elQuestionTypeNew = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elQuestionTypeNew}`);
436 if (!elQuestionTypeNew) {
437 return;
438 }
439 const questionType = elQuestionTypeNew.value.trim();
440 if (!questionType) {
441 const message = elQuestionTypeNew.dataset.messEmptyType;
442 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, 'error');
443 return;
444 }
445
446 // Call ajax to create new question type
447 const callBack = {
448 success: response => {
449 const {
450 message,
451 status,
452 data
453 } = response;
454 if (status === 'success') {
455 const {
456 html_option_answers
457 } = data;
458 const elAnswersConfig = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elAnswersConfig}`);
459 elAnswersConfig.outerHTML = html_option_answers;
460 this.initTinyMCE();
461 this.sortAbleQuestionAnswer(elQuestionEditMain);
462 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, status);
463 } else {
464 throw `Error: ${message}`;
465 }
466 },
467 error: error => {
468 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
469 },
470 completed: () => {}
471 };
472 const dataSend = {
473 action: 'update_question',
474 question_id: questionId,
475 question_type: questionType,
476 args: {
477 id_url: idUrlHandle
478 }
479 };
480 window.lpAJAXG.fetchAJAX(dataSend, callBack);
481 }
482 addQuestionAnswer(args) {
483 const {
484 e,
485 target
486 } = args;
487 const elQuestionAnswerItemAddNew = target.closest(`${EditQuestion.selectors.elQuestionAnswerItemAddNew}`);
488 if (!elQuestionAnswerItemAddNew) {
489 return;
490 }
491 e.preventDefault();
492 const elQuestionAnswerTitleNewInput = elQuestionAnswerItemAddNew.querySelector(`${EditQuestion.selectors.elQuestionAnswerTitleNewInput}`);
493 if (!elQuestionAnswerTitleNewInput.value.trim()) {
494 const message = elQuestionAnswerTitleNewInput.dataset.messEmptyTitle;
495 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, 'error');
496 return;
497 }
498 const elQuestionEditMain = target.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
499 const elQuestionAnswerClone = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elQuestionAnswerItem}.clone`);
500 const elQuestionAnswerNew = elQuestionAnswerClone.cloneNode(true);
501 const elQuestionAnswerTitleInputNew = elQuestionAnswerNew.querySelector(`${EditQuestion.selectors.elQuestionAnswerTitleInput}`);
502 elQuestionAnswerNew.classList.remove('clone');
503 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elQuestionAnswerNew, 1);
504 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionAnswerNew, 1);
505 elQuestionAnswerClone.insertAdjacentElement('beforebegin', elQuestionAnswerNew);
506 const answerTitle = elQuestionAnswerTitleNewInput.value.trim();
507 elQuestionAnswerTitleInputNew.value = answerTitle;
508 elQuestionAnswerTitleNewInput.value = '';
509 const questionId = elQuestionEditMain.dataset.questionId;
510
511 // Call ajax to add new question answer
512 const callBack = {
513 success: response => {
514 const {
515 message,
516 status,
517 data
518 } = response;
519 if (status === 'success') {
520 const {
521 question_answer
522 } = data;
523 elQuestionAnswerNew.dataset.answerId = question_answer.question_answer_id;
524 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionAnswerNew, 0);
525
526 // Set data lp-answers-config
527 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
528 dataAnswers.push(question_answer);
529 this.setDataAnswersConfig(elQuestionEditMain, dataAnswers);
530 } else {
531 throw `Error: ${message}`;
532 }
533 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, status);
534 },
535 error: error => {
536 elQuestionAnswerNew.remove();
537 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
538 },
539 completed: () => {}
540 };
541 const dataSend = {
542 action: 'add_question_answer',
543 question_id: questionId,
544 answer_title: answerTitle,
545 args: {
546 id_url: idUrlHandle
547 }
548 };
549 window.lpAJAXG.fetchAJAX(dataSend, callBack);
550 }
551
552 // Check to enable or disable add new question button
553 checkCanAddAnswer(args) {
554 const {
555 e,
556 target
557 } = args;
558 const elTrigger = target.closest(EditQuestion.selectors.elQuestionAnswerTitleNewInput);
559 if (!elTrigger) {
560 return;
561 }
562 const elQuestionAnswerItemAddNew = elTrigger.closest(`${EditQuestion.selectors.elQuestionAnswerItemAddNew}`);
563 if (!elQuestionAnswerItemAddNew) {
564 return;
565 }
566 const elBtnAddAnswer = elQuestionAnswerItemAddNew.querySelector(`${EditQuestion.selectors.elBtnAddAnswer}`);
567 if (!elBtnAddAnswer) {
568 return;
569 }
570 const titleValue = elTrigger.value.trim();
571 if (titleValue) {
572 elBtnAddAnswer.classList.add('active');
573 } else {
574 elBtnAddAnswer.classList.remove('active');
575 }
576 }
577
578 // Auto update question answer
579 autoUpdateAnswer(args) {
580 const {
581 e,
582 target
583 } = args;
584 const elAutoSaveAnswer = target.closest(`${EditQuestion.selectors.elAutoSaveAnswer}`);
585 if (!elAutoSaveAnswer) {
586 return;
587 }
588 const elQuestionAnswerItem = elAutoSaveAnswer.closest(`${EditQuestion.selectors.elQuestionAnswerItem}`);
589 clearTimeout(timeoutAutoUpdateAnswer);
590 timeoutAutoUpdateAnswer = setTimeout(() => {
591 const elQuestionEditMain = elAutoSaveAnswer.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
592 const questionId = elQuestionEditMain.dataset.questionId;
593 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
594 const elAnswersConfig = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elAnswersConfig}`);
595
596 // For both radio and checkbox.
597 const dataAnswersOld = structuredClone(dataAnswers);
598
599 // Get position of answers
600 const elQuestionAnswerItems = elAnswersConfig.querySelectorAll(`${EditQuestion.selectors.elQuestionAnswerItem}:not(.clone)`);
601 const answersPosition = {};
602 elQuestionAnswerItems.forEach((elQuestionAnswerItem, index) => {
603 answersPosition[elQuestionAnswerItem.dataset.answerId] = index + 1; // Start from 1
604 });
605
606 //console.log( 'answersPosition', answersPosition );
607
608 dataAnswers.map((answer, k) => {
609 const elQuestionAnswerItem = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elQuestionAnswerItem}[data-answer-id="${answer.question_answer_id}"]`);
610 const elInputAnswerSetTrue = elQuestionAnswerItem.querySelector(`${EditQuestion.selectors.elInputAnswerSetTrue}`);
611 const elInputAnswerTitle = elQuestionAnswerItem.querySelector(`${EditQuestion.selectors.elQuestionAnswerTitleInput}`);
612
613 // Set title
614 if (elInputAnswerTitle) {
615 answer.title = elInputAnswerTitle.value.trim();
616 }
617
618 // Set true answer
619 if (elInputAnswerSetTrue) {
620 if (elInputAnswerSetTrue.checked) {
621 answer.is_true = 'yes';
622 } else {
623 answer.is_true = '';
624 }
625 }
626
627 // Set position
628 if (answersPosition[answer.question_answer_id]) {
629 answer.order = answersPosition[answer.question_answer_id];
630 }
631 return answer;
632 });
633
634 //console.log( dataAnswers );
635
636 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionAnswerItem, 1);
637
638 // Call ajax to update answers config
639 const callBack = {
640 success: response => {
641 const {
642 message,
643 status
644 } = response;
645 if (status === 'success') {} else {
646 throw `Error: ${message}`;
647 }
648 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, status);
649 },
650 error: error => {
651 // rollback changes to old data
652 dataAnswersOld.forEach(answer => {
653 const elAnswerItem = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elQuestionAnswerItem}[data-answer-id="${answer.question_answer_id}"]`);
654 const inputAnswerSetTrue = elAnswerItem.querySelector(`${EditQuestion.selectors.elInputAnswerSetTrue}`);
655 if (answer.is_true === 'yes') {
656 inputAnswerSetTrue.checked = true;
657 }
658 return answer;
659 });
660 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
661 },
662 completed: () => {
663 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionAnswerItem, 0);
664 }
665 };
666 const dataSend = {
667 action: 'update_question_answers_config',
668 question_id: questionId,
669 answers: dataAnswers,
670 args: {
671 id_url: idUrlHandle
672 }
673 };
674 window.lpAJAXG.fetchAJAX(dataSend, callBack);
675 }, 700);
676 }
677
678 // Sortable answers's question
679 sortAbleQuestionAnswer(elQuestionEditMain) {
680 let isUpdateSectionPosition = 0;
681 let timeout;
682 const elQuestionAnswers = elQuestionEditMain.querySelectorAll(`${EditQuestion.selectors.elAnswersConfig}`);
683 elQuestionAnswers.forEach(elAnswersConfig => {
684 new sortablejs__WEBPACK_IMPORTED_MODULE_3__["default"](elAnswersConfig, {
685 handle: '.drag',
686 animation: 150,
687 onEnd: evt => {
688 const elQuestionAnswerItem = evt.item;
689 if (!isUpdateSectionPosition) {
690 // No change in section position, do nothing
691 return;
692 }
693 clearTimeout(timeout);
694 timeout = setTimeout(() => {
695 const elAutoSaveAnswer = elQuestionAnswerItem.querySelector(`${EditQuestion.selectors.elAutoSaveAnswer}`);
696 this.autoUpdateAnswer({
697 e: null,
698 target: elAutoSaveAnswer
699 });
700 }, 1000);
701 },
702 onMove: evt => {
703 clearTimeout(timeout);
704 },
705 onUpdate: evt => {
706 isUpdateSectionPosition = 1;
707 }
708 });
709 });
710 }
711
712 // Delete question answer
713 deleteQuestionAnswer(args) {
714 const {
715 e,
716 target
717 } = args;
718 const elBtnDeleteAnswer = target.closest(`${EditQuestion.selectors.elBtnDeleteAnswer}`);
719 if (!elBtnDeleteAnswer) {
720 return;
721 }
722 const elQuestionAnswerItem = elBtnDeleteAnswer.closest(`${EditQuestion.selectors.elQuestionAnswerItem}`);
723 if (!elQuestionAnswerItem) {
724 return;
725 }
726 const elQuestionEditMain = elBtnDeleteAnswer.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
727 const questionId = elQuestionEditMain.dataset.questionId;
728 const questionAnswerId = elQuestionAnswerItem.dataset.answerId;
729 if (!questionId || !questionAnswerId) {
730 return;
731 }
732 sweetalert2__WEBPACK_IMPORTED_MODULE_2___default().fire({
733 title: elBtnDeleteAnswer.dataset.title || 'Are you sure?',
734 text: elBtnDeleteAnswer.dataset.content || 'Do you want to delete this answer?',
735 icon: 'warning',
736 showCloseButton: true,
737 showCancelButton: true,
738 cancelButtonText: lpData.i18n.cancel,
739 confirmButtonText: lpData.i18n.yes,
740 reverseButtons: true
741 }).then(result => {
742 if (result.isConfirmed) {
743 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionAnswerItem, 1);
744
745 // Call ajax to delete item from section
746 const callBack = {
747 success: response => {
748 const {
749 message,
750 status
751 } = response;
752 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, status);
753 if (status === 'success') {
754 const elQuestionAnswerId = parseInt(elQuestionAnswerItem.dataset.answerId);
755 elQuestionAnswerItem.remove();
756 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
757 if (dataAnswers) {
758 const updatedAnswers = dataAnswers.filter(answer => parseInt(answer.question_answer_id) !== elQuestionAnswerId);
759 this.setDataAnswersConfig(elQuestionEditMain, updatedAnswers);
760 }
761 }
762 },
763 error: error => {
764 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
765 },
766 completed: () => {
767 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionAnswerItem, 0);
768 }
769 };
770 const dataSend = {
771 action: 'delete_question_answer',
772 question_id: questionId,
773 question_answer_id: questionAnswerId,
774 args: {
775 id_url: idUrlHandle
776 }
777 };
778 window.lpAJAXG.fetchAJAX(dataSend, callBack);
779 }
780 });
781 }
782
783 // Get data answers config
784 getDataAnswersConfig(elQuestionEditMain) {
785 const elAnswersConfig = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elAnswersConfig}`);
786 if (!elAnswersConfig) {
787 return null;
788 }
789 let dataAnswers = elAnswersConfig.dataset.answers || '[]';
790 try {
791 dataAnswers = JSON.parse(dataAnswers);
792 } catch (e) {
793 dataAnswers = [];
794 }
795 if (!dataAnswers.meta_data) {
796 dataAnswers.meta_data = {};
797 }
798 return dataAnswers;
799 }
800
801 // Set data answers config
802 setDataAnswersConfig(elQuestionEditMain, dataAnswers) {
803 const elAnswersConfig = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elAnswersConfig}`);
804 if (!elAnswersConfig) {
805 return;
806 }
807 if (!dataAnswers || typeof dataAnswers !== 'object') {
808 dataAnswers = {};
809 }
810 elAnswersConfig.dataset.answers = JSON.stringify(dataAnswers);
811 }
812
813 /***** Fill in the blank question type *****/
814 // For FIB question type
815 fibInsertBlank = args => {
816 const {
817 e,
818 target
819 } = args;
820 const elBtnFibInsertBlank = target.closest(EditQuestion.selectors.elBtnFibInsertBlank);
821 if (!elBtnFibInsertBlank) {
822 return;
823 }
824 const textPlaceholder = elBtnFibInsertBlank.dataset.defaultText;
825 const elQuestionEditMain = elBtnFibInsertBlank.closest(EditQuestion.selectors.elQuestionEditMain);
826 const questionId = elQuestionEditMain.dataset.questionId;
827 const messErrInserted = elBtnFibInsertBlank.dataset.messInserted;
828 const messErrRequireSelectText = elBtnFibInsertBlank.dataset.messRequireSelectText;
829 const idEditor = `${EditQuestion.selectors.elQuestionFibInput}-${questionId}`;
830 const uniquid = this.randomString();
831 let selectedText;
832 if (fibSelection) {
833 const elNode = fibSelection.getNode();
834 if (!elNode) {
835 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show('Event insert blank has error, please try again', 'error');
836 return;
837 }
838 const findParent = elNode.closest(`body[data-id="${idEditor}"]`);
839 if (!findParent) {
840 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(messErrRequireSelectText, 'error');
841 return;
842 }
843 if (elNode.classList.contains(`${EditQuestion.selectors.elQuestionFibInput}`)) {
844 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(messErrInserted, 'error');
845 return;
846 }
847 selectedText = fibSelection.getContent();
848 if (selectedText.length === 0) {
849 selectedText = textPlaceholder;
850 }
851 const elInputNew = `<span class="${EditQuestion.selectors.elQuestionFibInput}" data-id="${uniquid}">${selectedText}</span>`;
852 fibSelection.setContent(elInputNew);
853 } else {
854 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(messErrRequireSelectText, 'error');
855 return;
856 }
857 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
858 dataAnswers.meta_data = dataAnswers.meta_data || {};
859 // Convert array to object
860 if (Object.keys(dataAnswers.meta_data).length === 0) {
861 dataAnswers.meta_data = {};
862 }
863 dataAnswers.meta_data[uniquid] = {
864 id: uniquid,
865 match_case: 0,
866 comparison: 'equal',
867 fill: selectedText,
868 index: 1,
869 open: false
870 };
871 this.setDataAnswersConfig(elQuestionEditMain, dataAnswers);
872
873 // Clone blank options
874 const elFibBlankOptions = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elFibBlankOptions}`);
875 const elFibBlankOptionItemClone = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elFibBlankOptionItemClone}`);
876 const elFibBlankOptionItemNew = elFibBlankOptionItemClone.cloneNode(true);
877 const countOptions = elFibBlankOptions.querySelectorAll(`${EditQuestion.selectors.elFibBlankOptionItem}:not(.clone)`).length;
878 const elFibBlankOptionIndex = elFibBlankOptionItemNew.querySelector(`${EditQuestion.selectors.elFibBlankOptionIndex}`);
879 const elFibOptionTitleInput = elFibBlankOptionItemNew.querySelector(`${EditQuestion.selectors.elFibOptionTitleInput}`);
880 const elFibOptionMatchCaseInput = elFibBlankOptionItemNew.querySelector(`${EditQuestion.selectors.elFibOptionMatchCaseInput}`);
881 const elFibOptionComparisonInput = elFibBlankOptionItemNew.querySelectorAll(`${EditQuestion.selectors.elFibOptionComparisonInput}`);
882 elFibBlankOptionItemNew.dataset.id = uniquid;
883 elFibOptionTitleInput.name = `${EditQuestion.selectors.elFibOptionTitleInput}-${uniquid}`;
884 elFibOptionTitleInput.value = this.decodeHtml(selectedText);
885 elFibBlankOptionIndex.textContent = countOptions + 1 + '.';
886 elFibOptionMatchCaseInput.name = `${EditQuestion.selectors.elFibOptionMatchCaseInput}-${uniquid}`.replace(/\./g, '');
887 elFibOptionComparisonInput.forEach(elInput => {
888 elInput.name = `${EditQuestion.selectors.elFibOptionComparisonInput}-${uniquid}`.replace(/\./g, '');
889 if (elInput.value === 'equal') {
890 elInput.checked = true;
891 }
892 });
893 elFibBlankOptionItemClone.insertAdjacentElement('beforebegin', elFibBlankOptionItemNew);
894 elFibBlankOptionItemNew.classList.remove('clone');
895 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elFibBlankOptionItemNew, 1);
896 // End clone blank options
897
898 const elBtnFibSaveContent = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elBtnFibSaveContent}`);
899 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibInsertBlank, 1);
900 this.fibSaveContent({
901 e: null,
902 target: elBtnFibSaveContent,
903 callBackCompleted: () => {
904 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibInsertBlank, 0);
905 }
906 });
907 };
908
909 // Delete all blanks
910 fibDeleteAllBlanks(args) {
911 const {
912 e,
913 target
914 } = args;
915 const elBtnFibDeleteAllBlanks = target.closest(`${EditQuestion.selectors.elBtnFibDeleteAllBlanks}`);
916 if (!elBtnFibDeleteAllBlanks) {
917 return;
918 }
919 const elQuestionEditMain = elBtnFibDeleteAllBlanks.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
920 if (!elQuestionEditMain) {
921 return;
922 }
923 const questionId = elQuestionEditMain.dataset.questionId;
924 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
925 sweetalert2__WEBPACK_IMPORTED_MODULE_2___default().fire({
926 title: elBtnFibDeleteAllBlanks.dataset.title,
927 text: elBtnFibDeleteAllBlanks.dataset.content,
928 icon: 'warning',
929 showCloseButton: true,
930 showCancelButton: true,
931 cancelButtonText: lpData.i18n.cancel,
932 confirmButtonText: lpData.i18n.yes,
933 reverseButtons: true
934 }).then(result => {
935 if (result.isConfirmed) {
936 const editor = window.tinymce.get(`${EditQuestion.selectors.elQuestionFibInput}-${questionId}`);
937 const elBlanks = editor.dom.select(`.${EditQuestion.selectors.elQuestionFibInput}`);
938 elBlanks.forEach(elBlank => {
939 editor.dom.remove(elBlank, true);
940 });
941 dataAnswers.meta_data = {};
942 this.setDataAnswersConfig(elQuestionEditMain, dataAnswers);
943 const elFibBlankOptions = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elFibBlankOptions}`);
944 const elFibBlankOptionItems = elFibBlankOptions.querySelectorAll(`${EditQuestion.selectors.elFibBlankOptionItem}:not(.clone)`);
945 elFibBlankOptionItems.forEach(elFibBlankOptionItem => {
946 elFibBlankOptionItem.remove();
947 });
948 const elBtnFibSaveContent = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elBtnFibSaveContent}`);
949 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibDeleteAllBlanks, 1);
950 this.fibSaveContent({
951 e: null,
952 target: elBtnFibSaveContent,
953 callBackCompleted: () => {
954 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibDeleteAllBlanks, 0);
955 }
956 });
957 }
958 });
959 }
960 // Clear content FIB question
961 fibClearContent(args) {
962 const {
963 e,
964 target
965 } = args;
966 const elBtnFibClearAllContent = target.closest(`${EditQuestion.selectors.elBtnFibClearAllContent}`);
967 if (!elBtnFibClearAllContent) {
968 return;
969 }
970 const elQuestionEditMain = elBtnFibClearAllContent.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
971 if (!elQuestionEditMain) {
972 return;
973 }
974 const questionId = elQuestionEditMain.dataset.questionId;
975 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
976 sweetalert2__WEBPACK_IMPORTED_MODULE_2___default().fire({
977 title: elBtnFibClearAllContent.dataset.title,
978 text: elBtnFibClearAllContent.dataset.content,
979 icon: 'warning',
980 showCloseButton: true,
981 showCancelButton: true,
982 cancelButtonText: lpData.i18n.cancel,
983 confirmButtonText: lpData.i18n.yes,
984 reverseButtons: true
985 }).then(result => {
986 if (result.isConfirmed) {
987 const editor = window.tinymce.get(`lp-question-fib-input-${questionId}`);
988 editor.setContent('');
989 dataAnswers.meta_data = {};
990 this.setDataAnswersConfig(elQuestionEditMain, dataAnswers);
991 const elFibBlankOptions = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elFibBlankOptions}`);
992 const elFibBlankOptionItems = elFibBlankOptions.querySelectorAll(`${EditQuestion.selectors.elFibBlankOptionItem}:not(.clone)`);
993 elFibBlankOptionItems.forEach(elFibBlankOptionItem => {
994 elFibBlankOptionItem.remove();
995 });
996 const elBtnFibSaveContent = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elBtnFibSaveContent}`);
997 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibClearAllContent, 1);
998 this.fibSaveContent({
999 e: null,
1000 target: elBtnFibSaveContent,
1001 callBackCompleted: () => {
1002 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibClearAllContent, 0);
1003 }
1004 });
1005 }
1006 });
1007 }
1008
1009 // Remove blank
1010 fibDeleteBlank(args) {
1011 const {
1012 e,
1013 target
1014 } = args;
1015 const elBtnFibOptionDelete = target.closest(`${EditQuestion.selectors.elBtnFibOptionDelete}`);
1016 if (!elBtnFibOptionDelete) {
1017 return;
1018 }
1019 const elQuestionEditMain = elBtnFibOptionDelete.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
1020 if (!elQuestionEditMain) {
1021 return;
1022 }
1023 const questionId = elQuestionEditMain.dataset.questionId;
1024 const elAnswersConfig = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elAnswersConfig}`);
1025 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
1026 const elFibBlankOptionItem = elBtnFibOptionDelete.closest(`${EditQuestion.selectors.elFibBlankOptionItem}`);
1027 const blankId = elFibBlankOptionItem.dataset.id;
1028 sweetalert2__WEBPACK_IMPORTED_MODULE_2___default().fire({
1029 title: elBtnFibOptionDelete.dataset.title,
1030 text: elBtnFibOptionDelete.dataset.content,
1031 icon: 'warning',
1032 showCloseButton: true,
1033 showCancelButton: true,
1034 cancelButtonText: lpData.i18n.cancel,
1035 confirmButtonText: lpData.i18n.yes,
1036 reverseButtons: true
1037 }).then(result => {
1038 if (result.isConfirmed) {
1039 // Find span with id on editor and remove it
1040 const editor = window.tinymce.get(`${EditQuestion.selectors.elQuestionFibInput}-${questionId}`);
1041 const elBlank = editor.dom.select(`.${EditQuestion.selectors.elQuestionFibInput}[data-id="${blankId}"]`);
1042 if (elBlank[0]) {
1043 // Remove tag html but keep content
1044 editor.dom.remove(elBlank[0], true);
1045 }
1046 elFibBlankOptionItem.remove();
1047 dataAnswers.meta_data = dataAnswers.meta_data || {};
1048 if (dataAnswers.meta_data[blankId]) {
1049 delete dataAnswers.meta_data[blankId];
1050 }
1051 this.setDataAnswersConfig(elQuestionEditMain, dataAnswers);
1052 const elBtnFibSaveContent = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elBtnFibSaveContent}`);
1053 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elFibBlankOptionItem, 1);
1054 this.fibSaveContent({
1055 e: null,
1056 target: elBtnFibSaveContent,
1057 callBackCompleted: () => {
1058 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elFibBlankOptionItem, 0);
1059 }
1060 });
1061 }
1062 });
1063 }
1064
1065 // Change title of blank option
1066 fibOptionTitleInputChange(args) {
1067 const {
1068 e,
1069 target
1070 } = args;
1071 const elFibOptionTitleInput = target.closest(`${EditQuestion.selectors.elFibOptionTitleInput}`);
1072 if (!elFibOptionTitleInput) {
1073 return;
1074 }
1075 const elQuestionFibOptionItem = elFibOptionTitleInput.closest(`${EditQuestion.selectors.elFibBlankOptionItem}`);
1076 if (!elQuestionFibOptionItem) {
1077 return;
1078 }
1079 const elQuestionEditMain = elFibOptionTitleInput.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
1080 if (!elQuestionEditMain) {
1081 return;
1082 }
1083 const value = elFibOptionTitleInput.value.trim();
1084 const blankId = elQuestionFibOptionItem.dataset.id;
1085 const questionId = elQuestionEditMain.dataset.questionId;
1086 const editor = window.tinymce.get(`lp-question-fib-input-${questionId}`);
1087 const elBlank = editor.dom.select(`.lp-question-fib-input[data-id="${blankId}"]`);
1088 if (elBlank[0]) {
1089 // Update content of blank
1090 elBlank[0].textContent = value;
1091 }
1092 clearTimeout(timeoutAutoUpdateFib);
1093 timeoutAutoUpdateFib = setTimeout(() => {
1094 // Call ajax to update question description
1095 const elBtnFibSaveContent = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elBtnFibSaveContent}`);
1096 this.fibSaveContent({
1097 e: null,
1098 target: elBtnFibSaveContent
1099 });
1100 }, 700);
1101 }
1102
1103 // Save content FIB question
1104 fibSaveContent(args) {
1105 const {
1106 e,
1107 target,
1108 callBackCompleted = null
1109 } = args;
1110 const elBtnFibSaveContent = target.closest(`${EditQuestion.selectors.elBtnFibSaveContent}`);
1111 if (!elBtnFibSaveContent) {
1112 return;
1113 }
1114 const elQuestionEditMain = elBtnFibSaveContent.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
1115 const questionId = elQuestionEditMain.dataset.questionId;
1116 const dataAnswers = this.getDataAnswersConfig(elQuestionEditMain);
1117 if (!dataAnswers) {
1118 return;
1119 }
1120 const editor = window.tinymce.get(`${EditQuestion.selectors.elQuestionFibInput}-${questionId}`);
1121 dataAnswers.title = editor.getContent();
1122 const elFibBlankOptionItems = elQuestionEditMain.querySelectorAll(`${EditQuestion.selectors.elFibBlankOptionItem}:not(.clone)`);
1123 if (elFibBlankOptionItems) {
1124 elFibBlankOptionItems.forEach(elFibBlankOptionItem => {
1125 const blankId = elFibBlankOptionItem.dataset.id;
1126 const elFibOptionMatchCaseInput = elFibBlankOptionItem.querySelector(`${EditQuestion.selectors.elFibOptionMatchCaseInput}`);
1127 const elFibOptionComparisonInput = elFibBlankOptionItem.querySelector(`${EditQuestion.selectors.elFibOptionComparisonInput}:checked`);
1128 dataAnswers.meta_data[blankId].match_case = elFibOptionMatchCaseInput.checked ? 1 : 0;
1129 dataAnswers.meta_data[blankId].comparison = elFibOptionComparisonInput.value;
1130 });
1131 }
1132
1133 //console.log( 'dataAnswers', dataAnswers );
1134
1135 if (!callBackCompleted) {
1136 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibSaveContent, 1);
1137 }
1138
1139 // Call ajax to update answers config
1140 const callBack = {
1141 success: response => {
1142 const {
1143 message,
1144 status
1145 } = response;
1146 if (status === 'success') {
1147 this.setDataAnswersConfig(elQuestionEditMain, dataAnswers);
1148 } else {
1149 throw `Error: ${message}`;
1150 }
1151 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(message, status);
1152 },
1153 error: error => {
1154 lpAssetsJsPath_lpToastify__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
1155 },
1156 completed: () => {
1157 if (callBackCompleted && typeof callBackCompleted === 'function') {
1158 callBackCompleted();
1159 } else {
1160 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elBtnFibSaveContent, 0);
1161 }
1162 }
1163 };
1164
1165 //console.log( 'dataAnswers', dataAnswers );
1166
1167 const dataSend = {
1168 action: 'update_question_answers_config',
1169 question_id: questionId,
1170 answers: dataAnswers,
1171 args: {
1172 id_url: idUrlHandle
1173 }
1174 };
1175 window.lpAJAXG.fetchAJAX(dataSend, callBack);
1176 }
1177 // Show/hide match case option
1178 fibShowHideMatchCaseOption(args) {
1179 const {
1180 e,
1181 target
1182 } = args;
1183 const elFibOptionMatchCaseInput = target.closest(`${EditQuestion.selectors.elFibOptionMatchCaseInput}`);
1184 if (!elFibOptionMatchCaseInput) {
1185 return;
1186 }
1187 const elQuestionFibOptionDetail = elFibOptionMatchCaseInput.closest(`${EditQuestion.selectors.elQuestionFibOptionDetail}`);
1188 const elFibOptionMatchCaseWrap = elQuestionFibOptionDetail.querySelector(`${EditQuestion.selectors.elFibOptionMatchCaseWrap}`);
1189 if (!elQuestionFibOptionDetail || !elFibOptionMatchCaseWrap) {
1190 return;
1191 }
1192 if (elFibOptionMatchCaseInput.checked) {
1193 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elFibOptionMatchCaseWrap, 1);
1194 } else {
1195 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elFibOptionMatchCaseWrap, 0);
1196 }
1197 const elQuestionEditMain = elFibOptionMatchCaseInput.closest(`${EditQuestion.selectors.elQuestionEditMain}`);
1198 const elBtnFibSaveContent = elQuestionEditMain.querySelector(`${EditQuestion.selectors.elBtnFibSaveContent}`);
1199 elBtnFibSaveContent.click();
1200 }
1201 /***** End Fill in the blank question type *****/
1202
1203 // Generate a random string of specified length, for set unique id
1204 randomString(length = 10) {
1205 const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
1206 let result = '';
1207 for (let i = 0; i < length; i++) {
1208 result += chars.charAt(Math.floor(Math.random() * chars.length));
1209 }
1210 return result;
1211 }
1212 // Decode HTML entities
1213 decodeHtml(html) {
1214 const txt = document.createElement('textarea');
1215 txt.innerHTML = html;
1216 return txt.value;
1217 }
1218 }
1219 const editQuestion = new EditQuestion();
1220 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpOnElementReady(EditQuestion.selectors.elEditQuestionWrap, elEditQuestionWrap => {
1221 const findClass = EditQuestion.selectors.elQuestionEditMain.replace('.', '');
1222 if (!elEditQuestionWrap.classList.contains(findClass)) {
1223 return;
1224 }
1225 editQuestion.init();
1226 });
1227
1228 /***/ },
1229
1230 /***/ "./assets/src/js/lpPopupSelectItemToAdd.js"
1231 /*!*************************************************!*\
1232 !*** ./assets/src/js/lpPopupSelectItemToAdd.js ***!
1233 \*************************************************/
1234 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1235
1236 "use strict";
1237 __webpack_require__.r(__webpack_exports__);
1238 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1239 /* harmony export */ LpPopupSelectItemToAdd: () => (/* binding */ LpPopupSelectItemToAdd)
1240 /* harmony export */ });
1241 /* harmony import */ var lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lpAssetsJsPath/utils.js */ "./assets/src/js/utils.js");
1242 /* harmony import */ var lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lpAssetsJsPath/lpToastify.js */ "./assets/src/js/lpToastify.js");
1243 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! sweetalert2 */ "./node_modules/sweetalert2/dist/sweetalert2.all.js");
1244 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(sweetalert2__WEBPACK_IMPORTED_MODULE_2__);
1245 /**
1246 * LearnPress Popup Select Item
1247 *
1248 * Handles load(search) item from API, show in popup and select item.
1249 */
1250
1251
1252
1253
1254 let itemsSelectedData = [];
1255 let elPopup;
1256 let timeSearchTitleItem;
1257 class LpPopupSelectItemToAdd {
1258 constructor() {
1259 this.init();
1260 }
1261 static selectors = {
1262 elBtnShowPopupItemsToSelect: '.lp-btn-show-popup-items-to-select',
1263 elBtnAddItemsSelected: '.lp-btn-add-items-selected',
1264 elBtnCountItemsSelected: '.lp-btn-count-items-selected',
1265 elHeaderCountItemSelected: '.header-count-items-selected',
1266 elSelectItem: '.lp-select-item',
1267 elListItems: '.list-items',
1268 elPopupItemsToSelect: '.lp-popup-items-to-select',
1269 elSearchTitleItem: '.lp-search-title-item',
1270 elBtnBackListItems: '.lp-btn-back-to-select-items',
1271 elListItemsWrap: '.list-items-wrap',
1272 elListItemsSelected: '.list-items-selected',
1273 elItemSelectedClone: '.li-item-selected.clone',
1274 elItemSelected: '.li-item-selected',
1275 LPTarget: '.lp-target'
1276 };
1277 init() {
1278 this.events();
1279 }
1280 events = () => {
1281 if (LpPopupSelectItemToAdd._loadedEvents) {
1282 return;
1283 }
1284 LpPopupSelectItemToAdd._loadedEvents = true;
1285 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('click', [{
1286 selector: LpPopupSelectItemToAdd.selectors.elBtnShowPopupItemsToSelect,
1287 callBack: this.showPopupItemsToSelect.name,
1288 class: this
1289 }, {
1290 selector: LpPopupSelectItemToAdd.selectors.elSelectItem,
1291 callBack: this.selectItemsFromList.name,
1292 class: this
1293 }, {
1294 selector: LpPopupSelectItemToAdd.selectors.elBtnCountItemsSelected,
1295 callBack: this.showItemsSelected.name,
1296 class: this
1297 }, {
1298 selector: LpPopupSelectItemToAdd.selectors.elBtnBackListItems,
1299 callBack: this.backToSelectItems.name,
1300 class: this
1301 }, {
1302 selector: LpPopupSelectItemToAdd.selectors.elItemSelected,
1303 callBack: this.removeItemSelected.name,
1304 class: this
1305 }, {
1306 selector: '.tabs .tab',
1307 callBack: this.chooseTabItemsType.name,
1308 class: this
1309 }]);
1310 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('keyup', [{
1311 selector: LpPopupSelectItemToAdd.selectors.elSearchTitleItem,
1312 callBack: this.searchTitleItemToSelect.name,
1313 class: this
1314 }]);
1315 };
1316
1317 // Show popup items to select
1318 showPopupItemsToSelect = args => {
1319 const {
1320 e,
1321 target = false,
1322 callBack
1323 } = args;
1324 const elBtnShowPopupItemsToSelect = target.closest(`${LpPopupSelectItemToAdd.selectors.elBtnShowPopupItemsToSelect}`);
1325 if (!elBtnShowPopupItemsToSelect) {
1326 return;
1327 }
1328
1329 // Reset items selected data when opening popup
1330 itemsSelectedData = [];
1331 const templateId = target.dataset.template || '';
1332 const modalTemplate = document.querySelector(templateId);
1333 sweetalert2__WEBPACK_IMPORTED_MODULE_2___default().fire({
1334 html: modalTemplate.innerHTML,
1335 showConfirmButton: false,
1336 showCloseButton: true,
1337 width: '60%',
1338 customClass: {
1339 popup: 'lp-select-items-popup',
1340 htmlContainer: 'lp-select-items-html-container',
1341 container: 'lp-select-items-container'
1342 },
1343 willOpen: () => {
1344 elPopup = sweetalert2__WEBPACK_IMPORTED_MODULE_2___default().getPopup();
1345 const elLPTarget = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.LPTarget}`);
1346 if (elLPTarget) {
1347 const dataSend = window.lpAJAXG.getDataSetCurrent(elLPTarget);
1348 dataSend.args.paged = 1;
1349 dataSend.args.item_selecting = itemsSelectedData || [];
1350 window.lpAJAXG.setDataSetCurrent(elLPTarget, dataSend);
1351 window.lpAJAXG.fetchAJAX(dataSend, {
1352 success: response => {
1353 const {
1354 data
1355 } = response;
1356 const elSkeleton = elPopup.querySelector('.lp-skeleton-animation');
1357 elSkeleton.remove();
1358 elLPTarget.innerHTML = data.content || '';
1359 this.watchItemsSelectedDataChange();
1360 }
1361 });
1362 }
1363 }
1364 }).then(result => {
1365 if (result.isDismissed) {}
1366 });
1367 };
1368
1369 // Choose tab items type
1370 chooseTabItemsType = args => {
1371 const {
1372 e,
1373 target,
1374 callBack
1375 } = args;
1376 const elTabType = target.closest('.tab');
1377 if (!elTabType) {
1378 return;
1379 }
1380 e.preventDefault();
1381 const elTabs = elTabType.closest('.tabs');
1382 if (!elTabs) {
1383 return;
1384 }
1385 const elSelectItemsToAdd = elTabs.closest(`${LpPopupSelectItemToAdd.selectors.elPopupItemsToSelect}`);
1386 const elInputSearch = elSelectItemsToAdd.querySelector(`${LpPopupSelectItemToAdd.selectors.elSearchTitleItem}`);
1387 const itemType = elTabType.dataset.type;
1388 const elTabLis = elTabs.querySelectorAll('.tab');
1389 elTabLis.forEach(elTabLi => {
1390 if (elTabLi.classList.contains('active')) {
1391 elTabLi.classList.remove('active');
1392 }
1393 });
1394 elTabType.classList.add('active');
1395 // Reset search input
1396 elInputSearch.value = '';
1397 const elLPTarget = elSelectItemsToAdd.querySelector(`${LpPopupSelectItemToAdd.selectors.LPTarget}`);
1398 const dataSend = window.lpAJAXG.getDataSetCurrent(elLPTarget);
1399 dataSend.args.item_type = itemType;
1400 dataSend.args.paged = 1;
1401 dataSend.args.item_selecting = itemsSelectedData || [];
1402 window.lpAJAXG.setDataSetCurrent(elLPTarget, dataSend);
1403 window.lpAJAXG.showHideLoading(elLPTarget, 1);
1404 window.lpAJAXG.fetchAJAX(dataSend, {
1405 success: response => {
1406 const {
1407 data
1408 } = response;
1409 elLPTarget.innerHTML = data.content || '';
1410 },
1411 error: error => {
1412 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
1413 },
1414 completed: () => {
1415 window.lpAJAXG.showHideLoading(elLPTarget, 0);
1416 this.watchItemsSelectedDataChange();
1417 }
1418 });
1419 };
1420
1421 // Choice items to add list items selected before adding to section
1422 selectItemsFromList = args => {
1423 const {
1424 e,
1425 target
1426 } = args;
1427 const elItemAttend = target.closest(`${LpPopupSelectItemToAdd.selectors.elSelectItem}`);
1428 if (!elItemAttend) {
1429 return;
1430 }
1431 const elInput = elItemAttend.querySelector('input[type="checkbox"]');
1432 if (target.tagName !== 'INPUT') {
1433 elInput.click();
1434 return;
1435 }
1436 const elUl = elItemAttend.closest(`${LpPopupSelectItemToAdd.selectors.elListItems}`);
1437 if (!elUl) {
1438 return;
1439 }
1440 const itemSelected = {
1441 ...elInput.dataset
1442 };
1443 //console.log( 'itemSelected', itemSelected );
1444
1445 if (elInput.checked) {
1446 const exists = itemsSelectedData.some(item => item.id === itemSelected.id);
1447 if (!exists) {
1448 itemsSelectedData.push(itemSelected);
1449 }
1450 } else {
1451 const index = itemsSelectedData.findIndex(item => item.id === itemSelected.id);
1452 if (index !== -1) {
1453 itemsSelectedData.splice(index, 1);
1454 }
1455 }
1456 this.watchItemsSelectedDataChange();
1457 };
1458
1459 // Search title item
1460 searchTitleItemToSelect = args => {
1461 const {
1462 e,
1463 target
1464 } = args;
1465 const elInputSearch = target.closest(LpPopupSelectItemToAdd.selectors.elSearchTitleItem);
1466 if (!elInputSearch) {
1467 return;
1468 }
1469 const elLPTarget = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.LPTarget}`);
1470 clearTimeout(timeSearchTitleItem);
1471 timeSearchTitleItem = setTimeout(() => {
1472 const dataSet = window.lpAJAXG.getDataSetCurrent(elLPTarget);
1473 dataSet.args.search_title = elInputSearch.value.trim();
1474 dataSet.args.item_selecting = itemsSelectedData;
1475 dataSet.args.paged = 1;
1476 window.lpAJAXG.setDataSetCurrent(elLPTarget, dataSet);
1477
1478 // Show loading
1479 window.lpAJAXG.showHideLoading(elLPTarget, 1);
1480 window.lpAJAXG.fetchAJAX(dataSet, {
1481 success: response => {
1482 const {
1483 data
1484 } = response;
1485 elLPTarget.innerHTML = data.content || '';
1486 },
1487 error: error => {
1488 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_1__.show(error, 'error');
1489 },
1490 completed: () => {
1491 window.lpAJAXG.showHideLoading(elLPTarget, 0);
1492 }
1493 });
1494 }, 800);
1495 };
1496
1497 // Show list of items, to choose items to add to section
1498 showItemsSelected = args => {
1499 const {
1500 e,
1501 target
1502 } = args;
1503 const elBtnCountItemsSelected = target.closest(`${LpPopupSelectItemToAdd.selectors.elBtnCountItemsSelected}`);
1504 if (!elBtnCountItemsSelected) {
1505 return;
1506 }
1507 const elBtnBack = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elBtnBackListItems}`);
1508 const elTabs = elPopup.querySelector('.tabs');
1509 const elListItemsWrap = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elListItemsWrap}`);
1510 const elHeaderItemsSelected = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elHeaderCountItemSelected}`);
1511 const elListItemsSelected = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elListItemsSelected}`);
1512 const elItemClone = elListItemsSelected.querySelector(`${LpPopupSelectItemToAdd.selectors.elItemSelectedClone}`);
1513 elHeaderItemsSelected.innerHTML = elBtnCountItemsSelected.innerHTML;
1514 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elListItemsWrap, 0);
1515 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elBtnCountItemsSelected, 0);
1516 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elTabs, 0);
1517 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elBtnBack, 1);
1518 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elHeaderItemsSelected, 1);
1519 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elListItemsSelected, 1);
1520 elListItemsSelected.querySelectorAll(`${LpPopupSelectItemToAdd.selectors.elItemSelected}:not(.clone)`).forEach(elItem => {
1521 elItem.remove();
1522 });
1523 itemsSelectedData.forEach(item => {
1524 const elItemSelected = elItemClone.cloneNode(true);
1525 elItemSelected.classList.remove('clone');
1526 Object.entries(item).forEach(([key, value]) => {
1527 elItemSelected.dataset[key] = value;
1528 });
1529 const elTitleDisplay = elItemSelected.querySelector('.title-display');
1530 elTitleDisplay.innerHTML = item.title;
1531 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elItemSelected, 1);
1532 elItemClone.insertAdjacentElement('beforebegin', elItemSelected);
1533 });
1534 };
1535
1536 // Back to list of items
1537 backToSelectItems = args => {
1538 const {
1539 e,
1540 target
1541 } = args;
1542 const elBtnBack = target.closest(`${LpPopupSelectItemToAdd.selectors.elBtnBackListItems}`);
1543 if (!elBtnBack) {
1544 return;
1545 }
1546 const elBtnCountItemsSelected = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elBtnCountItemsSelected}`);
1547 const elTabs = elPopup.querySelector('.tabs');
1548 const elListItemsWrap = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elListItemsWrap}`);
1549 const elHeaderCountItemSelected = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elHeaderCountItemSelected}`);
1550 const elListItemsSelected = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elListItemsSelected}`);
1551 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elBtnCountItemsSelected, 1);
1552 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elListItemsWrap, 1);
1553 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elTabs, 1);
1554 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elBtnBack, 0);
1555 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elHeaderCountItemSelected, 0);
1556 lpAssetsJsPath_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elListItemsSelected, 0);
1557 };
1558
1559 // Remove item selected from list items selected
1560 removeItemSelected = args => {
1561 const {
1562 e,
1563 target
1564 } = args;
1565 const elRemoveItemSelected = target.closest(`${LpPopupSelectItemToAdd.selectors.elItemSelected}`);
1566 if (!elRemoveItemSelected) {
1567 return;
1568 }
1569 const itemRemove = elRemoveItemSelected.dataset;
1570 const index = itemsSelectedData.findIndex(item => item.id === itemRemove.id);
1571 if (index !== -1) {
1572 itemsSelectedData.splice(index, 1);
1573 }
1574 elRemoveItemSelected.remove();
1575 this.watchItemsSelectedDataChange();
1576 };
1577
1578 // Watch items selected when data change
1579 watchItemsSelectedDataChange = () => {
1580 // Update count items selected, disable/enable buttons
1581 const elBtnAddItemsSelected = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elBtnAddItemsSelected}`);
1582 const elBtnCountItemsSelected = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elBtnCountItemsSelected}`);
1583 const elSpanCount = elBtnCountItemsSelected.querySelector('span');
1584 const elHeaderCount = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elHeaderCountItemSelected}`);
1585 const elTarget = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.LPTarget}`);
1586 if (itemsSelectedData.length !== 0) {
1587 elBtnCountItemsSelected.disabled = false;
1588 elBtnAddItemsSelected.disabled = false;
1589 elBtnAddItemsSelected.classList.add('active');
1590 elSpanCount.textContent = `(${itemsSelectedData.length})`;
1591 elHeaderCount.innerHTML = elBtnCountItemsSelected.innerHTML;
1592 } else {
1593 elBtnCountItemsSelected.disabled = true;
1594 elBtnAddItemsSelected.disabled = true;
1595 elBtnAddItemsSelected.classList.remove('active');
1596 elSpanCount.textContent = '';
1597 elHeaderCount.textContent = '';
1598 }
1599
1600 // Update list input checked, when items removed, or change tab type
1601 const elListItems = elPopup.querySelector(`${LpPopupSelectItemToAdd.selectors.elListItems}`);
1602 const elInputs = elListItems.querySelectorAll('input[type="checkbox"]');
1603 elInputs.forEach(elInputItem => {
1604 const itemSelected = elInputItem.dataset;
1605 const exists = itemsSelectedData.some(item => item.id === itemSelected.id);
1606 elInputItem.checked = exists;
1607 });
1608
1609 // Set item selecting data to dataset for query.
1610 const dataSet = window.lpAJAXG.getDataSetCurrent(elTarget);
1611 dataSet.args.item_selecting = itemsSelectedData;
1612 window.lpAJAXG.setDataSetCurrent(elTarget, dataSet);
1613 };
1614
1615 // Add items selected to section
1616 addItemsSelectedToSection = args => {
1617 const {
1618 e,
1619 target,
1620 callBackHandle
1621 } = args;
1622 if (!elPopup) {
1623 return;
1624 }
1625 sweetalert2__WEBPACK_IMPORTED_MODULE_2___default().close();
1626 if (typeof callBackHandle === 'function') {
1627 callBackHandle(itemsSelectedData);
1628 itemsSelectedData = [];
1629 }
1630 };
1631 }
1632
1633 /***/ },
1634
1635 /***/ "./assets/src/js/lpToastify.js"
1636 /*!*************************************!*\
1637 !*** ./assets/src/js/lpToastify.js ***!
1638 \*************************************/
1639 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1640
1641 "use strict";
1642 __webpack_require__.r(__webpack_exports__);
1643 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1644 /* harmony export */ show: () => (/* binding */ show)
1645 /* harmony export */ });
1646 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! toastify-js */ "./node_modules/toastify-js/src/toastify.js");
1647 /* harmony import */ var toastify_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(toastify_js__WEBPACK_IMPORTED_MODULE_0__);
1648 /* 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");
1649 /**
1650 * Utils functions
1651 *
1652 * @param url
1653 * @param data
1654 * @param functions
1655 * @since 4.3.0
1656 * @version 1.0.0
1657 */
1658
1659
1660 const argsToastify = {
1661 text: '',
1662 gravity: lpData.toast.gravity,
1663 // `top` or `bottom`
1664 position: lpData.toast.position,
1665 // `left`, `center` or `right`
1666 className: `${lpData.toast.classPrefix}`,
1667 close: lpData.toast.close == 1,
1668 stopOnFocus: lpData.toast.stopOnFocus == 1,
1669 duration: lpData.toast.duration
1670 };
1671 const show = (message, status = 'success', argsCustom) => {
1672 let args = argsToastify;
1673 if (argsCustom) {
1674 args = {
1675 ...args,
1676 ...argsCustom
1677 };
1678 }
1679 const toastify = new (toastify_js__WEBPACK_IMPORTED_MODULE_0___default())({
1680 ...args,
1681 text: message,
1682 className: `${lpData.toast.classPrefix} ${status}`
1683 });
1684 toastify.showToast();
1685 };
1686
1687 /***/ },
1688
1689 /***/ "./assets/src/js/utils.js"
1690 /*!********************************!*\
1691 !*** ./assets/src/js/utils.js ***!
1692 \********************************/
1693 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1694
1695 "use strict";
1696 __webpack_require__.r(__webpack_exports__);
1697 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1698 /* harmony export */ debounce: () => (/* binding */ debounce),
1699 /* harmony export */ eventHandlers: () => (/* binding */ eventHandlers),
1700 /* harmony export */ fullScreenView: () => (/* binding */ fullScreenView),
1701 /* harmony export */ getDataOfForm: () => (/* binding */ getDataOfForm),
1702 /* harmony export */ getFieldKeysOfForm: () => (/* binding */ getFieldKeysOfForm),
1703 /* harmony export */ listenElementCreated: () => (/* binding */ listenElementCreated),
1704 /* harmony export */ listenElementViewed: () => (/* binding */ listenElementViewed),
1705 /* harmony export */ lpAddQueryArgs: () => (/* binding */ lpAddQueryArgs),
1706 /* harmony export */ lpAjaxParseJsonOld: () => (/* binding */ lpAjaxParseJsonOld),
1707 /* harmony export */ lpClassName: () => (/* binding */ lpClassName),
1708 /* harmony export */ lpFetchAPI: () => (/* binding */ lpFetchAPI),
1709 /* harmony export */ lpGetCurrentURLNoParam: () => (/* binding */ lpGetCurrentURLNoParam),
1710 /* harmony export */ lpOnElementReady: () => (/* binding */ lpOnElementReady),
1711 /* harmony export */ lpSetLoadingEl: () => (/* binding */ lpSetLoadingEl),
1712 /* harmony export */ lpShowHideEl: () => (/* binding */ lpShowHideEl),
1713 /* harmony export */ mergeDataWithDatForm: () => (/* binding */ mergeDataWithDatForm),
1714 /* harmony export */ toggleCollapse: () => (/* binding */ toggleCollapse),
1715 /* harmony export */ toggleEnable: () => (/* binding */ toggleEnable)
1716 /* harmony export */ });
1717 /**
1718 * Utils functions
1719 *
1720 * @param url
1721 * @param data
1722 * @param functions
1723 * @since 4.2.5.1
1724 * @version 1.0.7
1725 */
1726 const lpClassName = {
1727 hidden: 'lp-hidden',
1728 loading: 'loading',
1729 elCollapse: 'lp-collapse',
1730 elSectionToggle: '.lp-section-toggle',
1731 elTriggerToggle: '.lp-trigger-toggle',
1732 elBtnFullScreen: '.lp-btn-full-screen-view',
1733 elFullScreen: 'lp-full-screen-view',
1734 elBtnFullScreenClose: 'lp-full-screen-view__close'
1735 };
1736 const lpFetchAPI = (url, data = {}, functions = {}) => {
1737 if ('function' === typeof functions.before) {
1738 functions.before();
1739 }
1740 fetch(url, {
1741 method: 'GET',
1742 ...data
1743 }).then(response => response.json()).then(response => {
1744 if ('function' === typeof functions.success) {
1745 functions.success(response);
1746 }
1747 }).catch(err => {
1748 if ('function' === typeof functions.error) {
1749 functions.error(err);
1750 }
1751 }).finally(() => {
1752 if ('function' === typeof functions.completed) {
1753 functions.completed();
1754 }
1755 });
1756 };
1757
1758 /**
1759 * Get current URL without params.
1760 *
1761 * @since 4.2.5.1
1762 */
1763 const lpGetCurrentURLNoParam = () => {
1764 let currentUrl = window.location.href;
1765 const hasParams = currentUrl.includes('?');
1766 if (hasParams) {
1767 currentUrl = currentUrl.split('?')[0];
1768 }
1769 return currentUrl;
1770 };
1771 const lpAddQueryArgs = (endpoint, args) => {
1772 const url = new URL(endpoint);
1773 Object.keys(args).forEach(arg => {
1774 url.searchParams.set(arg, args[arg]);
1775 });
1776 return url;
1777 };
1778
1779 /**
1780 * Listen element viewed.
1781 *
1782 * @param el
1783 * @param callback
1784 * @since 4.2.5.8
1785 */
1786 const listenElementViewed = (el, callback) => {
1787 const observerSeeItem = new IntersectionObserver(function (entries) {
1788 for (const entry of entries) {
1789 if (entry.isIntersecting) {
1790 callback(entry);
1791 }
1792 }
1793 });
1794 observerSeeItem.observe(el);
1795 };
1796
1797 /**
1798 * Listen element created.
1799 *
1800 * @param callback
1801 * @since 4.2.5.8
1802 */
1803 const listenElementCreated = callback => {
1804 const observerCreateItem = new MutationObserver(function (mutations) {
1805 mutations.forEach(function (mutation) {
1806 if (mutation.addedNodes) {
1807 mutation.addedNodes.forEach(function (node) {
1808 if (node.nodeType === 1) {
1809 callback(node);
1810 }
1811 });
1812 }
1813 });
1814 });
1815 observerCreateItem.observe(document, {
1816 childList: true,
1817 subtree: true
1818 });
1819 // End.
1820 };
1821
1822 /**
1823 * Listen element created.
1824 *
1825 * @param selector
1826 * @param callback
1827 * @since 4.2.7.1
1828 */
1829 const lpOnElementReady = (selector, callback) => {
1830 const element = document.querySelector(selector);
1831 if (element) {
1832 callback(element);
1833 return;
1834 }
1835 const observer = new MutationObserver((mutations, obs) => {
1836 const element = document.querySelector(selector);
1837 if (element) {
1838 obs.disconnect();
1839 callback(element);
1840 }
1841 });
1842 observer.observe(document.documentElement, {
1843 childList: true,
1844 subtree: true
1845 });
1846 };
1847
1848 // Parse JSON from string with content include LP_AJAX_START.
1849 const lpAjaxParseJsonOld = data => {
1850 if (typeof data !== 'string') {
1851 return data;
1852 }
1853 const m = String.raw({
1854 raw: data
1855 }).match(/<-- LP_AJAX_START -->(.*)<-- LP_AJAX_END -->/s);
1856 try {
1857 if (m) {
1858 data = JSON.parse(m[1].replace(/(?:\r\n|\r|\n)/g, ''));
1859 } else {
1860 data = JSON.parse(data);
1861 }
1862 } catch (e) {
1863 data = {};
1864 }
1865 return data;
1866 };
1867
1868 // status 0: hide, 1: show
1869 const lpShowHideEl = (el, status = 0) => {
1870 if (!el) {
1871 return;
1872 }
1873 if (!status) {
1874 el.classList.add(lpClassName.hidden);
1875 } else {
1876 el.classList.remove(lpClassName.hidden);
1877 }
1878 };
1879
1880 // status 0: hide, 1: show
1881 const lpSetLoadingEl = (el, status) => {
1882 if (!el) {
1883 return;
1884 }
1885 if (!status) {
1886 el.classList.remove(lpClassName.loading);
1887 } else {
1888 el.classList.add(lpClassName.loading);
1889 }
1890 };
1891
1892 // Toggle collapse section
1893 const toggleCollapse = (e, target, elTriggerClassName = '', elsExclude = [], callback) => {
1894 if (!elTriggerClassName) {
1895 elTriggerClassName = lpClassName.elTriggerToggle;
1896 }
1897
1898 // Exclude elements, which should not trigger the collapse toggle
1899 if (elsExclude && elsExclude.length > 0) {
1900 for (const elExclude of elsExclude) {
1901 if (target.closest(elExclude)) {
1902 return;
1903 }
1904 }
1905 }
1906 const elTrigger = target.closest(elTriggerClassName);
1907 if (!elTrigger) {
1908 return;
1909 }
1910
1911 //console.log( 'elTrigger', elTrigger );
1912
1913 const elSectionToggle = elTrigger.closest(`${lpClassName.elSectionToggle}`);
1914 if (!elSectionToggle) {
1915 return;
1916 }
1917 elSectionToggle.classList.toggle(`${lpClassName.elCollapse}`);
1918 if ('function' === typeof callback) {
1919 callback(elSectionToggle);
1920 }
1921 };
1922
1923 // Get data of form
1924 const getDataOfForm = form => {
1925 const dataSend = {};
1926 const formData = new FormData(form);
1927 for (const pair of formData.entries()) {
1928 const key = pair[0];
1929 const value = formData.getAll(key);
1930 if (!dataSend.hasOwnProperty(key)) {
1931 // Convert value array to string.
1932 dataSend[key] = value.join(',');
1933 }
1934 }
1935 return dataSend;
1936 };
1937
1938 // Get field keys of form
1939 const getFieldKeysOfForm = form => {
1940 const keys = [];
1941 const elements = form.elements;
1942 for (let i = 0; i < elements.length; i++) {
1943 const name = elements[i].name;
1944 if (name && !keys.includes(name)) {
1945 keys.push(name);
1946 }
1947 }
1948 return keys;
1949 };
1950
1951 // Merge data handle with data form.
1952 const mergeDataWithDatForm = (elForm, dataHandle) => {
1953 const dataForm = getDataOfForm(elForm);
1954 const keys = getFieldKeysOfForm(elForm);
1955 keys.forEach(key => {
1956 if (!dataForm.hasOwnProperty(key)) {
1957 delete dataHandle[key];
1958 } else if (dataForm[key][0] === '') {
1959 delete dataForm[key];
1960 delete dataHandle[key];
1961 }
1962 });
1963 dataHandle = {
1964 ...dataHandle,
1965 ...dataForm
1966 };
1967 return dataHandle;
1968 };
1969
1970 /**
1971 * Event trigger
1972 * For each list of event handlers, listen event on document.
1973 *
1974 * eventName: 'click', 'change', ...
1975 * eventHandlers = [ { selector: '.lp-button', callBack: function(){}, class: object } ]
1976 *
1977 * @param eventName
1978 * @param eventHandlers
1979 */
1980 const eventHandlers = (eventName, eventHandlers) => {
1981 document.addEventListener(eventName, e => {
1982 const target = e.target;
1983 let args = {
1984 e,
1985 target
1986 };
1987 eventHandlers.forEach(eventHandler => {
1988 args = {
1989 ...args,
1990 ...eventHandler
1991 };
1992
1993 //console.log( args );
1994
1995 // Check condition before call back
1996 if (eventHandler.conditionBeforeCallBack) {
1997 if (eventHandler.conditionBeforeCallBack(args) !== true) {
1998 return;
1999 }
2000 }
2001
2002 // Special check for keydown event with checkIsEventEnter = true
2003 if (eventName === 'keydown' && eventHandler.checkIsEventEnter) {
2004 if (e.key !== 'Enter') {
2005 return;
2006 }
2007 }
2008 if (target.closest(eventHandler.selector)) {
2009 if (eventHandler.class) {
2010 // Call method of class, function callBack will understand exactly {this} is class object.
2011 eventHandler.class[eventHandler.callBack](args);
2012 } else {
2013 // For send args is objected, {this} is eventHandler object, not class object.
2014 eventHandler.callBack(args);
2015 }
2016 }
2017 });
2018 });
2019 };
2020
2021 /**
2022 * Debounce - delays function execution until after `wait` ms of inactivity.
2023 *
2024 * Each call resets the timer. Only the last call in a burst executes.
2025 *
2026 * USE CASES:
2027 * - Search inputs, form validation, window resize
2028 * - Multiple elements need independent timers
2029 * - When you need to call with different arguments
2030 *
2031 * EXAMPLES:
2032 * const debouncedSearch = debounce( (query) => fetchResults(query), 300 );
2033 * searchInput.addEventListener('input', (e) => debouncedSearch(e.target.value));
2034 *
2035 * const debouncedResize = debounce( recalculateLayout, 250 );
2036 * window.addEventListener('resize', debouncedResize);
2037 *
2038 * ⚠️ Create ONCE outside event handlers, not inside.
2039 *
2040 * @param {Function} func - Function to debounce (can be anonymous)
2041 * @param {number} wait - Milliseconds to wait (default: 500)
2042 * @return {Function} Debounced wrapper function
2043 * @since 4.3.7
2044 * @version 1.0.0
2045 */
2046 const debounce = (func, wait = 500) => {
2047 let timer;
2048 return args => {
2049 clearTimeout(timer);
2050 timer = setTimeout(() => func(args), wait);
2051 };
2052 };
2053
2054 /**
2055 * Initialize lp-toggle-enable components.
2056 *
2057 * Finds all `.lp-toggle-enable` elements and wires up toggle behavior.
2058 * Reads initial state from `data-enabled` attribute ("true"/"false").
2059 * Calls `data-on-toggle` callback (if provided via options) on state change.
2060 *
2061 * HTML structure:
2062 * <label class="lp-toggle-enable" data-enabled="true">
2063 * <input type="checkbox" class="lp-toggle-enable__input" />
2064 * <span class="lp-toggle-enable__track"></span>
2065 * </label>
2066 *
2067 * @param {string} selector CSS selector for toggle elements (default: '.lp-toggle-enable')
2068 * @param {Function} onToggle Optional callback( el, isEnabled ) called on state change
2069 * @since 4.4.5
2070 * @version 1.0.0
2071 */
2072 window.lpToggleEnableInit = 0;
2073 const toggleEnable = (onToggle = null) => {
2074 if (window.lpToggleEnableInit) {
2075 return;
2076 }
2077 window.lpToggleEnableInit = 1;
2078 const selector = '.lp-toggle-enable';
2079 const updateUI = (toggle, isEnabled) => {
2080 toggle.classList.toggle('is-enabled', isEnabled);
2081 const input = toggle.querySelector('.lp-toggle-enable__input');
2082 if (input) {
2083 input.checked = isEnabled;
2084 input.value = isEnabled ? '1' : '0';
2085 }
2086 };
2087
2088 // Delegate click handling via eventHandlers.
2089 eventHandlers('click', [{
2090 selector,
2091 callBack: args => {
2092 const {
2093 e,
2094 target
2095 } = args;
2096 const toggle = target.closest(selector);
2097 if (!toggle || toggle.classList.contains('is-disabled')) {
2098 return;
2099 }
2100 e.preventDefault();
2101 const isEnabled = !toggle.classList.contains('is-enabled');
2102 updateUI(toggle, isEnabled);
2103 if ('function' === typeof onToggle) {
2104 onToggle(toggle, isEnabled);
2105 }
2106 }
2107 }]);
2108 };
2109
2110 /**
2111 * Initialize custom fullscreen view buttons.
2112 *
2113 * Delegates clicks on `.lp-btn-full-screen-view` buttons to
2114 * `lpToggleFullscreenView`. Reads the `data-target` attribute to find the
2115 * target element. Falls back to the button's parent element when
2116 * `data-target` is not provided.
2117 *
2118 * @since 4.4.5
2119 * @version 1.0.0
2120 */
2121 window.lpFullScreenViewInit = 0;
2122 const fullScreenView = () => {
2123 if (window.lpFullScreenViewInit) {
2124 return;
2125 }
2126 window.lpFullScreenViewInit = 1;
2127 let lastScrollY = 0;
2128 const lpToggleFullscreenView = (elTarget, elBtnFullScreen = null) => {
2129 const isFullscreen = elTarget.classList.contains(lpClassName.elFullScreen);
2130 if (isFullscreen) {
2131 elTarget.classList.remove(lpClassName.elFullScreen);
2132 document.documentElement.classList.remove('lp-full-screen-active');
2133 window.scrollTo(0, lastScrollY);
2134 } else {
2135 lastScrollY = window.scrollY;
2136 elTarget.classList.add(lpClassName.elFullScreen);
2137 document.documentElement.classList.add('lp-full-screen-active');
2138 }
2139 if (!isFullscreen) {
2140 if (!elTarget.querySelector(`.${lpClassName.elBtnFullScreenClose}`)) {
2141 const closeButton = document.createElement('button');
2142 closeButton.type = 'button';
2143 closeButton.className = lpClassName.elBtnFullScreenClose;
2144 closeButton.setAttribute('aria-label', 'Close');
2145 closeButton.innerHTML = lpData.i18n.closeButtonFullScreen || 'Close &times;';
2146 closeButton.addEventListener('click', e => {
2147 e.preventDefault();
2148 lpToggleFullscreenView(elTarget);
2149 });
2150 elTarget.appendChild(closeButton);
2151 }
2152 } else {
2153 const closeButton = elTarget.querySelector(`.${lpClassName.elBtnFullScreenClose}`);
2154 if (closeButton) {
2155 closeButton.remove();
2156 }
2157 }
2158 };
2159 eventHandlers('click', [{
2160 selector: lpClassName.elBtnFullScreen,
2161 callBack: args => {
2162 const {
2163 e,
2164 target
2165 } = args;
2166 const elBtnFullScreen = target.closest(lpClassName.elBtnFullScreen);
2167 if (!elBtnFullScreen) {
2168 console.log('No full screen button found');
2169 return;
2170 }
2171 e.preventDefault();
2172 let elTarget = null;
2173 const targetSelector = elBtnFullScreen.dataset.targetFullscreen;
2174 console.log(targetSelector);
2175 if (targetSelector) {
2176 elTarget = document.querySelector(targetSelector);
2177 }
2178 if (!elTarget) {
2179 console.log('No target element found');
2180 return;
2181 }
2182 lpToggleFullscreenView(elTarget, elBtnFullScreen);
2183 }
2184 }]);
2185 };
2186
2187 /***/ },
2188
2189 /***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/toastify-js/src/toastify.css"
2190 /*!*****************************************************************************************!*\
2191 !*** ./node_modules/css-loader/dist/cjs.js!./node_modules/toastify-js/src/toastify.css ***!
2192 \*****************************************************************************************/
2193 (module, __webpack_exports__, __webpack_require__) {
2194
2195 "use strict";
2196 __webpack_require__.r(__webpack_exports__);
2197 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2198 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
2199 /* harmony export */ });
2200 /* 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");
2201 /* 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__);
2202 /* 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");
2203 /* 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__);
2204 // Imports
2205
2206
2207 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()));
2208 // Module
2209 ___CSS_LOADER_EXPORT___.push([module.id, `/*!
2210 * Toastify js 1.12.0
2211 * https://github.com/apvarun/toastify-js
2212 * @license MIT licensed
2213 *
2214 * Copyright (C) 2018 Varun A P
2215 */
2216
2217 .toastify {
2218 padding: 12px 20px;
2219 color: #ffffff;
2220 display: inline-block;
2221 box-shadow: 0 3px 6px -1px rgba(0, 0, 0, 0.12), 0 10px 36px -4px rgba(77, 96, 232, 0.3);
2222 background: -webkit-linear-gradient(315deg, #73a5ff, #5477f5);
2223 background: linear-gradient(135deg, #73a5ff, #5477f5);
2224 position: fixed;
2225 opacity: 0;
2226 transition: all 0.4s cubic-bezier(0.215, 0.61, 0.355, 1);
2227 border-radius: 2px;
2228 cursor: pointer;
2229 text-decoration: none;
2230 max-width: calc(50% - 20px);
2231 z-index: 2147483647;
2232 }
2233
2234 .toastify.on {
2235 opacity: 1;
2236 }
2237
2238 .toast-close {
2239 background: transparent;
2240 border: 0;
2241 color: white;
2242 cursor: pointer;
2243 font-family: inherit;
2244 font-size: 1em;
2245 opacity: 0.4;
2246 padding: 0 5px;
2247 }
2248
2249 .toastify-right {
2250 right: 15px;
2251 }
2252
2253 .toastify-left {
2254 left: 15px;
2255 }
2256
2257 .toastify-top {
2258 top: -150px;
2259 }
2260
2261 .toastify-bottom {
2262 bottom: -150px;
2263 }
2264
2265 .toastify-rounded {
2266 border-radius: 25px;
2267 }
2268
2269 .toastify-avatar {
2270 width: 1.5em;
2271 height: 1.5em;
2272 margin: -7px 5px;
2273 border-radius: 2px;
2274 }
2275
2276 .toastify-center {
2277 margin-left: auto;
2278 margin-right: auto;
2279 left: 0;
2280 right: 0;
2281 max-width: fit-content;
2282 max-width: -moz-fit-content;
2283 }
2284
2285 @media only screen and (max-width: 360px) {
2286 .toastify-right, .toastify-left {
2287 margin-left: auto;
2288 margin-right: auto;
2289 left: 0;
2290 right: 0;
2291 max-width: fit-content;
2292 }
2293 }
2294 `, "",{"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":""}]);
2295 // Exports
2296 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);
2297
2298
2299 /***/ },
2300
2301 /***/ "./node_modules/css-loader/dist/runtime/api.js"
2302 /*!*****************************************************!*\
2303 !*** ./node_modules/css-loader/dist/runtime/api.js ***!
2304 \*****************************************************/
2305 (module) {
2306
2307 "use strict";
2308
2309
2310 /*
2311 MIT License http://www.opensource.org/licenses/mit-license.php
2312 Author Tobias Koppers @sokra
2313 */
2314 module.exports = function (cssWithMappingToString) {
2315 var list = [];
2316
2317 // return the list of modules as css string
2318 list.toString = function toString() {
2319 return this.map(function (item) {
2320 var content = "";
2321 var needLayer = typeof item[5] !== "undefined";
2322 if (item[4]) {
2323 content += "@supports (".concat(item[4], ") {");
2324 }
2325 if (item[2]) {
2326 content += "@media ".concat(item[2], " {");
2327 }
2328 if (needLayer) {
2329 content += "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {");
2330 }
2331 content += cssWithMappingToString(item);
2332 if (needLayer) {
2333 content += "}";
2334 }
2335 if (item[2]) {
2336 content += "}";
2337 }
2338 if (item[4]) {
2339 content += "}";
2340 }
2341 return content;
2342 }).join("");
2343 };
2344
2345 // import a list of modules into the list
2346 list.i = function i(modules, media, dedupe, supports, layer) {
2347 if (typeof modules === "string") {
2348 modules = [[null, modules, undefined]];
2349 }
2350 var alreadyImportedModules = {};
2351 if (dedupe) {
2352 for (var k = 0; k < this.length; k++) {
2353 var id = this[k][0];
2354 if (id != null) {
2355 alreadyImportedModules[id] = true;
2356 }
2357 }
2358 }
2359 for (var _k = 0; _k < modules.length; _k++) {
2360 var item = [].concat(modules[_k]);
2361 if (dedupe && alreadyImportedModules[item[0]]) {
2362 continue;
2363 }
2364 if (typeof layer !== "undefined") {
2365 if (typeof item[5] === "undefined") {
2366 item[5] = layer;
2367 } else {
2368 item[1] = "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {").concat(item[1], "}");
2369 item[5] = layer;
2370 }
2371 }
2372 if (media) {
2373 if (!item[2]) {
2374 item[2] = media;
2375 } else {
2376 item[1] = "@media ".concat(item[2], " {").concat(item[1], "}");
2377 item[2] = media;
2378 }
2379 }
2380 if (supports) {
2381 if (!item[4]) {
2382 item[4] = "".concat(supports);
2383 } else {
2384 item[1] = "@supports (".concat(item[4], ") {").concat(item[1], "}");
2385 item[4] = supports;
2386 }
2387 }
2388 list.push(item);
2389 }
2390 };
2391 return list;
2392 };
2393
2394 /***/ },
2395
2396 /***/ "./node_modules/css-loader/dist/runtime/sourceMaps.js"
2397 /*!************************************************************!*\
2398 !*** ./node_modules/css-loader/dist/runtime/sourceMaps.js ***!
2399 \************************************************************/
2400 (module) {
2401
2402 "use strict";
2403
2404
2405 module.exports = function (item) {
2406 var content = item[1];
2407 var cssMapping = item[3];
2408 if (!cssMapping) {
2409 return content;
2410 }
2411 if (typeof btoa === "function") {
2412 var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping))));
2413 var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
2414 var sourceMapping = "/*# ".concat(data, " */");
2415 return [content].concat([sourceMapping]).join("\n");
2416 }
2417 return [content].join("\n");
2418 };
2419
2420 /***/ },
2421
2422 /***/ "./node_modules/sortablejs/modular/sortable.esm.js"
2423 /*!*********************************************************!*\
2424 !*** ./node_modules/sortablejs/modular/sortable.esm.js ***!
2425 \*********************************************************/
2426 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
2427
2428 "use strict";
2429 __webpack_require__.r(__webpack_exports__);
2430 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2431 /* harmony export */ MultiDrag: () => (/* binding */ MultiDragPlugin),
2432 /* harmony export */ Sortable: () => (/* binding */ Sortable),
2433 /* harmony export */ Swap: () => (/* binding */ SwapPlugin),
2434 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
2435 /* harmony export */ });
2436 /**!
2437 * Sortable 1.15.7
2438 * @author RubaXa <trash@rubaxa.org>
2439 * @author owenm <owen23355@gmail.com>
2440 * @license MIT
2441 */
2442 function _arrayLikeToArray(r, a) {
2443 (null == a || a > r.length) && (a = r.length);
2444 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
2445 return n;
2446 }
2447 function _arrayWithoutHoles(r) {
2448 if (Array.isArray(r)) return _arrayLikeToArray(r);
2449 }
2450 function _defineProperty(e, r, t) {
2451 return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
2452 value: t,
2453 enumerable: !0,
2454 configurable: !0,
2455 writable: !0
2456 }) : e[r] = t, e;
2457 }
2458 function _extends() {
2459 return _extends = Object.assign ? Object.assign.bind() : function (n) {
2460 for (var e = 1; e < arguments.length; e++) {
2461 var t = arguments[e];
2462 for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
2463 }
2464 return n;
2465 }, _extends.apply(null, arguments);
2466 }
2467 function _iterableToArray(r) {
2468 if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
2469 }
2470 function _nonIterableSpread() {
2471 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2472 }
2473 function ownKeys(e, r) {
2474 var t = Object.keys(e);
2475 if (Object.getOwnPropertySymbols) {
2476 var o = Object.getOwnPropertySymbols(e);
2477 r && (o = o.filter(function (r) {
2478 return Object.getOwnPropertyDescriptor(e, r).enumerable;
2479 })), t.push.apply(t, o);
2480 }
2481 return t;
2482 }
2483 function _objectSpread2(e) {
2484 for (var r = 1; r < arguments.length; r++) {
2485 var t = null != arguments[r] ? arguments[r] : {};
2486 r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
2487 _defineProperty(e, r, t[r]);
2488 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
2489 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
2490 });
2491 }
2492 return e;
2493 }
2494 function _objectWithoutProperties(e, t) {
2495 if (null == e) return {};
2496 var o,
2497 r,
2498 i = _objectWithoutPropertiesLoose(e, t);
2499 if (Object.getOwnPropertySymbols) {
2500 var n = Object.getOwnPropertySymbols(e);
2501 for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
2502 }
2503 return i;
2504 }
2505 function _objectWithoutPropertiesLoose(r, e) {
2506 if (null == r) return {};
2507 var t = {};
2508 for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
2509 if (-1 !== e.indexOf(n)) continue;
2510 t[n] = r[n];
2511 }
2512 return t;
2513 }
2514 function _toConsumableArray(r) {
2515 return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
2516 }
2517 function _toPrimitive(t, r) {
2518 if ("object" != typeof t || !t) return t;
2519 var e = t[Symbol.toPrimitive];
2520 if (void 0 !== e) {
2521 var i = e.call(t, r || "default");
2522 if ("object" != typeof i) return i;
2523 throw new TypeError("@@toPrimitive must return a primitive value.");
2524 }
2525 return ("string" === r ? String : Number)(t);
2526 }
2527 function _toPropertyKey(t) {
2528 var i = _toPrimitive(t, "string");
2529 return "symbol" == typeof i ? i : i + "";
2530 }
2531 function _typeof(o) {
2532 "@babel/helpers - typeof";
2533
2534 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
2535 return typeof o;
2536 } : function (o) {
2537 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
2538 }, _typeof(o);
2539 }
2540 function _unsupportedIterableToArray(r, a) {
2541 if (r) {
2542 if ("string" == typeof r) return _arrayLikeToArray(r, a);
2543 var t = {}.toString.call(r).slice(8, -1);
2544 return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
2545 }
2546 }
2547
2548 var version = "1.15.7";
2549
2550 function userAgent(pattern) {
2551 if (typeof window !== 'undefined' && window.navigator) {
2552 return !! /*@__PURE__*/navigator.userAgent.match(pattern);
2553 }
2554 }
2555 var IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i);
2556 var Edge = userAgent(/Edge/i);
2557 var FireFox = userAgent(/firefox/i);
2558 var Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);
2559 var IOS = userAgent(/iP(ad|od|hone)/i);
2560 var ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);
2561
2562 var captureMode = {
2563 capture: false,
2564 passive: false
2565 };
2566 function on(el, event, fn) {
2567 el.addEventListener(event, fn, !IE11OrLess && captureMode);
2568 }
2569 function off(el, event, fn) {
2570 el.removeEventListener(event, fn, !IE11OrLess && captureMode);
2571 }
2572 function matches( /**HTMLElement*/el, /**String*/selector) {
2573 if (!selector) return;
2574 selector[0] === '>' && (selector = selector.substring(1));
2575 if (el) {
2576 try {
2577 if (el.matches) {
2578 return el.matches(selector);
2579 } else if (el.msMatchesSelector) {
2580 return el.msMatchesSelector(selector);
2581 } else if (el.webkitMatchesSelector) {
2582 return el.webkitMatchesSelector(selector);
2583 }
2584 } catch (_) {
2585 return false;
2586 }
2587 }
2588 return false;
2589 }
2590 function getParentOrHost(el) {
2591 return el.host && el !== document && el.host.nodeType && el.host !== el ? el.host : el.parentNode;
2592 }
2593 function closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) {
2594 if (el) {
2595 ctx = ctx || document;
2596 do {
2597 if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {
2598 return el;
2599 }
2600 if (el === ctx) break;
2601 /* jshint boss:true */
2602 } while (el = getParentOrHost(el));
2603 }
2604 return null;
2605 }
2606 var R_SPACE = /\s+/g;
2607 function toggleClass(el, name, state) {
2608 if (el && name) {
2609 if (el.classList) {
2610 el.classList[state ? 'add' : 'remove'](name);
2611 } else {
2612 var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
2613 el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
2614 }
2615 }
2616 }
2617 function css(el, prop, val) {
2618 var style = el && el.style;
2619 if (style) {
2620 if (val === void 0) {
2621 if (document.defaultView && document.defaultView.getComputedStyle) {
2622 val = document.defaultView.getComputedStyle(el, '');
2623 } else if (el.currentStyle) {
2624 val = el.currentStyle;
2625 }
2626 return prop === void 0 ? val : val[prop];
2627 } else {
2628 if (!(prop in style) && prop.indexOf('webkit') === -1) {
2629 prop = '-webkit-' + prop;
2630 }
2631 style[prop] = val + (typeof val === 'string' ? '' : 'px');
2632 }
2633 }
2634 }
2635 function matrix(el, selfOnly) {
2636 var appliedTransforms = '';
2637 if (typeof el === 'string') {
2638 appliedTransforms = el;
2639 } else {
2640 do {
2641 var transform = css(el, 'transform');
2642 if (transform && transform !== 'none') {
2643 appliedTransforms = transform + ' ' + appliedTransforms;
2644 }
2645 /* jshint boss:true */
2646 } while (!selfOnly && (el = el.parentNode));
2647 }
2648 var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix;
2649 /*jshint -W056 */
2650 return matrixFn && new matrixFn(appliedTransforms);
2651 }
2652 function find(ctx, tagName, iterator) {
2653 if (ctx) {
2654 var list = ctx.getElementsByTagName(tagName),
2655 i = 0,
2656 n = list.length;
2657 if (iterator) {
2658 for (; i < n; i++) {
2659 iterator(list[i], i);
2660 }
2661 }
2662 return list;
2663 }
2664 return [];
2665 }
2666 function getWindowScrollingElement() {
2667 var scrollingElement = document.scrollingElement;
2668 if (scrollingElement) {
2669 return scrollingElement;
2670 } else {
2671 return document.documentElement;
2672 }
2673 }
2674
2675 /**
2676 * Returns the "bounding client rect" of given element
2677 * @param {HTMLElement} el The element whose boundingClientRect is wanted
2678 * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container
2679 * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr
2680 * @param {[Boolean]} undoScale Whether the container's scale() should be undone
2681 * @param {[HTMLElement]} container The parent the element will be placed in
2682 * @return {Object} The boundingClientRect of el, with specified adjustments
2683 */
2684 function getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {
2685 if (!el.getBoundingClientRect && el !== window) return;
2686 var elRect, top, left, bottom, right, height, width;
2687 if (el !== window && el.parentNode && el !== getWindowScrollingElement()) {
2688 elRect = el.getBoundingClientRect();
2689 top = elRect.top;
2690 left = elRect.left;
2691 bottom = elRect.bottom;
2692 right = elRect.right;
2693 height = elRect.height;
2694 width = elRect.width;
2695 } else {
2696 top = 0;
2697 left = 0;
2698 bottom = window.innerHeight;
2699 right = window.innerWidth;
2700 height = window.innerHeight;
2701 width = window.innerWidth;
2702 }
2703 if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {
2704 // Adjust for translate()
2705 container = container || el.parentNode;
2706
2707 // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)
2708 // Not needed on <= IE11
2709 if (!IE11OrLess) {
2710 do {
2711 if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {
2712 var containerRect = container.getBoundingClientRect();
2713
2714 // Set relative to edges of padding box of container
2715 top -= containerRect.top + parseInt(css(container, 'border-top-width'));
2716 left -= containerRect.left + parseInt(css(container, 'border-left-width'));
2717 bottom = top + elRect.height;
2718 right = left + elRect.width;
2719 break;
2720 }
2721 /* jshint boss:true */
2722 } while (container = container.parentNode);
2723 }
2724 }
2725 if (undoScale && el !== window) {
2726 // Adjust for scale()
2727 var elMatrix = matrix(container || el),
2728 scaleX = elMatrix && elMatrix.a,
2729 scaleY = elMatrix && elMatrix.d;
2730 if (elMatrix) {
2731 top /= scaleY;
2732 left /= scaleX;
2733 width /= scaleX;
2734 height /= scaleY;
2735 bottom = top + height;
2736 right = left + width;
2737 }
2738 }
2739 return {
2740 top: top,
2741 left: left,
2742 bottom: bottom,
2743 right: right,
2744 width: width,
2745 height: height
2746 };
2747 }
2748
2749 /**
2750 * Checks if a side of an element is scrolled past a side of its parents
2751 * @param {HTMLElement} el The element who's side being scrolled out of view is in question
2752 * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom')
2753 * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom')
2754 * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element
2755 */
2756 function isScrolledPast(el, elSide, parentSide) {
2757 var parent = getParentAutoScrollElement(el, true),
2758 elSideVal = getRect(el)[elSide];
2759
2760 /* jshint boss:true */
2761 while (parent) {
2762 var parentSideVal = getRect(parent)[parentSide],
2763 visible = void 0;
2764 if (parentSide === 'top' || parentSide === 'left') {
2765 visible = elSideVal >= parentSideVal;
2766 } else {
2767 visible = elSideVal <= parentSideVal;
2768 }
2769 if (!visible) return parent;
2770 if (parent === getWindowScrollingElement()) break;
2771 parent = getParentAutoScrollElement(parent, false);
2772 }
2773 return false;
2774 }
2775
2776 /**
2777 * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)
2778 * and non-draggable elements
2779 * @param {HTMLElement} el The parent element
2780 * @param {Number} childNum The index of the child
2781 * @param {Object} options Parent Sortable's options
2782 * @return {HTMLElement} The child at index childNum, or null if not found
2783 */
2784 function getChild(el, childNum, options, includeDragEl) {
2785 var currentChild = 0,
2786 i = 0,
2787 children = el.children;
2788 while (i < children.length) {
2789 if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) {
2790 if (currentChild === childNum) {
2791 return children[i];
2792 }
2793 currentChild++;
2794 }
2795 i++;
2796 }
2797 return null;
2798 }
2799
2800 /**
2801 * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)
2802 * @param {HTMLElement} el Parent element
2803 * @param {selector} selector Any other elements that should be ignored
2804 * @return {HTMLElement} The last child, ignoring ghostEl
2805 */
2806 function lastChild(el, selector) {
2807 var last = el.lastElementChild;
2808 while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {
2809 last = last.previousElementSibling;
2810 }
2811 return last || null;
2812 }
2813
2814 /**
2815 * Returns the index of an element within its parent for a selected set of
2816 * elements
2817 * @param {HTMLElement} el
2818 * @param {selector} selector
2819 * @return {number}
2820 */
2821 function index(el, selector) {
2822 var index = 0;
2823 if (!el || !el.parentNode) {
2824 return -1;
2825 }
2826
2827 /* jshint boss:true */
2828 while (el = el.previousElementSibling) {
2829 if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {
2830 index++;
2831 }
2832 }
2833 return index;
2834 }
2835
2836 /**
2837 * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.
2838 * The value is returned in real pixels.
2839 * @param {HTMLElement} el
2840 * @return {Array} Offsets in the format of [left, top]
2841 */
2842 function getRelativeScrollOffset(el) {
2843 var offsetLeft = 0,
2844 offsetTop = 0,
2845 winScroller = getWindowScrollingElement();
2846 if (el) {
2847 do {
2848 var elMatrix = matrix(el),
2849 scaleX = elMatrix.a,
2850 scaleY = elMatrix.d;
2851 offsetLeft += el.scrollLeft * scaleX;
2852 offsetTop += el.scrollTop * scaleY;
2853 } while (el !== winScroller && (el = el.parentNode));
2854 }
2855 return [offsetLeft, offsetTop];
2856 }
2857
2858 /**
2859 * Returns the index of the object within the given array
2860 * @param {Array} arr Array that may or may not hold the object
2861 * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find
2862 * @return {Number} The index of the object in the array, or -1
2863 */
2864 function indexOfObject(arr, obj) {
2865 for (var i in arr) {
2866 if (!arr.hasOwnProperty(i)) continue;
2867 for (var key in obj) {
2868 if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);
2869 }
2870 }
2871 return -1;
2872 }
2873 function getParentAutoScrollElement(el, includeSelf) {
2874 // skip to window
2875 if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();
2876 var elem = el;
2877 var gotSelf = false;
2878 do {
2879 // we don't need to get elem css if it isn't even overflowing in the first place (performance)
2880 if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {
2881 var elemCSS = css(elem);
2882 if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {
2883 if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();
2884 if (gotSelf || includeSelf) return elem;
2885 gotSelf = true;
2886 }
2887 }
2888 /* jshint boss:true */
2889 } while (elem = elem.parentNode);
2890 return getWindowScrollingElement();
2891 }
2892 function extend(dst, src) {
2893 if (dst && src) {
2894 for (var key in src) {
2895 if (src.hasOwnProperty(key)) {
2896 dst[key] = src[key];
2897 }
2898 }
2899 }
2900 return dst;
2901 }
2902 function isRectEqual(rect1, rect2) {
2903 return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);
2904 }
2905 var _throttleTimeout;
2906 function throttle(callback, ms) {
2907 return function () {
2908 if (!_throttleTimeout) {
2909 var args = arguments,
2910 _this = this;
2911 if (args.length === 1) {
2912 callback.call(_this, args[0]);
2913 } else {
2914 callback.apply(_this, args);
2915 }
2916 _throttleTimeout = setTimeout(function () {
2917 _throttleTimeout = void 0;
2918 }, ms);
2919 }
2920 };
2921 }
2922 function cancelThrottle() {
2923 clearTimeout(_throttleTimeout);
2924 _throttleTimeout = void 0;
2925 }
2926 function scrollBy(el, x, y) {
2927 el.scrollLeft += x;
2928 el.scrollTop += y;
2929 }
2930 function clone(el) {
2931 var Polymer = window.Polymer;
2932 var $ = window.jQuery || window.Zepto;
2933 if (Polymer && Polymer.dom) {
2934 return Polymer.dom(el).cloneNode(true);
2935 } else if ($) {
2936 return $(el).clone(true)[0];
2937 } else {
2938 return el.cloneNode(true);
2939 }
2940 }
2941 function setRect(el, rect) {
2942 css(el, 'position', 'absolute');
2943 css(el, 'top', rect.top);
2944 css(el, 'left', rect.left);
2945 css(el, 'width', rect.width);
2946 css(el, 'height', rect.height);
2947 }
2948 function unsetRect(el) {
2949 css(el, 'position', '');
2950 css(el, 'top', '');
2951 css(el, 'left', '');
2952 css(el, 'width', '');
2953 css(el, 'height', '');
2954 }
2955 function getChildContainingRectFromElement(container, options, ghostEl) {
2956 var rect = {};
2957 Array.from(container.children).forEach(function (child) {
2958 var _rect$left, _rect$top, _rect$right, _rect$bottom;
2959 if (!closest(child, options.draggable, container, false) || child.animated || child === ghostEl) return;
2960 var childRect = getRect(child);
2961 rect.left = Math.min((_rect$left = rect.left) !== null && _rect$left !== void 0 ? _rect$left : Infinity, childRect.left);
2962 rect.top = Math.min((_rect$top = rect.top) !== null && _rect$top !== void 0 ? _rect$top : Infinity, childRect.top);
2963 rect.right = Math.max((_rect$right = rect.right) !== null && _rect$right !== void 0 ? _rect$right : -Infinity, childRect.right);
2964 rect.bottom = Math.max((_rect$bottom = rect.bottom) !== null && _rect$bottom !== void 0 ? _rect$bottom : -Infinity, childRect.bottom);
2965 });
2966 rect.width = rect.right - rect.left;
2967 rect.height = rect.bottom - rect.top;
2968 rect.x = rect.left;
2969 rect.y = rect.top;
2970 return rect;
2971 }
2972 var expando = 'Sortable' + new Date().getTime();
2973
2974 function AnimationStateManager() {
2975 var animationStates = [],
2976 animationCallbackId;
2977 return {
2978 captureAnimationState: function captureAnimationState() {
2979 animationStates = [];
2980 if (!this.options.animation) return;
2981 var children = [].slice.call(this.el.children);
2982 children.forEach(function (child) {
2983 if (css(child, 'display') === 'none' || child === Sortable.ghost) return;
2984 animationStates.push({
2985 target: child,
2986 rect: getRect(child)
2987 });
2988 var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect);
2989
2990 // If animating: compensate for current animation
2991 if (child.thisAnimationDuration) {
2992 var childMatrix = matrix(child, true);
2993 if (childMatrix) {
2994 fromRect.top -= childMatrix.f;
2995 fromRect.left -= childMatrix.e;
2996 }
2997 }
2998 child.fromRect = fromRect;
2999 });
3000 },
3001 addAnimationState: function addAnimationState(state) {
3002 animationStates.push(state);
3003 },
3004 removeAnimationState: function removeAnimationState(target) {
3005 animationStates.splice(indexOfObject(animationStates, {
3006 target: target
3007 }), 1);
3008 },
3009 animateAll: function animateAll(callback) {
3010 var _this = this;
3011 if (!this.options.animation) {
3012 clearTimeout(animationCallbackId);
3013 if (typeof callback === 'function') callback();
3014 return;
3015 }
3016 var animating = false,
3017 animationTime = 0;
3018 animationStates.forEach(function (state) {
3019 var time = 0,
3020 target = state.target,
3021 fromRect = target.fromRect,
3022 toRect = getRect(target),
3023 prevFromRect = target.prevFromRect,
3024 prevToRect = target.prevToRect,
3025 animatingRect = state.rect,
3026 targetMatrix = matrix(target, true);
3027 if (targetMatrix) {
3028 // Compensate for current animation
3029 toRect.top -= targetMatrix.f;
3030 toRect.left -= targetMatrix.e;
3031 }
3032 target.toRect = toRect;
3033 if (target.thisAnimationDuration) {
3034 // Could also check if animatingRect is between fromRect and toRect
3035 if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) &&
3036 // Make sure animatingRect is on line between toRect & fromRect
3037 (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {
3038 // If returning to same place as started from animation and on same axis
3039 time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);
3040 }
3041 }
3042
3043 // if fromRect != toRect: animate
3044 if (!isRectEqual(toRect, fromRect)) {
3045 target.prevFromRect = fromRect;
3046 target.prevToRect = toRect;
3047 if (!time) {
3048 time = _this.options.animation;
3049 }
3050 _this.animate(target, animatingRect, toRect, time);
3051 }
3052 if (time) {
3053 animating = true;
3054 animationTime = Math.max(animationTime, time);
3055 clearTimeout(target.animationResetTimer);
3056 target.animationResetTimer = setTimeout(function () {
3057 target.animationTime = 0;
3058 target.prevFromRect = null;
3059 target.fromRect = null;
3060 target.prevToRect = null;
3061 target.thisAnimationDuration = null;
3062 }, time);
3063 target.thisAnimationDuration = time;
3064 }
3065 });
3066 clearTimeout(animationCallbackId);
3067 if (!animating) {
3068 if (typeof callback === 'function') callback();
3069 } else {
3070 animationCallbackId = setTimeout(function () {
3071 if (typeof callback === 'function') callback();
3072 }, animationTime);
3073 }
3074 animationStates = [];
3075 },
3076 animate: function animate(target, currentRect, toRect, duration) {
3077 if (duration) {
3078 css(target, 'transition', '');
3079 css(target, 'transform', '');
3080 var elMatrix = matrix(this.el),
3081 scaleX = elMatrix && elMatrix.a,
3082 scaleY = elMatrix && elMatrix.d,
3083 translateX = (currentRect.left - toRect.left) / (scaleX || 1),
3084 translateY = (currentRect.top - toRect.top) / (scaleY || 1);
3085 target.animatingX = !!translateX;
3086 target.animatingY = !!translateY;
3087 css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');
3088 this.forRepaintDummy = repaint(target); // repaint
3089
3090 css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));
3091 css(target, 'transform', 'translate3d(0,0,0)');
3092 typeof target.animated === 'number' && clearTimeout(target.animated);
3093 target.animated = setTimeout(function () {
3094 css(target, 'transition', '');
3095 css(target, 'transform', '');
3096 target.animated = false;
3097 target.animatingX = false;
3098 target.animatingY = false;
3099 }, duration);
3100 }
3101 }
3102 };
3103 }
3104 function repaint(target) {
3105 return target.offsetWidth;
3106 }
3107 function calculateRealTime(animatingRect, fromRect, toRect, options) {
3108 return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;
3109 }
3110
3111 var plugins = [];
3112 var defaults = {
3113 initializeByDefault: true
3114 };
3115 var PluginManager = {
3116 mount: function mount(plugin) {
3117 // Set default static properties
3118 for (var option in defaults) {
3119 if (defaults.hasOwnProperty(option) && !(option in plugin)) {
3120 plugin[option] = defaults[option];
3121 }
3122 }
3123 plugins.forEach(function (p) {
3124 if (p.pluginName === plugin.pluginName) {
3125 throw "Sortable: Cannot mount plugin ".concat(plugin.pluginName, " more than once");
3126 }
3127 });
3128 plugins.push(plugin);
3129 },
3130 pluginEvent: function pluginEvent(eventName, sortable, evt) {
3131 var _this = this;
3132 this.eventCanceled = false;
3133 evt.cancel = function () {
3134 _this.eventCanceled = true;
3135 };
3136 var eventNameGlobal = eventName + 'Global';
3137 plugins.forEach(function (plugin) {
3138 if (!sortable[plugin.pluginName]) return;
3139 // Fire global events if it exists in this sortable
3140 if (sortable[plugin.pluginName][eventNameGlobal]) {
3141 sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({
3142 sortable: sortable
3143 }, evt));
3144 }
3145
3146 // Only fire plugin event if plugin is enabled in this sortable,
3147 // and plugin has event defined
3148 if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {
3149 sortable[plugin.pluginName][eventName](_objectSpread2({
3150 sortable: sortable
3151 }, evt));
3152 }
3153 });
3154 },
3155 initializePlugins: function initializePlugins(sortable, el, defaults, options) {
3156 plugins.forEach(function (plugin) {
3157 var pluginName = plugin.pluginName;
3158 if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;
3159 var initialized = new plugin(sortable, el, sortable.options);
3160 initialized.sortable = sortable;
3161 initialized.options = sortable.options;
3162 sortable[pluginName] = initialized;
3163
3164 // Add default options from plugin
3165 _extends(defaults, initialized.defaults);
3166 });
3167 for (var option in sortable.options) {
3168 if (!sortable.options.hasOwnProperty(option)) continue;
3169 var modified = this.modifyOption(sortable, option, sortable.options[option]);
3170 if (typeof modified !== 'undefined') {
3171 sortable.options[option] = modified;
3172 }
3173 }
3174 },
3175 getEventProperties: function getEventProperties(name, sortable) {
3176 var eventProperties = {};
3177 plugins.forEach(function (plugin) {
3178 if (typeof plugin.eventProperties !== 'function') return;
3179 _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name));
3180 });
3181 return eventProperties;
3182 },
3183 modifyOption: function modifyOption(sortable, name, value) {
3184 var modifiedValue;
3185 plugins.forEach(function (plugin) {
3186 // Plugin must exist on the Sortable
3187 if (!sortable[plugin.pluginName]) return;
3188
3189 // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin
3190 if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {
3191 modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);
3192 }
3193 });
3194 return modifiedValue;
3195 }
3196 };
3197
3198 function dispatchEvent(_ref) {
3199 var sortable = _ref.sortable,
3200 rootEl = _ref.rootEl,
3201 name = _ref.name,
3202 targetEl = _ref.targetEl,
3203 cloneEl = _ref.cloneEl,
3204 toEl = _ref.toEl,
3205 fromEl = _ref.fromEl,
3206 oldIndex = _ref.oldIndex,
3207 newIndex = _ref.newIndex,
3208 oldDraggableIndex = _ref.oldDraggableIndex,
3209 newDraggableIndex = _ref.newDraggableIndex,
3210 originalEvent = _ref.originalEvent,
3211 putSortable = _ref.putSortable,
3212 extraEventProperties = _ref.extraEventProperties;
3213 sortable = sortable || rootEl && rootEl[expando];
3214 if (!sortable) return;
3215 var evt,
3216 options = sortable.options,
3217 onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
3218 // Support for new CustomEvent feature
3219 if (window.CustomEvent && !IE11OrLess && !Edge) {
3220 evt = new CustomEvent(name, {
3221 bubbles: true,
3222 cancelable: true
3223 });
3224 } else {
3225 evt = document.createEvent('Event');
3226 evt.initEvent(name, true, true);
3227 }
3228 evt.to = toEl || rootEl;
3229 evt.from = fromEl || rootEl;
3230 evt.item = targetEl || rootEl;
3231 evt.clone = cloneEl;
3232 evt.oldIndex = oldIndex;
3233 evt.newIndex = newIndex;
3234 evt.oldDraggableIndex = oldDraggableIndex;
3235 evt.newDraggableIndex = newDraggableIndex;
3236 evt.originalEvent = originalEvent;
3237 evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;
3238 var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable));
3239 for (var option in allEventProperties) {
3240 evt[option] = allEventProperties[option];
3241 }
3242 if (rootEl) {
3243 rootEl.dispatchEvent(evt);
3244 }
3245 if (options[onName]) {
3246 options[onName].call(sortable, evt);
3247 }
3248 }
3249
3250 var _excluded = ["evt"];
3251 var pluginEvent = function pluginEvent(eventName, sortable) {
3252 var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
3253 originalEvent = _ref.evt,
3254 data = _objectWithoutProperties(_ref, _excluded);
3255 PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({
3256 dragEl: dragEl,
3257 parentEl: parentEl,
3258 ghostEl: ghostEl,
3259 rootEl: rootEl,
3260 nextEl: nextEl,
3261 lastDownEl: lastDownEl,
3262 cloneEl: cloneEl,
3263 cloneHidden: cloneHidden,
3264 dragStarted: moved,
3265 putSortable: putSortable,
3266 activeSortable: Sortable.active,
3267 originalEvent: originalEvent,
3268 oldIndex: oldIndex,
3269 oldDraggableIndex: oldDraggableIndex,
3270 newIndex: newIndex,
3271 newDraggableIndex: newDraggableIndex,
3272 hideGhostForTarget: _hideGhostForTarget,
3273 unhideGhostForTarget: _unhideGhostForTarget,
3274 cloneNowHidden: function cloneNowHidden() {
3275 cloneHidden = true;
3276 },
3277 cloneNowShown: function cloneNowShown() {
3278 cloneHidden = false;
3279 },
3280 dispatchSortableEvent: function dispatchSortableEvent(name) {
3281 _dispatchEvent({
3282 sortable: sortable,
3283 name: name,
3284 originalEvent: originalEvent
3285 });
3286 }
3287 }, data));
3288 };
3289 function _dispatchEvent(info) {
3290 dispatchEvent(_objectSpread2({
3291 putSortable: putSortable,
3292 cloneEl: cloneEl,
3293 targetEl: dragEl,
3294 rootEl: rootEl,
3295 oldIndex: oldIndex,
3296 oldDraggableIndex: oldDraggableIndex,
3297 newIndex: newIndex,
3298 newDraggableIndex: newDraggableIndex
3299 }, info));
3300 }
3301 var dragEl,
3302 parentEl,
3303 ghostEl,
3304 rootEl,
3305 nextEl,
3306 lastDownEl,
3307 cloneEl,
3308 cloneHidden,
3309 oldIndex,
3310 newIndex,
3311 oldDraggableIndex,
3312 newDraggableIndex,
3313 activeGroup,
3314 putSortable,
3315 awaitingDragStarted = false,
3316 ignoreNextClick = false,
3317 sortables = [],
3318 tapEvt,
3319 touchEvt,
3320 lastDx,
3321 lastDy,
3322 tapDistanceLeft,
3323 tapDistanceTop,
3324 moved,
3325 lastTarget,
3326 lastDirection,
3327 pastFirstInvertThresh = false,
3328 isCircumstantialInvert = false,
3329 targetMoveDistance,
3330 // For positioning ghost absolutely
3331 ghostRelativeParent,
3332 ghostRelativeParentInitialScroll = [],
3333 // (left, top)
3334
3335 _silent = false,
3336 savedInputChecked = [];
3337
3338 /** @const */
3339 var documentExists = typeof document !== 'undefined',
3340 PositionGhostAbsolutely = IOS,
3341 CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',
3342 // This will not pass for IE9, because IE9 DnD only works on anchors
3343 supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),
3344 supportCssPointerEvents = function () {
3345 if (!documentExists) return;
3346 // false when <= IE11
3347 if (IE11OrLess) {
3348 return false;
3349 }
3350 var el = document.createElement('x');
3351 el.style.cssText = 'pointer-events:auto';
3352 return el.style.pointerEvents === 'auto';
3353 }(),
3354 _detectDirection = function _detectDirection(el, options) {
3355 var elCSS = css(el),
3356 elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),
3357 child1 = getChild(el, 0, options),
3358 child2 = getChild(el, 1, options),
3359 firstChildCSS = child1 && css(child1),
3360 secondChildCSS = child2 && css(child2),
3361 firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,
3362 secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;
3363 if (elCSS.display === 'flex') {
3364 return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';
3365 }
3366 if (elCSS.display === 'grid') {
3367 return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';
3368 }
3369 if (child1 && firstChildCSS["float"] && firstChildCSS["float"] !== 'none') {
3370 var touchingSideChild2 = firstChildCSS["float"] === 'left' ? 'left' : 'right';
3371 return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';
3372 }
3373 return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';
3374 },
3375 _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {
3376 var dragElS1Opp = vertical ? dragRect.left : dragRect.top,
3377 dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,
3378 dragElOppLength = vertical ? dragRect.width : dragRect.height,
3379 targetS1Opp = vertical ? targetRect.left : targetRect.top,
3380 targetS2Opp = vertical ? targetRect.right : targetRect.bottom,
3381 targetOppLength = vertical ? targetRect.width : targetRect.height;
3382 return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;
3383 },
3384 /**
3385 * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.
3386 * @param {Number} x X position
3387 * @param {Number} y Y position
3388 * @return {HTMLElement} Element of the first found nearest Sortable
3389 */
3390 _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {
3391 var ret;
3392 sortables.some(function (sortable) {
3393 var threshold = sortable[expando].options.emptyInsertThreshold;
3394 if (!threshold || lastChild(sortable)) return;
3395 var rect = getRect(sortable),
3396 insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,
3397 insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;
3398 if (insideHorizontally && insideVertically) {
3399 return ret = sortable;
3400 }
3401 });
3402 return ret;
3403 },
3404 _prepareGroup = function _prepareGroup(options) {
3405 function toFn(value, pull) {
3406 return function (to, from, dragEl, evt) {
3407 var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;
3408 if (value == null && (pull || sameGroup)) {
3409 // Default pull value
3410 // Default pull and put value if same group
3411 return true;
3412 } else if (value == null || value === false) {
3413 return false;
3414 } else if (pull && value === 'clone') {
3415 return value;
3416 } else if (typeof value === 'function') {
3417 return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);
3418 } else {
3419 var otherGroup = (pull ? to : from).options.group.name;
3420 return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;
3421 }
3422 };
3423 }
3424 var group = {};
3425 var originalGroup = options.group;
3426 if (!originalGroup || _typeof(originalGroup) != 'object') {
3427 originalGroup = {
3428 name: originalGroup
3429 };
3430 }
3431 group.name = originalGroup.name;
3432 group.checkPull = toFn(originalGroup.pull, true);
3433 group.checkPut = toFn(originalGroup.put);
3434 group.revertClone = originalGroup.revertClone;
3435 options.group = group;
3436 },
3437 _hideGhostForTarget = function _hideGhostForTarget() {
3438 if (!supportCssPointerEvents && ghostEl) {
3439 css(ghostEl, 'display', 'none');
3440 }
3441 },
3442 _unhideGhostForTarget = function _unhideGhostForTarget() {
3443 if (!supportCssPointerEvents && ghostEl) {
3444 css(ghostEl, 'display', '');
3445 }
3446 };
3447
3448 // #1184 fix - Prevent click event on fallback if dragged but item not changed position
3449 if (documentExists && !ChromeForAndroid) {
3450 document.addEventListener('click', function (evt) {
3451 if (ignoreNextClick) {
3452 evt.preventDefault();
3453 evt.stopPropagation && evt.stopPropagation();
3454 evt.stopImmediatePropagation && evt.stopImmediatePropagation();
3455 ignoreNextClick = false;
3456 return false;
3457 }
3458 }, true);
3459 }
3460 var nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {
3461 if (dragEl) {
3462 evt = evt.touches ? evt.touches[0] : evt;
3463 var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);
3464 if (nearest) {
3465 // Create imitation event
3466 var event = {};
3467 for (var i in evt) {
3468 if (evt.hasOwnProperty(i)) {
3469 event[i] = evt[i];
3470 }
3471 }
3472 event.target = event.rootEl = nearest;
3473 event.preventDefault = void 0;
3474 event.stopPropagation = void 0;
3475 nearest[expando]._onDragOver(event);
3476 }
3477 }
3478 };
3479 var _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {
3480 if (dragEl) {
3481 dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
3482 }
3483 };
3484
3485 /**
3486 * @class Sortable
3487 * @param {HTMLElement} el
3488 * @param {Object} [options]
3489 */
3490 function Sortable(el, options) {
3491 if (!(el && el.nodeType && el.nodeType === 1)) {
3492 throw "Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));
3493 }
3494 this.el = el; // root element
3495 this.options = options = _extends({}, options);
3496
3497 // Export instance
3498 el[expando] = this;
3499 var defaults = {
3500 group: null,
3501 sort: true,
3502 disabled: false,
3503 store: null,
3504 handle: null,
3505 draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',
3506 swapThreshold: 1,
3507 // percentage; 0 <= x <= 1
3508 invertSwap: false,
3509 // invert always
3510 invertedSwapThreshold: null,
3511 // will be set to same as swapThreshold if default
3512 removeCloneOnHide: true,
3513 direction: function direction() {
3514 return _detectDirection(el, this.options);
3515 },
3516 ghostClass: 'sortable-ghost',
3517 chosenClass: 'sortable-chosen',
3518 dragClass: 'sortable-drag',
3519 ignore: 'a, img',
3520 filter: null,
3521 preventOnFilter: true,
3522 animation: 0,
3523 easing: null,
3524 setData: function setData(dataTransfer, dragEl) {
3525 dataTransfer.setData('Text', dragEl.textContent);
3526 },
3527 dropBubble: false,
3528 dragoverBubble: false,
3529 dataIdAttr: 'data-id',
3530 delay: 0,
3531 delayOnTouchOnly: false,
3532 touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,
3533 forceFallback: false,
3534 fallbackClass: 'sortable-fallback',
3535 fallbackOnBody: false,
3536 fallbackTolerance: 0,
3537 fallbackOffset: {
3538 x: 0,
3539 y: 0
3540 },
3541 // Disabled on Safari: #1571; Enabled on Safari IOS: #2244
3542 supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && (!Safari || IOS),
3543 emptyInsertThreshold: 5
3544 };
3545 PluginManager.initializePlugins(this, el, defaults);
3546
3547 // Set default options
3548 for (var name in defaults) {
3549 !(name in options) && (options[name] = defaults[name]);
3550 }
3551 _prepareGroup(options);
3552
3553 // Bind all private methods
3554 for (var fn in this) {
3555 if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
3556 this[fn] = this[fn].bind(this);
3557 }
3558 }
3559
3560 // Setup drag mode
3561 this.nativeDraggable = options.forceFallback ? false : supportDraggable;
3562 if (this.nativeDraggable) {
3563 // Touch start threshold cannot be greater than the native dragstart threshold
3564 this.options.touchStartThreshold = 1;
3565 }
3566
3567 // Bind events
3568 if (options.supportPointer) {
3569 on(el, 'pointerdown', this._onTapStart);
3570 } else {
3571 on(el, 'mousedown', this._onTapStart);
3572 on(el, 'touchstart', this._onTapStart);
3573 }
3574 if (this.nativeDraggable) {
3575 on(el, 'dragover', this);
3576 on(el, 'dragenter', this);
3577 }
3578 sortables.push(this.el);
3579
3580 // Restore sorting
3581 options.store && options.store.get && this.sort(options.store.get(this) || []);
3582
3583 // Add animation state manager
3584 _extends(this, AnimationStateManager());
3585 }
3586 Sortable.prototype = /** @lends Sortable.prototype */{
3587 constructor: Sortable,
3588 _isOutsideThisEl: function _isOutsideThisEl(target) {
3589 if (!this.el.contains(target) && target !== this.el) {
3590 lastTarget = null;
3591 }
3592 },
3593 _getDirection: function _getDirection(evt, target) {
3594 return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;
3595 },
3596 _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) {
3597 if (!evt.cancelable) return;
3598 var _this = this,
3599 el = this.el,
3600 options = this.options,
3601 preventOnFilter = options.preventOnFilter,
3602 type = evt.type,
3603 touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt,
3604 target = (touch || evt).target,
3605 originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,
3606 filter = options.filter;
3607 _saveInputCheckedState(el);
3608
3609 // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
3610 if (dragEl) {
3611 return;
3612 }
3613 if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
3614 return; // only left button and enabled
3615 }
3616
3617 // cancel dnd if original target is content editable
3618 if (originalTarget.isContentEditable) {
3619 return;
3620 }
3621
3622 // Safari ignores further event handling after mousedown
3623 if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') {
3624 return;
3625 }
3626 target = closest(target, options.draggable, el, false);
3627 if (target && target.animated) {
3628 return;
3629 }
3630 if (lastDownEl === target) {
3631 // Ignoring duplicate `down`
3632 return;
3633 }
3634
3635 // Get the index of the dragged element within its parent
3636 oldIndex = index(target);
3637 oldDraggableIndex = index(target, options.draggable);
3638
3639 // Check filter
3640 if (typeof filter === 'function') {
3641 if (filter.call(this, evt, target, this)) {
3642 _dispatchEvent({
3643 sortable: _this,
3644 rootEl: originalTarget,
3645 name: 'filter',
3646 targetEl: target,
3647 toEl: el,
3648 fromEl: el
3649 });
3650 pluginEvent('filter', _this, {
3651 evt: evt
3652 });
3653 preventOnFilter && evt.preventDefault();
3654 return; // cancel dnd
3655 }
3656 } else if (filter) {
3657 filter = filter.split(',').some(function (criteria) {
3658 criteria = closest(originalTarget, criteria.trim(), el, false);
3659 if (criteria) {
3660 _dispatchEvent({
3661 sortable: _this,
3662 rootEl: criteria,
3663 name: 'filter',
3664 targetEl: target,
3665 fromEl: el,
3666 toEl: el
3667 });
3668 pluginEvent('filter', _this, {
3669 evt: evt
3670 });
3671 return true;
3672 }
3673 });
3674 if (filter) {
3675 preventOnFilter && evt.preventDefault();
3676 return; // cancel dnd
3677 }
3678 }
3679 if (options.handle && !closest(originalTarget, options.handle, el, false)) {
3680 return;
3681 }
3682
3683 // Prepare `dragstart`
3684 this._prepareDragStart(evt, touch, target);
3685 },
3686 _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) {
3687 var _this = this,
3688 el = _this.el,
3689 options = _this.options,
3690 ownerDocument = el.ownerDocument,
3691 dragStartFn;
3692 if (target && !dragEl && target.parentNode === el) {
3693 var dragRect = getRect(target);
3694 rootEl = el;
3695 dragEl = target;
3696 parentEl = dragEl.parentNode;
3697 nextEl = dragEl.nextSibling;
3698 lastDownEl = target;
3699 activeGroup = options.group;
3700 Sortable.dragged = dragEl;
3701 tapEvt = {
3702 target: dragEl,
3703 clientX: (touch || evt).clientX,
3704 clientY: (touch || evt).clientY
3705 };
3706 tapDistanceLeft = tapEvt.clientX - dragRect.left;
3707 tapDistanceTop = tapEvt.clientY - dragRect.top;
3708 this._lastX = (touch || evt).clientX;
3709 this._lastY = (touch || evt).clientY;
3710 dragEl.style['will-change'] = 'all';
3711 dragStartFn = function dragStartFn() {
3712 pluginEvent('delayEnded', _this, {
3713 evt: evt
3714 });
3715 if (Sortable.eventCanceled) {
3716 _this._onDrop();
3717 return;
3718 }
3719 // Delayed drag has been triggered
3720 // we can re-enable the events: touchmove/mousemove
3721 _this._disableDelayedDragEvents();
3722 if (!FireFox && _this.nativeDraggable) {
3723 dragEl.draggable = true;
3724 }
3725
3726 // Bind the events: dragstart/dragend
3727 _this._triggerDragStart(evt, touch);
3728
3729 // Drag start event
3730 _dispatchEvent({
3731 sortable: _this,
3732 name: 'choose',
3733 originalEvent: evt
3734 });
3735
3736 // Chosen item
3737 toggleClass(dragEl, options.chosenClass, true);
3738 };
3739
3740 // Disable "draggable"
3741 options.ignore.split(',').forEach(function (criteria) {
3742 find(dragEl, criteria.trim(), _disableDraggable);
3743 });
3744 on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);
3745 on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);
3746 on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);
3747 if (options.supportPointer) {
3748 on(ownerDocument, 'pointerup', _this._onDrop);
3749 // Native D&D triggers pointercancel
3750 !this.nativeDraggable && on(ownerDocument, 'pointercancel', _this._onDrop);
3751 } else {
3752 on(ownerDocument, 'mouseup', _this._onDrop);
3753 on(ownerDocument, 'touchend', _this._onDrop);
3754 on(ownerDocument, 'touchcancel', _this._onDrop);
3755 }
3756
3757 // Make dragEl draggable (must be before delay for FireFox)
3758 if (FireFox && this.nativeDraggable) {
3759 this.options.touchStartThreshold = 4;
3760 dragEl.draggable = true;
3761 }
3762 pluginEvent('delayStart', this, {
3763 evt: evt
3764 });
3765
3766 // Delay is impossible for native DnD in Edge or IE
3767 if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {
3768 if (Sortable.eventCanceled) {
3769 this._onDrop();
3770 return;
3771 }
3772 // If the user moves the pointer or let go the click or touch
3773 // before the delay has been reached:
3774 // disable the delayed drag
3775 if (options.supportPointer) {
3776 on(ownerDocument, 'pointerup', _this._disableDelayedDrag);
3777 on(ownerDocument, 'pointercancel', _this._disableDelayedDrag);
3778 } else {
3779 on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
3780 on(ownerDocument, 'touchend', _this._disableDelayedDrag);
3781 on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
3782 }
3783 on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);
3784 on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
3785 options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
3786 _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
3787 } else {
3788 dragStartFn();
3789 }
3790 }
3791 },
3792 _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) {
3793 var touch = e.touches ? e.touches[0] : e;
3794 if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {
3795 this._disableDelayedDrag();
3796 }
3797 },
3798 _disableDelayedDrag: function _disableDelayedDrag() {
3799 dragEl && _disableDraggable(dragEl);
3800 clearTimeout(this._dragStartTimer);
3801 this._disableDelayedDragEvents();
3802 },
3803 _disableDelayedDragEvents: function _disableDelayedDragEvents() {
3804 var ownerDocument = this.el.ownerDocument;
3805 off(ownerDocument, 'mouseup', this._disableDelayedDrag);
3806 off(ownerDocument, 'touchend', this._disableDelayedDrag);
3807 off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
3808 off(ownerDocument, 'pointerup', this._disableDelayedDrag);
3809 off(ownerDocument, 'pointercancel', this._disableDelayedDrag);
3810 off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);
3811 off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);
3812 off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);
3813 },
3814 _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) {
3815 touch = touch || evt.pointerType == 'touch' && evt;
3816 if (!this.nativeDraggable || touch) {
3817 if (this.options.supportPointer) {
3818 on(document, 'pointermove', this._onTouchMove);
3819 } else if (touch) {
3820 on(document, 'touchmove', this._onTouchMove);
3821 } else {
3822 on(document, 'mousemove', this._onTouchMove);
3823 }
3824 } else {
3825 on(dragEl, 'dragend', this);
3826 on(rootEl, 'dragstart', this._onDragStart);
3827 }
3828 try {
3829 if (document.selection) {
3830 _nextTick(function () {
3831 document.selection.empty();
3832 });
3833 } else {
3834 window.getSelection().removeAllRanges();
3835 }
3836 } catch (err) {}
3837 },
3838 _dragStarted: function _dragStarted(fallback, evt) {
3839 awaitingDragStarted = false;
3840 if (rootEl && dragEl) {
3841 pluginEvent('dragStarted', this, {
3842 evt: evt
3843 });
3844 if (this.nativeDraggable) {
3845 on(document, 'dragover', _checkOutsideTargetEl);
3846 }
3847 var options = this.options;
3848
3849 // Apply effect
3850 !fallback && toggleClass(dragEl, options.dragClass, false);
3851 toggleClass(dragEl, options.ghostClass, true);
3852 Sortable.active = this;
3853 fallback && this._appendGhost();
3854
3855 // Drag start event
3856 _dispatchEvent({
3857 sortable: this,
3858 name: 'start',
3859 originalEvent: evt
3860 });
3861 } else {
3862 this._nulling();
3863 }
3864 },
3865 _emulateDragOver: function _emulateDragOver() {
3866 if (touchEvt) {
3867 this._lastX = touchEvt.clientX;
3868 this._lastY = touchEvt.clientY;
3869 _hideGhostForTarget();
3870 var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
3871 var parent = target;
3872 while (target && target.shadowRoot) {
3873 target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
3874 if (target === parent) break;
3875 parent = target;
3876 }
3877 dragEl.parentNode[expando]._isOutsideThisEl(target);
3878 if (parent) {
3879 do {
3880 if (parent[expando]) {
3881 var inserted = void 0;
3882 inserted = parent[expando]._onDragOver({
3883 clientX: touchEvt.clientX,
3884 clientY: touchEvt.clientY,
3885 target: target,
3886 rootEl: parent
3887 });
3888 if (inserted && !this.options.dragoverBubble) {
3889 break;
3890 }
3891 }
3892 target = parent; // store last element
3893 }
3894 /* jshint boss:true */ while (parent = getParentOrHost(parent));
3895 }
3896 _unhideGhostForTarget();
3897 }
3898 },
3899 _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) {
3900 if (tapEvt) {
3901 var options = this.options,
3902 fallbackTolerance = options.fallbackTolerance,
3903 fallbackOffset = options.fallbackOffset,
3904 touch = evt.touches ? evt.touches[0] : evt,
3905 ghostMatrix = ghostEl && matrix(ghostEl, true),
3906 scaleX = ghostEl && ghostMatrix && ghostMatrix.a,
3907 scaleY = ghostEl && ghostMatrix && ghostMatrix.d,
3908 relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),
3909 dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),
3910 dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1);
3911
3912 // only set the status to dragging, when we are actually dragging
3913 if (!Sortable.active && !awaitingDragStarted) {
3914 if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {
3915 return;
3916 }
3917 this._onDragStart(evt, true);
3918 }
3919 if (ghostEl) {
3920 if (ghostMatrix) {
3921 ghostMatrix.e += dx - (lastDx || 0);
3922 ghostMatrix.f += dy - (lastDy || 0);
3923 } else {
3924 ghostMatrix = {
3925 a: 1,
3926 b: 0,
3927 c: 0,
3928 d: 1,
3929 e: dx,
3930 f: dy
3931 };
3932 }
3933 var cssMatrix = "matrix(".concat(ghostMatrix.a, ",").concat(ghostMatrix.b, ",").concat(ghostMatrix.c, ",").concat(ghostMatrix.d, ",").concat(ghostMatrix.e, ",").concat(ghostMatrix.f, ")");
3934 css(ghostEl, 'webkitTransform', cssMatrix);
3935 css(ghostEl, 'mozTransform', cssMatrix);
3936 css(ghostEl, 'msTransform', cssMatrix);
3937 css(ghostEl, 'transform', cssMatrix);
3938 lastDx = dx;
3939 lastDy = dy;
3940 touchEvt = touch;
3941 }
3942 evt.cancelable && evt.preventDefault();
3943 }
3944 },
3945 _appendGhost: function _appendGhost() {
3946 // Bug if using scale(): https://stackoverflow.com/questions/2637058
3947 // Not being adjusted for
3948 if (!ghostEl) {
3949 var container = this.options.fallbackOnBody ? document.body : rootEl,
3950 rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),
3951 options = this.options;
3952
3953 // Position absolutely
3954 if (PositionGhostAbsolutely) {
3955 // Get relatively positioned parent
3956 ghostRelativeParent = container;
3957 while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {
3958 ghostRelativeParent = ghostRelativeParent.parentNode;
3959 }
3960 if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {
3961 if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();
3962 rect.top += ghostRelativeParent.scrollTop;
3963 rect.left += ghostRelativeParent.scrollLeft;
3964 } else {
3965 ghostRelativeParent = getWindowScrollingElement();
3966 }
3967 ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);
3968 }
3969 ghostEl = dragEl.cloneNode(true);
3970 toggleClass(ghostEl, options.ghostClass, false);
3971 toggleClass(ghostEl, options.fallbackClass, true);
3972 toggleClass(ghostEl, options.dragClass, true);
3973 css(ghostEl, 'transition', '');
3974 css(ghostEl, 'transform', '');
3975 css(ghostEl, 'box-sizing', 'border-box');
3976 css(ghostEl, 'margin', 0);
3977 css(ghostEl, 'top', rect.top);
3978 css(ghostEl, 'left', rect.left);
3979 css(ghostEl, 'width', rect.width);
3980 css(ghostEl, 'height', rect.height);
3981 css(ghostEl, 'opacity', '0.8');
3982 css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');
3983 css(ghostEl, 'zIndex', '100000');
3984 css(ghostEl, 'pointerEvents', 'none');
3985 Sortable.ghost = ghostEl;
3986 container.appendChild(ghostEl);
3987
3988 // Set transform-origin
3989 css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%');
3990 }
3991 },
3992 _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) {
3993 var _this = this;
3994 var dataTransfer = evt.dataTransfer;
3995 var options = _this.options;
3996 pluginEvent('dragStart', this, {
3997 evt: evt
3998 });
3999 if (Sortable.eventCanceled) {
4000 this._onDrop();
4001 return;
4002 }
4003 pluginEvent('setupClone', this);
4004 if (!Sortable.eventCanceled) {
4005 cloneEl = clone(dragEl);
4006 cloneEl.removeAttribute("id");
4007 cloneEl.draggable = false;
4008 cloneEl.style['will-change'] = '';
4009 this._hideClone();
4010 toggleClass(cloneEl, this.options.chosenClass, false);
4011 Sortable.clone = cloneEl;
4012 }
4013
4014 // #1143: IFrame support workaround
4015 _this.cloneId = _nextTick(function () {
4016 pluginEvent('clone', _this);
4017 if (Sortable.eventCanceled) return;
4018 if (!_this.options.removeCloneOnHide) {
4019 rootEl.insertBefore(cloneEl, dragEl);
4020 }
4021 _this._hideClone();
4022 _dispatchEvent({
4023 sortable: _this,
4024 name: 'clone'
4025 });
4026 });
4027 !fallback && toggleClass(dragEl, options.dragClass, true);
4028
4029 // Set proper drop events
4030 if (fallback) {
4031 ignoreNextClick = true;
4032 _this._loopId = setInterval(_this._emulateDragOver, 50);
4033 } else {
4034 // Undo what was set in _prepareDragStart before drag started
4035 off(document, 'mouseup', _this._onDrop);
4036 off(document, 'touchend', _this._onDrop);
4037 off(document, 'touchcancel', _this._onDrop);
4038 if (dataTransfer) {
4039 dataTransfer.effectAllowed = 'move';
4040 options.setData && options.setData.call(_this, dataTransfer, dragEl);
4041 }
4042 on(document, 'drop', _this);
4043
4044 // #1276 fix:
4045 css(dragEl, 'transform', 'translateZ(0)');
4046 }
4047 awaitingDragStarted = true;
4048 _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));
4049 on(document, 'selectstart', _this);
4050 moved = true;
4051 window.getSelection().removeAllRanges();
4052 if (Safari) {
4053 css(document.body, 'user-select', 'none');
4054 }
4055 },
4056 // Returns true - if no further action is needed (either inserted or another condition)
4057 _onDragOver: function _onDragOver( /**Event*/evt) {
4058 var el = this.el,
4059 target = evt.target,
4060 dragRect,
4061 targetRect,
4062 revert,
4063 options = this.options,
4064 group = options.group,
4065 activeSortable = Sortable.active,
4066 isOwner = activeGroup === group,
4067 canSort = options.sort,
4068 fromSortable = putSortable || activeSortable,
4069 vertical,
4070 _this = this,
4071 completedFired = false;
4072 if (_silent) return;
4073 function dragOverEvent(name, extra) {
4074 pluginEvent(name, _this, _objectSpread2({
4075 evt: evt,
4076 isOwner: isOwner,
4077 axis: vertical ? 'vertical' : 'horizontal',
4078 revert: revert,
4079 dragRect: dragRect,
4080 targetRect: targetRect,
4081 canSort: canSort,
4082 fromSortable: fromSortable,
4083 target: target,
4084 completed: completed,
4085 onMove: function onMove(target, after) {
4086 return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);
4087 },
4088 changed: changed
4089 }, extra));
4090 }
4091
4092 // Capture animation state
4093 function capture() {
4094 dragOverEvent('dragOverAnimationCapture');
4095 _this.captureAnimationState();
4096 if (_this !== fromSortable) {
4097 fromSortable.captureAnimationState();
4098 }
4099 }
4100
4101 // Return invocation when dragEl is inserted (or completed)
4102 function completed(insertion) {
4103 dragOverEvent('dragOverCompleted', {
4104 insertion: insertion
4105 });
4106 if (insertion) {
4107 // Clones must be hidden before folding animation to capture dragRectAbsolute properly
4108 if (isOwner) {
4109 activeSortable._hideClone();
4110 } else {
4111 activeSortable._showClone(_this);
4112 }
4113 if (_this !== fromSortable) {
4114 // Set ghost class to new sortable's ghost class
4115 toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);
4116 toggleClass(dragEl, options.ghostClass, true);
4117 }
4118 if (putSortable !== _this && _this !== Sortable.active) {
4119 putSortable = _this;
4120 } else if (_this === Sortable.active && putSortable) {
4121 putSortable = null;
4122 }
4123
4124 // Animation
4125 if (fromSortable === _this) {
4126 _this._ignoreWhileAnimating = target;
4127 }
4128 _this.animateAll(function () {
4129 dragOverEvent('dragOverAnimationComplete');
4130 _this._ignoreWhileAnimating = null;
4131 });
4132 if (_this !== fromSortable) {
4133 fromSortable.animateAll();
4134 fromSortable._ignoreWhileAnimating = null;
4135 }
4136 }
4137
4138 // Null lastTarget if it is not inside a previously swapped element
4139 if (target === dragEl && !dragEl.animated || target === el && !target.animated) {
4140 lastTarget = null;
4141 }
4142
4143 // no bubbling and not fallback
4144 if (!options.dragoverBubble && !evt.rootEl && target !== document) {
4145 dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
4146
4147 // Do not detect for empty insert if already inserted
4148 !insertion && nearestEmptyInsertDetectEvent(evt);
4149 }
4150 !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();
4151 return completedFired = true;
4152 }
4153
4154 // Call when dragEl has been inserted
4155 function changed() {
4156 newIndex = index(dragEl);
4157 newDraggableIndex = index(dragEl, options.draggable);
4158 _dispatchEvent({
4159 sortable: _this,
4160 name: 'change',
4161 toEl: el,
4162 newIndex: newIndex,
4163 newDraggableIndex: newDraggableIndex,
4164 originalEvent: evt
4165 });
4166 }
4167 if (evt.preventDefault !== void 0) {
4168 evt.cancelable && evt.preventDefault();
4169 }
4170 target = closest(target, options.draggable, el, true);
4171 dragOverEvent('dragOver');
4172 if (Sortable.eventCanceled) return completedFired;
4173 if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {
4174 return completed(false);
4175 }
4176 ignoreNextClick = false;
4177 if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list
4178 : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {
4179 vertical = this._getDirection(evt, target) === 'vertical';
4180 dragRect = getRect(dragEl);
4181 dragOverEvent('dragOverValid');
4182 if (Sortable.eventCanceled) return completedFired;
4183 if (revert) {
4184 parentEl = rootEl; // actualization
4185 capture();
4186 this._hideClone();
4187 dragOverEvent('revert');
4188 if (!Sortable.eventCanceled) {
4189 if (nextEl) {
4190 rootEl.insertBefore(dragEl, nextEl);
4191 } else {
4192 rootEl.appendChild(dragEl);
4193 }
4194 }
4195 return completed(true);
4196 }
4197 var elLastChild = lastChild(el, options.draggable);
4198 if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {
4199 // Insert to end of list
4200
4201 // If already at end of list: Do not insert
4202 if (elLastChild === dragEl) {
4203 return completed(false);
4204 }
4205
4206 // if there is a last element, it is the target
4207 if (elLastChild && el === evt.target) {
4208 target = elLastChild;
4209 }
4210 if (target) {
4211 targetRect = getRect(target);
4212 }
4213 if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {
4214 capture();
4215 if (elLastChild && elLastChild.nextSibling) {
4216 // the last draggable element is not the last node
4217 el.insertBefore(dragEl, elLastChild.nextSibling);
4218 } else {
4219 el.appendChild(dragEl);
4220 }
4221 parentEl = el; // actualization
4222
4223 changed();
4224 return completed(true);
4225 }
4226 } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) {
4227 // Insert to start of list
4228 var firstChild = getChild(el, 0, options, true);
4229 if (firstChild === dragEl) {
4230 return completed(false);
4231 }
4232 target = firstChild;
4233 targetRect = getRect(target);
4234 if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {
4235 capture();
4236 el.insertBefore(dragEl, firstChild);
4237 parentEl = el; // actualization
4238
4239 changed();
4240 return completed(true);
4241 }
4242 } else if (target.parentNode === el) {
4243 targetRect = getRect(target);
4244 var direction = 0,
4245 targetBeforeFirstSwap,
4246 differentLevel = dragEl.parentNode !== el,
4247 differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),
4248 side1 = vertical ? 'top' : 'left',
4249 scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'),
4250 scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;
4251 if (lastTarget !== target) {
4252 targetBeforeFirstSwap = targetRect[side1];
4253 pastFirstInvertThresh = false;
4254 isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;
4255 }
4256 direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);
4257 var sibling;
4258 if (direction !== 0) {
4259 // Check if target is beside dragEl in respective direction (ignoring hidden elements)
4260 var dragIndex = index(dragEl);
4261 do {
4262 dragIndex -= direction;
4263 sibling = parentEl.children[dragIndex];
4264 } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));
4265 }
4266 // If dragEl is already beside target: Do not insert
4267 if (direction === 0 || sibling === target) {
4268 return completed(false);
4269 }
4270 lastTarget = target;
4271 lastDirection = direction;
4272 var nextSibling = target.nextElementSibling,
4273 after = false;
4274 after = direction === 1;
4275 var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
4276 if (moveVector !== false) {
4277 if (moveVector === 1 || moveVector === -1) {
4278 after = moveVector === 1;
4279 }
4280 _silent = true;
4281 setTimeout(_unsilent, 30);
4282 capture();
4283 if (after && !nextSibling) {
4284 el.appendChild(dragEl);
4285 } else {
4286 target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
4287 }
4288
4289 // Undo chrome's scroll adjustment (has no effect on other browsers)
4290 if (scrolledPastTop) {
4291 scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);
4292 }
4293 parentEl = dragEl.parentNode; // actualization
4294
4295 // must be done before animation
4296 if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {
4297 targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);
4298 }
4299 changed();
4300 return completed(true);
4301 }
4302 }
4303 if (el.contains(dragEl)) {
4304 return completed(false);
4305 }
4306 }
4307 return false;
4308 },
4309 _ignoreWhileAnimating: null,
4310 _offMoveEvents: function _offMoveEvents() {
4311 off(document, 'mousemove', this._onTouchMove);
4312 off(document, 'touchmove', this._onTouchMove);
4313 off(document, 'pointermove', this._onTouchMove);
4314 off(document, 'dragover', nearestEmptyInsertDetectEvent);
4315 off(document, 'mousemove', nearestEmptyInsertDetectEvent);
4316 off(document, 'touchmove', nearestEmptyInsertDetectEvent);
4317 },
4318 _offUpEvents: function _offUpEvents() {
4319 var ownerDocument = this.el.ownerDocument;
4320 off(ownerDocument, 'mouseup', this._onDrop);
4321 off(ownerDocument, 'touchend', this._onDrop);
4322 off(ownerDocument, 'pointerup', this._onDrop);
4323 off(ownerDocument, 'pointercancel', this._onDrop);
4324 off(ownerDocument, 'touchcancel', this._onDrop);
4325 off(document, 'selectstart', this);
4326 },
4327 _onDrop: function _onDrop( /**Event*/evt) {
4328 var el = this.el,
4329 options = this.options;
4330
4331 // Get the index of the dragged element within its parent
4332 newIndex = index(dragEl);
4333 newDraggableIndex = index(dragEl, options.draggable);
4334 pluginEvent('drop', this, {
4335 evt: evt
4336 });
4337 parentEl = dragEl && dragEl.parentNode;
4338
4339 // Get again after plugin event
4340 newIndex = index(dragEl);
4341 newDraggableIndex = index(dragEl, options.draggable);
4342 if (Sortable.eventCanceled) {
4343 this._nulling();
4344 return;
4345 }
4346 awaitingDragStarted = false;
4347 isCircumstantialInvert = false;
4348 pastFirstInvertThresh = false;
4349 clearInterval(this._loopId);
4350 clearTimeout(this._dragStartTimer);
4351 _cancelNextTick(this.cloneId);
4352 _cancelNextTick(this._dragStartId);
4353
4354 // Unbind events
4355 if (this.nativeDraggable) {
4356 off(document, 'drop', this);
4357 off(el, 'dragstart', this._onDragStart);
4358 }
4359 this._offMoveEvents();
4360 this._offUpEvents();
4361 if (Safari) {
4362 css(document.body, 'user-select', '');
4363 }
4364 css(dragEl, 'transform', '');
4365 if (evt) {
4366 if (moved) {
4367 evt.cancelable && evt.preventDefault();
4368 !options.dropBubble && evt.stopPropagation();
4369 }
4370 ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
4371 if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
4372 // Remove clone(s)
4373 cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
4374 }
4375 if (dragEl) {
4376 if (this.nativeDraggable) {
4377 off(dragEl, 'dragend', this);
4378 }
4379 _disableDraggable(dragEl);
4380 dragEl.style['will-change'] = '';
4381
4382 // Remove classes
4383 // ghostClass is added in dragStarted
4384 if (moved && !awaitingDragStarted) {
4385 toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);
4386 }
4387 toggleClass(dragEl, this.options.chosenClass, false);
4388
4389 // Drag stop event
4390 _dispatchEvent({
4391 sortable: this,
4392 name: 'unchoose',
4393 toEl: parentEl,
4394 newIndex: null,
4395 newDraggableIndex: null,
4396 originalEvent: evt
4397 });
4398 if (rootEl !== parentEl) {
4399 if (newIndex >= 0) {
4400 // Add event
4401 _dispatchEvent({
4402 rootEl: parentEl,
4403 name: 'add',
4404 toEl: parentEl,
4405 fromEl: rootEl,
4406 originalEvent: evt
4407 });
4408
4409 // Remove event
4410 _dispatchEvent({
4411 sortable: this,
4412 name: 'remove',
4413 toEl: parentEl,
4414 originalEvent: evt
4415 });
4416
4417 // drag from one list and drop into another
4418 _dispatchEvent({
4419 rootEl: parentEl,
4420 name: 'sort',
4421 toEl: parentEl,
4422 fromEl: rootEl,
4423 originalEvent: evt
4424 });
4425 _dispatchEvent({
4426 sortable: this,
4427 name: 'sort',
4428 toEl: parentEl,
4429 originalEvent: evt
4430 });
4431 }
4432 putSortable && putSortable.save();
4433 } else {
4434 if (newIndex !== oldIndex) {
4435 if (newIndex >= 0) {
4436 // drag & drop within the same list
4437 _dispatchEvent({
4438 sortable: this,
4439 name: 'update',
4440 toEl: parentEl,
4441 originalEvent: evt
4442 });
4443 _dispatchEvent({
4444 sortable: this,
4445 name: 'sort',
4446 toEl: parentEl,
4447 originalEvent: evt
4448 });
4449 }
4450 }
4451 }
4452 if (Sortable.active) {
4453 /* jshint eqnull:true */
4454 if (newIndex == null || newIndex === -1) {
4455 newIndex = oldIndex;
4456 newDraggableIndex = oldDraggableIndex;
4457 }
4458 _dispatchEvent({
4459 sortable: this,
4460 name: 'end',
4461 toEl: parentEl,
4462 originalEvent: evt
4463 });
4464
4465 // Save sorting
4466 this.save();
4467 }
4468 }
4469 }
4470 this._nulling();
4471 },
4472 _nulling: function _nulling() {
4473 pluginEvent('nulling', this);
4474 rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;
4475 var el = this.el;
4476 savedInputChecked.forEach(function (checkEl) {
4477 if (el.contains(checkEl)) {
4478 checkEl.checked = true;
4479 }
4480 });
4481 savedInputChecked.length = lastDx = lastDy = 0;
4482 },
4483 handleEvent: function handleEvent( /**Event*/evt) {
4484 switch (evt.type) {
4485 case 'drop':
4486 case 'dragend':
4487 this._onDrop(evt);
4488 break;
4489 case 'dragenter':
4490 case 'dragover':
4491 if (dragEl) {
4492 this._onDragOver(evt);
4493 _globalDragOver(evt);
4494 }
4495 break;
4496 case 'selectstart':
4497 evt.preventDefault();
4498 break;
4499 }
4500 },
4501 /**
4502 * Serializes the item into an array of string.
4503 * @returns {String[]}
4504 */
4505 toArray: function toArray() {
4506 var order = [],
4507 el,
4508 children = this.el.children,
4509 i = 0,
4510 n = children.length,
4511 options = this.options;
4512 for (; i < n; i++) {
4513 el = children[i];
4514 if (closest(el, options.draggable, this.el, false)) {
4515 order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
4516 }
4517 }
4518 return order;
4519 },
4520 /**
4521 * Sorts the elements according to the array.
4522 * @param {String[]} order order of the items
4523 */
4524 sort: function sort(order, useAnimation) {
4525 var items = {},
4526 rootEl = this.el;
4527 this.toArray().forEach(function (id, i) {
4528 var el = rootEl.children[i];
4529 if (closest(el, this.options.draggable, rootEl, false)) {
4530 items[id] = el;
4531 }
4532 }, this);
4533 useAnimation && this.captureAnimationState();
4534 order.forEach(function (id) {
4535 if (items[id]) {
4536 rootEl.removeChild(items[id]);
4537 rootEl.appendChild(items[id]);
4538 }
4539 });
4540 useAnimation && this.animateAll();
4541 },
4542 /**
4543 * Save the current sorting
4544 */
4545 save: function save() {
4546 var store = this.options.store;
4547 store && store.set && store.set(this);
4548 },
4549 /**
4550 * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
4551 * @param {HTMLElement} el
4552 * @param {String} [selector] default: `options.draggable`
4553 * @returns {HTMLElement|null}
4554 */
4555 closest: function closest$1(el, selector) {
4556 return closest(el, selector || this.options.draggable, this.el, false);
4557 },
4558 /**
4559 * Set/get option
4560 * @param {string} name
4561 * @param {*} [value]
4562 * @returns {*}
4563 */
4564 option: function option(name, value) {
4565 var options = this.options;
4566 if (value === void 0) {
4567 return options[name];
4568 } else {
4569 var modifiedValue = PluginManager.modifyOption(this, name, value);
4570 if (typeof modifiedValue !== 'undefined') {
4571 options[name] = modifiedValue;
4572 } else {
4573 options[name] = value;
4574 }
4575 if (name === 'group') {
4576 _prepareGroup(options);
4577 }
4578 }
4579 },
4580 /**
4581 * Destroy
4582 */
4583 destroy: function destroy() {
4584 pluginEvent('destroy', this);
4585 var el = this.el;
4586 el[expando] = null;
4587 off(el, 'mousedown', this._onTapStart);
4588 off(el, 'touchstart', this._onTapStart);
4589 off(el, 'pointerdown', this._onTapStart);
4590 if (this.nativeDraggable) {
4591 off(el, 'dragover', this);
4592 off(el, 'dragenter', this);
4593 }
4594 // Remove draggable attributes
4595 Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
4596 el.removeAttribute('draggable');
4597 });
4598 this._onDrop();
4599 this._disableDelayedDragEvents();
4600 sortables.splice(sortables.indexOf(this.el), 1);
4601 this.el = el = null;
4602 },
4603 _hideClone: function _hideClone() {
4604 if (!cloneHidden) {
4605 pluginEvent('hideClone', this);
4606 if (Sortable.eventCanceled) return;
4607 css(cloneEl, 'display', 'none');
4608 if (this.options.removeCloneOnHide && cloneEl.parentNode) {
4609 cloneEl.parentNode.removeChild(cloneEl);
4610 }
4611 cloneHidden = true;
4612 }
4613 },
4614 _showClone: function _showClone(putSortable) {
4615 if (putSortable.lastPutMode !== 'clone') {
4616 this._hideClone();
4617 return;
4618 }
4619 if (cloneHidden) {
4620 pluginEvent('showClone', this);
4621 if (Sortable.eventCanceled) return;
4622
4623 // show clone at dragEl or original position
4624 if (dragEl.parentNode == rootEl && !this.options.group.revertClone) {
4625 rootEl.insertBefore(cloneEl, dragEl);
4626 } else if (nextEl) {
4627 rootEl.insertBefore(cloneEl, nextEl);
4628 } else {
4629 rootEl.appendChild(cloneEl);
4630 }
4631 if (this.options.group.revertClone) {
4632 this.animate(dragEl, cloneEl);
4633 }
4634 css(cloneEl, 'display', '');
4635 cloneHidden = false;
4636 }
4637 }
4638 };
4639 function _globalDragOver( /**Event*/evt) {
4640 if (evt.dataTransfer) {
4641 evt.dataTransfer.dropEffect = 'move';
4642 }
4643 evt.cancelable && evt.preventDefault();
4644 }
4645 function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {
4646 var evt,
4647 sortable = fromEl[expando],
4648 onMoveFn = sortable.options.onMove,
4649 retVal;
4650 // Support for new CustomEvent feature
4651 if (window.CustomEvent && !IE11OrLess && !Edge) {
4652 evt = new CustomEvent('move', {
4653 bubbles: true,
4654 cancelable: true
4655 });
4656 } else {
4657 evt = document.createEvent('Event');
4658 evt.initEvent('move', true, true);
4659 }
4660 evt.to = toEl;
4661 evt.from = fromEl;
4662 evt.dragged = dragEl;
4663 evt.draggedRect = dragRect;
4664 evt.related = targetEl || toEl;
4665 evt.relatedRect = targetRect || getRect(toEl);
4666 evt.willInsertAfter = willInsertAfter;
4667 evt.originalEvent = originalEvent;
4668 fromEl.dispatchEvent(evt);
4669 if (onMoveFn) {
4670 retVal = onMoveFn.call(sortable, evt, originalEvent);
4671 }
4672 return retVal;
4673 }
4674 function _disableDraggable(el) {
4675 el.draggable = false;
4676 }
4677 function _unsilent() {
4678 _silent = false;
4679 }
4680 function _ghostIsFirst(evt, vertical, sortable) {
4681 var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true));
4682 var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);
4683 var spacer = 10;
4684 return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left;
4685 }
4686 function _ghostIsLast(evt, vertical, sortable) {
4687 var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable));
4688 var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);
4689 var spacer = 10;
4690 return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top;
4691 }
4692 function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {
4693 var mouseOnAxis = vertical ? evt.clientY : evt.clientX,
4694 targetLength = vertical ? targetRect.height : targetRect.width,
4695 targetS1 = vertical ? targetRect.top : targetRect.left,
4696 targetS2 = vertical ? targetRect.bottom : targetRect.right,
4697 invert = false;
4698 if (!invertSwap) {
4699 // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold
4700 if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {
4701 // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2
4702 // check if past first invert threshold on side opposite of lastDirection
4703 if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {
4704 // past first invert threshold, do not restrict inverted threshold to dragEl shadow
4705 pastFirstInvertThresh = true;
4706 }
4707 if (!pastFirstInvertThresh) {
4708 // dragEl shadow (target move distance shadow)
4709 if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow
4710 : mouseOnAxis > targetS2 - targetMoveDistance) {
4711 return -lastDirection;
4712 }
4713 } else {
4714 invert = true;
4715 }
4716 } else {
4717 // Regular
4718 if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {
4719 return _getInsertDirection(target);
4720 }
4721 }
4722 }
4723 invert = invert || invertSwap;
4724 if (invert) {
4725 // Invert of regular
4726 if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {
4727 return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;
4728 }
4729 }
4730 return 0;
4731 }
4732
4733 /**
4734 * Gets the direction dragEl must be swapped relative to target in order to make it
4735 * seem that dragEl has been "inserted" into that element's position
4736 * @param {HTMLElement} target The target whose position dragEl is being inserted at
4737 * @return {Number} Direction dragEl must be swapped
4738 */
4739 function _getInsertDirection(target) {
4740 if (index(dragEl) < index(target)) {
4741 return 1;
4742 } else {
4743 return -1;
4744 }
4745 }
4746
4747 /**
4748 * Generate id
4749 * @param {HTMLElement} el
4750 * @returns {String}
4751 * @private
4752 */
4753 function _generateId(el) {
4754 var str = el.tagName + el.className + el.src + el.href + el.textContent,
4755 i = str.length,
4756 sum = 0;
4757 while (i--) {
4758 sum += str.charCodeAt(i);
4759 }
4760 return sum.toString(36);
4761 }
4762 function _saveInputCheckedState(root) {
4763 savedInputChecked.length = 0;
4764 var inputs = root.getElementsByTagName('input');
4765 var idx = inputs.length;
4766 while (idx--) {
4767 var el = inputs[idx];
4768 el.checked && savedInputChecked.push(el);
4769 }
4770 }
4771 function _nextTick(fn) {
4772 return setTimeout(fn, 0);
4773 }
4774 function _cancelNextTick(id) {
4775 return clearTimeout(id);
4776 }
4777
4778 // Fixed #973:
4779 if (documentExists) {
4780 on(document, 'touchmove', function (evt) {
4781 if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {
4782 evt.preventDefault();
4783 }
4784 });
4785 }
4786
4787 // Export utils
4788 Sortable.utils = {
4789 on: on,
4790 off: off,
4791 css: css,
4792 find: find,
4793 is: function is(el, selector) {
4794 return !!closest(el, selector, el, false);
4795 },
4796 extend: extend,
4797 throttle: throttle,
4798 closest: closest,
4799 toggleClass: toggleClass,
4800 clone: clone,
4801 index: index,
4802 nextTick: _nextTick,
4803 cancelNextTick: _cancelNextTick,
4804 detectDirection: _detectDirection,
4805 getChild: getChild,
4806 expando: expando
4807 };
4808
4809 /**
4810 * Get the Sortable instance of an element
4811 * @param {HTMLElement} element The element
4812 * @return {Sortable|undefined} The instance of Sortable
4813 */
4814 Sortable.get = function (element) {
4815 return element[expando];
4816 };
4817
4818 /**
4819 * Mount a plugin to Sortable
4820 * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted
4821 */
4822 Sortable.mount = function () {
4823 for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {
4824 plugins[_key] = arguments[_key];
4825 }
4826 if (plugins[0].constructor === Array) plugins = plugins[0];
4827 plugins.forEach(function (plugin) {
4828 if (!plugin.prototype || !plugin.prototype.constructor) {
4829 throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(plugin));
4830 }
4831 if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils);
4832 PluginManager.mount(plugin);
4833 });
4834 };
4835
4836 /**
4837 * Create sortable instance
4838 * @param {HTMLElement} el
4839 * @param {Object} [options]
4840 */
4841 Sortable.create = function (el, options) {
4842 return new Sortable(el, options);
4843 };
4844
4845 // Export
4846 Sortable.version = version;
4847
4848 var autoScrolls = [],
4849 scrollEl,
4850 scrollRootEl,
4851 scrolling = false,
4852 lastAutoScrollX,
4853 lastAutoScrollY,
4854 touchEvt$1,
4855 pointerElemChangedInterval;
4856 function AutoScrollPlugin() {
4857 function AutoScroll() {
4858 this.defaults = {
4859 scroll: true,
4860 forceAutoScrollFallback: false,
4861 scrollSensitivity: 30,
4862 scrollSpeed: 10,
4863 bubbleScroll: true
4864 };
4865
4866 // Bind all private methods
4867 for (var fn in this) {
4868 if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
4869 this[fn] = this[fn].bind(this);
4870 }
4871 }
4872 }
4873 AutoScroll.prototype = {
4874 dragStarted: function dragStarted(_ref) {
4875 var originalEvent = _ref.originalEvent;
4876 if (this.sortable.nativeDraggable) {
4877 on(document, 'dragover', this._handleAutoScroll);
4878 } else {
4879 if (this.options.supportPointer) {
4880 on(document, 'pointermove', this._handleFallbackAutoScroll);
4881 } else if (originalEvent.touches) {
4882 on(document, 'touchmove', this._handleFallbackAutoScroll);
4883 } else {
4884 on(document, 'mousemove', this._handleFallbackAutoScroll);
4885 }
4886 }
4887 },
4888 dragOverCompleted: function dragOverCompleted(_ref2) {
4889 var originalEvent = _ref2.originalEvent;
4890 // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)
4891 if (!this.options.dragOverBubble && !originalEvent.rootEl) {
4892 this._handleAutoScroll(originalEvent);
4893 }
4894 },
4895 drop: function drop() {
4896 if (this.sortable.nativeDraggable) {
4897 off(document, 'dragover', this._handleAutoScroll);
4898 } else {
4899 off(document, 'pointermove', this._handleFallbackAutoScroll);
4900 off(document, 'touchmove', this._handleFallbackAutoScroll);
4901 off(document, 'mousemove', this._handleFallbackAutoScroll);
4902 }
4903 clearPointerElemChangedInterval();
4904 clearAutoScrolls();
4905 cancelThrottle();
4906 },
4907 nulling: function nulling() {
4908 touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;
4909 autoScrolls.length = 0;
4910 },
4911 _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {
4912 this._handleAutoScroll(evt, true);
4913 },
4914 _handleAutoScroll: function _handleAutoScroll(evt, fallback) {
4915 var _this = this;
4916 var x = (evt.touches ? evt.touches[0] : evt).clientX,
4917 y = (evt.touches ? evt.touches[0] : evt).clientY,
4918 elem = document.elementFromPoint(x, y);
4919 touchEvt$1 = evt;
4920
4921 // IE does not seem to have native autoscroll,
4922 // Edge's autoscroll seems too conditional,
4923 // MACOS Safari does not have autoscroll,
4924 // Firefox and Chrome are good
4925 if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) {
4926 autoScroll(evt, this.options, elem, fallback);
4927
4928 // Listener for pointer element change
4929 var ogElemScroller = getParentAutoScrollElement(elem, true);
4930 if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {
4931 pointerElemChangedInterval && clearPointerElemChangedInterval();
4932 // Detect for pointer elem change, emulating native DnD behaviour
4933 pointerElemChangedInterval = setInterval(function () {
4934 var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);
4935 if (newElem !== ogElemScroller) {
4936 ogElemScroller = newElem;
4937 clearAutoScrolls();
4938 }
4939 autoScroll(evt, _this.options, newElem, fallback);
4940 }, 10);
4941 lastAutoScrollX = x;
4942 lastAutoScrollY = y;
4943 }
4944 } else {
4945 // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll
4946 if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {
4947 clearAutoScrolls();
4948 return;
4949 }
4950 autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);
4951 }
4952 }
4953 };
4954 return _extends(AutoScroll, {
4955 pluginName: 'scroll',
4956 initializeByDefault: true
4957 });
4958 }
4959 function clearAutoScrolls() {
4960 autoScrolls.forEach(function (autoScroll) {
4961 clearInterval(autoScroll.pid);
4962 });
4963 autoScrolls = [];
4964 }
4965 function clearPointerElemChangedInterval() {
4966 clearInterval(pointerElemChangedInterval);
4967 }
4968 var autoScroll = throttle(function (evt, options, rootEl, isFallback) {
4969 // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
4970 if (!options.scroll) return;
4971 var x = (evt.touches ? evt.touches[0] : evt).clientX,
4972 y = (evt.touches ? evt.touches[0] : evt).clientY,
4973 sens = options.scrollSensitivity,
4974 speed = options.scrollSpeed,
4975 winScroller = getWindowScrollingElement();
4976 var scrollThisInstance = false,
4977 scrollCustomFn;
4978
4979 // New scroll root, set scrollEl
4980 if (scrollRootEl !== rootEl) {
4981 scrollRootEl = rootEl;
4982 clearAutoScrolls();
4983 scrollEl = options.scroll;
4984 scrollCustomFn = options.scrollFn;
4985 if (scrollEl === true) {
4986 scrollEl = getParentAutoScrollElement(rootEl, true);
4987 }
4988 }
4989 var layersOut = 0;
4990 var currentParent = scrollEl;
4991 do {
4992 var el = currentParent,
4993 rect = getRect(el),
4994 top = rect.top,
4995 bottom = rect.bottom,
4996 left = rect.left,
4997 right = rect.right,
4998 width = rect.width,
4999 height = rect.height,
5000 canScrollX = void 0,
5001 canScrollY = void 0,
5002 scrollWidth = el.scrollWidth,
5003 scrollHeight = el.scrollHeight,
5004 elCSS = css(el),
5005 scrollPosX = el.scrollLeft,
5006 scrollPosY = el.scrollTop;
5007 if (el === winScroller) {
5008 canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');
5009 canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');
5010 } else {
5011 canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');
5012 canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');
5013 }
5014 var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX);
5015 var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY);
5016 if (!autoScrolls[layersOut]) {
5017 for (var i = 0; i <= layersOut; i++) {
5018 if (!autoScrolls[i]) {
5019 autoScrolls[i] = {};
5020 }
5021 }
5022 }
5023 if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {
5024 autoScrolls[layersOut].el = el;
5025 autoScrolls[layersOut].vx = vx;
5026 autoScrolls[layersOut].vy = vy;
5027 clearInterval(autoScrolls[layersOut].pid);
5028 if (vx != 0 || vy != 0) {
5029 scrollThisInstance = true;
5030 /* jshint loopfunc:true */
5031 autoScrolls[layersOut].pid = setInterval(function () {
5032 // emulate drag over during autoscroll (fallback), emulating native DnD behaviour
5033 if (isFallback && this.layer === 0) {
5034 Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely
5035 }
5036 var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;
5037 var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;
5038 if (typeof scrollCustomFn === 'function') {
5039 if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {
5040 return;
5041 }
5042 }
5043 scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);
5044 }.bind({
5045 layer: layersOut
5046 }), 24);
5047 }
5048 }
5049 layersOut++;
5050 } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));
5051 scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not
5052 }, 30);
5053
5054 var drop = function drop(_ref) {
5055 var originalEvent = _ref.originalEvent,
5056 putSortable = _ref.putSortable,
5057 dragEl = _ref.dragEl,
5058 activeSortable = _ref.activeSortable,
5059 dispatchSortableEvent = _ref.dispatchSortableEvent,
5060 hideGhostForTarget = _ref.hideGhostForTarget,
5061 unhideGhostForTarget = _ref.unhideGhostForTarget;
5062 if (!originalEvent) return;
5063 var toSortable = putSortable || activeSortable;
5064 hideGhostForTarget();
5065 var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent;
5066 var target = document.elementFromPoint(touch.clientX, touch.clientY);
5067 unhideGhostForTarget();
5068 if (toSortable && !toSortable.el.contains(target)) {
5069 dispatchSortableEvent('spill');
5070 this.onSpill({
5071 dragEl: dragEl,
5072 putSortable: putSortable
5073 });
5074 }
5075 };
5076 function Revert() {}
5077 Revert.prototype = {
5078 startIndex: null,
5079 dragStart: function dragStart(_ref2) {
5080 var oldDraggableIndex = _ref2.oldDraggableIndex;
5081 this.startIndex = oldDraggableIndex;
5082 },
5083 onSpill: function onSpill(_ref3) {
5084 var dragEl = _ref3.dragEl,
5085 putSortable = _ref3.putSortable;
5086 this.sortable.captureAnimationState();
5087 if (putSortable) {
5088 putSortable.captureAnimationState();
5089 }
5090 var nextSibling = getChild(this.sortable.el, this.startIndex, this.options);
5091 if (nextSibling) {
5092 this.sortable.el.insertBefore(dragEl, nextSibling);
5093 } else {
5094 this.sortable.el.appendChild(dragEl);
5095 }
5096 this.sortable.animateAll();
5097 if (putSortable) {
5098 putSortable.animateAll();
5099 }
5100 },
5101 drop: drop
5102 };
5103 _extends(Revert, {
5104 pluginName: 'revertOnSpill'
5105 });
5106 function Remove() {}
5107 Remove.prototype = {
5108 onSpill: function onSpill(_ref4) {
5109 var dragEl = _ref4.dragEl,
5110 putSortable = _ref4.putSortable;
5111 var parentSortable = putSortable || this.sortable;
5112 parentSortable.captureAnimationState();
5113 dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
5114 parentSortable.animateAll();
5115 },
5116 drop: drop
5117 };
5118 _extends(Remove, {
5119 pluginName: 'removeOnSpill'
5120 });
5121
5122 var lastSwapEl;
5123 function SwapPlugin() {
5124 function Swap() {
5125 this.defaults = {
5126 swapClass: 'sortable-swap-highlight'
5127 };
5128 }
5129 Swap.prototype = {
5130 dragStart: function dragStart(_ref) {
5131 var dragEl = _ref.dragEl;
5132 lastSwapEl = dragEl;
5133 },
5134 dragOverValid: function dragOverValid(_ref2) {
5135 var completed = _ref2.completed,
5136 target = _ref2.target,
5137 onMove = _ref2.onMove,
5138 activeSortable = _ref2.activeSortable,
5139 changed = _ref2.changed,
5140 cancel = _ref2.cancel;
5141 if (!activeSortable.options.swap) return;
5142 var el = this.sortable.el,
5143 options = this.options;
5144 if (target && target !== el) {
5145 var prevSwapEl = lastSwapEl;
5146 if (onMove(target) !== false) {
5147 toggleClass(target, options.swapClass, true);
5148 lastSwapEl = target;
5149 } else {
5150 lastSwapEl = null;
5151 }
5152 if (prevSwapEl && prevSwapEl !== lastSwapEl) {
5153 toggleClass(prevSwapEl, options.swapClass, false);
5154 }
5155 }
5156 changed();
5157 completed(true);
5158 cancel();
5159 },
5160 drop: function drop(_ref3) {
5161 var activeSortable = _ref3.activeSortable,
5162 putSortable = _ref3.putSortable,
5163 dragEl = _ref3.dragEl;
5164 var toSortable = putSortable || this.sortable;
5165 var options = this.options;
5166 lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);
5167 if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {
5168 if (dragEl !== lastSwapEl) {
5169 toSortable.captureAnimationState();
5170 if (toSortable !== activeSortable) activeSortable.captureAnimationState();
5171 swapNodes(dragEl, lastSwapEl);
5172 toSortable.animateAll();
5173 if (toSortable !== activeSortable) activeSortable.animateAll();
5174 }
5175 }
5176 },
5177 nulling: function nulling() {
5178 lastSwapEl = null;
5179 }
5180 };
5181 return _extends(Swap, {
5182 pluginName: 'swap',
5183 eventProperties: function eventProperties() {
5184 return {
5185 swapItem: lastSwapEl
5186 };
5187 }
5188 });
5189 }
5190 function swapNodes(n1, n2) {
5191 var p1 = n1.parentNode,
5192 p2 = n2.parentNode,
5193 i1,
5194 i2;
5195 if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;
5196 i1 = index(n1);
5197 i2 = index(n2);
5198 if (p1.isEqualNode(p2) && i1 < i2) {
5199 i2++;
5200 }
5201 p1.insertBefore(n2, p1.children[i1]);
5202 p2.insertBefore(n1, p2.children[i2]);
5203 }
5204
5205 var multiDragElements = [],
5206 multiDragClones = [],
5207 lastMultiDragSelect,
5208 // for selection with modifier key down (SHIFT)
5209 multiDragSortable,
5210 initialFolding = false,
5211 // Initial multi-drag fold when drag started
5212 folding = false,
5213 // Folding any other time
5214 dragStarted = false,
5215 dragEl$1,
5216 clonesFromRect,
5217 clonesHidden;
5218 function MultiDragPlugin() {
5219 function MultiDrag(sortable) {
5220 // Bind all private methods
5221 for (var fn in this) {
5222 if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
5223 this[fn] = this[fn].bind(this);
5224 }
5225 }
5226 if (!sortable.options.avoidImplicitDeselect) {
5227 if (sortable.options.supportPointer) {
5228 on(document, 'pointerup', this._deselectMultiDrag);
5229 } else {
5230 on(document, 'mouseup', this._deselectMultiDrag);
5231 on(document, 'touchend', this._deselectMultiDrag);
5232 }
5233 }
5234 on(document, 'keydown', this._checkKeyDown);
5235 on(document, 'keyup', this._checkKeyUp);
5236 this.defaults = {
5237 selectedClass: 'sortable-selected',
5238 multiDragKey: null,
5239 avoidImplicitDeselect: false,
5240 setData: function setData(dataTransfer, dragEl) {
5241 var data = '';
5242 if (multiDragElements.length && multiDragSortable === sortable) {
5243 multiDragElements.forEach(function (multiDragElement, i) {
5244 data += (!i ? '' : ', ') + multiDragElement.textContent;
5245 });
5246 } else {
5247 data = dragEl.textContent;
5248 }
5249 dataTransfer.setData('Text', data);
5250 }
5251 };
5252 }
5253 MultiDrag.prototype = {
5254 multiDragKeyDown: false,
5255 isMultiDrag: false,
5256 delayStartGlobal: function delayStartGlobal(_ref) {
5257 var dragged = _ref.dragEl;
5258 dragEl$1 = dragged;
5259 },
5260 delayEnded: function delayEnded() {
5261 this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1);
5262 },
5263 setupClone: function setupClone(_ref2) {
5264 var sortable = _ref2.sortable,
5265 cancel = _ref2.cancel;
5266 if (!this.isMultiDrag) return;
5267 for (var i = 0; i < multiDragElements.length; i++) {
5268 multiDragClones.push(clone(multiDragElements[i]));
5269 multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex;
5270 multiDragClones[i].draggable = false;
5271 multiDragClones[i].style['will-change'] = '';
5272 toggleClass(multiDragClones[i], this.options.selectedClass, false);
5273 multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false);
5274 }
5275 sortable._hideClone();
5276 cancel();
5277 },
5278 clone: function clone(_ref3) {
5279 var sortable = _ref3.sortable,
5280 rootEl = _ref3.rootEl,
5281 dispatchSortableEvent = _ref3.dispatchSortableEvent,
5282 cancel = _ref3.cancel;
5283 if (!this.isMultiDrag) return;
5284 if (!this.options.removeCloneOnHide) {
5285 if (multiDragElements.length && multiDragSortable === sortable) {
5286 insertMultiDragClones(true, rootEl);
5287 dispatchSortableEvent('clone');
5288 cancel();
5289 }
5290 }
5291 },
5292 showClone: function showClone(_ref4) {
5293 var cloneNowShown = _ref4.cloneNowShown,
5294 rootEl = _ref4.rootEl,
5295 cancel = _ref4.cancel;
5296 if (!this.isMultiDrag) return;
5297 insertMultiDragClones(false, rootEl);
5298 multiDragClones.forEach(function (clone) {
5299 css(clone, 'display', '');
5300 });
5301 cloneNowShown();
5302 clonesHidden = false;
5303 cancel();
5304 },
5305 hideClone: function hideClone(_ref5) {
5306 var _this = this;
5307 var sortable = _ref5.sortable,
5308 cloneNowHidden = _ref5.cloneNowHidden,
5309 cancel = _ref5.cancel;
5310 if (!this.isMultiDrag) return;
5311 multiDragClones.forEach(function (clone) {
5312 css(clone, 'display', 'none');
5313 if (_this.options.removeCloneOnHide && clone.parentNode) {
5314 clone.parentNode.removeChild(clone);
5315 }
5316 });
5317 cloneNowHidden();
5318 clonesHidden = true;
5319 cancel();
5320 },
5321 dragStartGlobal: function dragStartGlobal(_ref6) {
5322 var sortable = _ref6.sortable;
5323 if (!this.isMultiDrag && multiDragSortable) {
5324 multiDragSortable.multiDrag._deselectMultiDrag();
5325 }
5326 multiDragElements.forEach(function (multiDragElement) {
5327 multiDragElement.sortableIndex = index(multiDragElement);
5328 });
5329
5330 // Sort multi-drag elements
5331 multiDragElements = multiDragElements.sort(function (a, b) {
5332 return a.sortableIndex - b.sortableIndex;
5333 });
5334 dragStarted = true;
5335 },
5336 dragStarted: function dragStarted(_ref7) {
5337 var _this2 = this;
5338 var sortable = _ref7.sortable;
5339 if (!this.isMultiDrag) return;
5340 if (this.options.sort) {
5341 // Capture rects,
5342 // hide multi drag elements (by positioning them absolute),
5343 // set multi drag elements rects to dragRect,
5344 // show multi drag elements,
5345 // animate to rects,
5346 // unset rects & remove from DOM
5347
5348 sortable.captureAnimationState();
5349 if (this.options.animation) {
5350 multiDragElements.forEach(function (multiDragElement) {
5351 if (multiDragElement === dragEl$1) return;
5352 css(multiDragElement, 'position', 'absolute');
5353 });
5354 var dragRect = getRect(dragEl$1, false, true, true);
5355 multiDragElements.forEach(function (multiDragElement) {
5356 if (multiDragElement === dragEl$1) return;
5357 setRect(multiDragElement, dragRect);
5358 });
5359 folding = true;
5360 initialFolding = true;
5361 }
5362 }
5363 sortable.animateAll(function () {
5364 folding = false;
5365 initialFolding = false;
5366 if (_this2.options.animation) {
5367 multiDragElements.forEach(function (multiDragElement) {
5368 unsetRect(multiDragElement);
5369 });
5370 }
5371
5372 // Remove all auxiliary multidrag items from el, if sorting enabled
5373 if (_this2.options.sort) {
5374 removeMultiDragElements();
5375 }
5376 });
5377 },
5378 dragOver: function dragOver(_ref8) {
5379 var target = _ref8.target,
5380 completed = _ref8.completed,
5381 cancel = _ref8.cancel;
5382 if (folding && ~multiDragElements.indexOf(target)) {
5383 completed(false);
5384 cancel();
5385 }
5386 },
5387 revert: function revert(_ref9) {
5388 var fromSortable = _ref9.fromSortable,
5389 rootEl = _ref9.rootEl,
5390 sortable = _ref9.sortable,
5391 dragRect = _ref9.dragRect;
5392 if (multiDragElements.length > 1) {
5393 // Setup unfold animation
5394 multiDragElements.forEach(function (multiDragElement) {
5395 sortable.addAnimationState({
5396 target: multiDragElement,
5397 rect: folding ? getRect(multiDragElement) : dragRect
5398 });
5399 unsetRect(multiDragElement);
5400 multiDragElement.fromRect = dragRect;
5401 fromSortable.removeAnimationState(multiDragElement);
5402 });
5403 folding = false;
5404 insertMultiDragElements(!this.options.removeCloneOnHide, rootEl);
5405 }
5406 },
5407 dragOverCompleted: function dragOverCompleted(_ref10) {
5408 var sortable = _ref10.sortable,
5409 isOwner = _ref10.isOwner,
5410 insertion = _ref10.insertion,
5411 activeSortable = _ref10.activeSortable,
5412 parentEl = _ref10.parentEl,
5413 putSortable = _ref10.putSortable;
5414 var options = this.options;
5415 if (insertion) {
5416 // Clones must be hidden before folding animation to capture dragRectAbsolute properly
5417 if (isOwner) {
5418 activeSortable._hideClone();
5419 }
5420 initialFolding = false;
5421 // If leaving sort:false root, or already folding - Fold to new location
5422 if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) {
5423 // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible
5424 var dragRectAbsolute = getRect(dragEl$1, false, true, true);
5425 multiDragElements.forEach(function (multiDragElement) {
5426 if (multiDragElement === dragEl$1) return;
5427 setRect(multiDragElement, dragRectAbsolute);
5428
5429 // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted
5430 // while folding, and so that we can capture them again because old sortable will no longer be fromSortable
5431 parentEl.appendChild(multiDragElement);
5432 });
5433 folding = true;
5434 }
5435
5436 // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out
5437 if (!isOwner) {
5438 // Only remove if not folding (folding will remove them anyways)
5439 if (!folding) {
5440 removeMultiDragElements();
5441 }
5442 if (multiDragElements.length > 1) {
5443 var clonesHiddenBefore = clonesHidden;
5444 activeSortable._showClone(sortable);
5445
5446 // Unfold animation for clones if showing from hidden
5447 if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) {
5448 multiDragClones.forEach(function (clone) {
5449 activeSortable.addAnimationState({
5450 target: clone,
5451 rect: clonesFromRect
5452 });
5453 clone.fromRect = clonesFromRect;
5454 clone.thisAnimationDuration = null;
5455 });
5456 }
5457 } else {
5458 activeSortable._showClone(sortable);
5459 }
5460 }
5461 }
5462 },
5463 dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) {
5464 var dragRect = _ref11.dragRect,
5465 isOwner = _ref11.isOwner,
5466 activeSortable = _ref11.activeSortable;
5467 multiDragElements.forEach(function (multiDragElement) {
5468 multiDragElement.thisAnimationDuration = null;
5469 });
5470 if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) {
5471 clonesFromRect = _extends({}, dragRect);
5472 var dragMatrix = matrix(dragEl$1, true);
5473 clonesFromRect.top -= dragMatrix.f;
5474 clonesFromRect.left -= dragMatrix.e;
5475 }
5476 },
5477 dragOverAnimationComplete: function dragOverAnimationComplete() {
5478 if (folding) {
5479 folding = false;
5480 removeMultiDragElements();
5481 }
5482 },
5483 drop: function drop(_ref12) {
5484 var evt = _ref12.originalEvent,
5485 rootEl = _ref12.rootEl,
5486 parentEl = _ref12.parentEl,
5487 sortable = _ref12.sortable,
5488 dispatchSortableEvent = _ref12.dispatchSortableEvent,
5489 oldIndex = _ref12.oldIndex,
5490 putSortable = _ref12.putSortable;
5491 var toSortable = putSortable || this.sortable;
5492 if (!evt) return;
5493 var options = this.options,
5494 children = parentEl.children;
5495
5496 // Multi-drag selection
5497 if (!dragStarted) {
5498 if (options.multiDragKey && !this.multiDragKeyDown) {
5499 this._deselectMultiDrag();
5500 }
5501 toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1));
5502 if (!~multiDragElements.indexOf(dragEl$1)) {
5503 multiDragElements.push(dragEl$1);
5504 dispatchEvent({
5505 sortable: sortable,
5506 rootEl: rootEl,
5507 name: 'select',
5508 targetEl: dragEl$1,
5509 originalEvent: evt
5510 });
5511
5512 // Modifier activated, select from last to dragEl
5513 if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) {
5514 var lastIndex = index(lastMultiDragSelect),
5515 currentIndex = index(dragEl$1);
5516 if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) {
5517 (function () {
5518 // Must include lastMultiDragSelect (select it), in case modified selection from no selection
5519 // (but previous selection existed)
5520 var n, i;
5521 if (currentIndex > lastIndex) {
5522 i = lastIndex;
5523 n = currentIndex;
5524 } else {
5525 i = currentIndex;
5526 n = lastIndex + 1;
5527 }
5528 var filter = options.filter;
5529 for (; i < n; i++) {
5530 if (~multiDragElements.indexOf(children[i])) continue;
5531 // Check if element is draggable
5532 if (!closest(children[i], options.draggable, parentEl, false)) continue;
5533 // Check if element is filtered
5534 var filtered = filter && (typeof filter === 'function' ? filter.call(sortable, evt, children[i], sortable) : filter.split(',').some(function (criteria) {
5535 return closest(children[i], criteria.trim(), parentEl, false);
5536 }));
5537 if (filtered) continue;
5538 toggleClass(children[i], options.selectedClass, true);
5539 multiDragElements.push(children[i]);
5540 dispatchEvent({
5541 sortable: sortable,
5542 rootEl: rootEl,
5543 name: 'select',
5544 targetEl: children[i],
5545 originalEvent: evt
5546 });
5547 }
5548 })();
5549 }
5550 } else {
5551 lastMultiDragSelect = dragEl$1;
5552 }
5553 multiDragSortable = toSortable;
5554 } else {
5555 multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1);
5556 lastMultiDragSelect = null;
5557 dispatchEvent({
5558 sortable: sortable,
5559 rootEl: rootEl,
5560 name: 'deselect',
5561 targetEl: dragEl$1,
5562 originalEvent: evt
5563 });
5564 }
5565 }
5566
5567 // Multi-drag drop
5568 if (dragStarted && this.isMultiDrag) {
5569 folding = false;
5570 // Do not "unfold" after around dragEl if reverted
5571 if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) {
5572 var dragRect = getRect(dragEl$1),
5573 multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')');
5574 if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null;
5575 toSortable.captureAnimationState();
5576 if (!initialFolding) {
5577 if (options.animation) {
5578 dragEl$1.fromRect = dragRect;
5579 multiDragElements.forEach(function (multiDragElement) {
5580 multiDragElement.thisAnimationDuration = null;
5581 if (multiDragElement !== dragEl$1) {
5582 var rect = folding ? getRect(multiDragElement) : dragRect;
5583 multiDragElement.fromRect = rect;
5584
5585 // Prepare unfold animation
5586 toSortable.addAnimationState({
5587 target: multiDragElement,
5588 rect: rect
5589 });
5590 }
5591 });
5592 }
5593
5594 // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert
5595 // properly they must all be removed
5596 removeMultiDragElements();
5597 multiDragElements.forEach(function (multiDragElement) {
5598 if (children[multiDragIndex]) {
5599 parentEl.insertBefore(multiDragElement, children[multiDragIndex]);
5600 } else {
5601 parentEl.appendChild(multiDragElement);
5602 }
5603 multiDragIndex++;
5604 });
5605
5606 // If initial folding is done, the elements may have changed position because they are now
5607 // unfolding around dragEl, even though dragEl may not have his index changed, so update event
5608 // must be fired here as Sortable will not.
5609 if (oldIndex === index(dragEl$1)) {
5610 var update = false;
5611 multiDragElements.forEach(function (multiDragElement) {
5612 if (multiDragElement.sortableIndex !== index(multiDragElement)) {
5613 update = true;
5614 return;
5615 }
5616 });
5617 if (update) {
5618 dispatchSortableEvent('update');
5619 dispatchSortableEvent('sort');
5620 }
5621 }
5622 }
5623
5624 // Must be done after capturing individual rects (scroll bar)
5625 multiDragElements.forEach(function (multiDragElement) {
5626 unsetRect(multiDragElement);
5627 });
5628 toSortable.animateAll();
5629 }
5630 multiDragSortable = toSortable;
5631 }
5632
5633 // Remove clones if necessary
5634 if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
5635 multiDragClones.forEach(function (clone) {
5636 clone.parentNode && clone.parentNode.removeChild(clone);
5637 });
5638 }
5639 },
5640 nullingGlobal: function nullingGlobal() {
5641 this.isMultiDrag = dragStarted = false;
5642 multiDragClones.length = 0;
5643 },
5644 destroyGlobal: function destroyGlobal() {
5645 this._deselectMultiDrag();
5646 off(document, 'pointerup', this._deselectMultiDrag);
5647 off(document, 'mouseup', this._deselectMultiDrag);
5648 off(document, 'touchend', this._deselectMultiDrag);
5649 off(document, 'keydown', this._checkKeyDown);
5650 off(document, 'keyup', this._checkKeyUp);
5651 },
5652 _deselectMultiDrag: function _deselectMultiDrag(evt) {
5653 if (typeof dragStarted !== "undefined" && dragStarted) return;
5654
5655 // Only deselect if selection is in this sortable
5656 if (multiDragSortable !== this.sortable) return;
5657
5658 // Only deselect if target is not item in this sortable
5659 if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return;
5660
5661 // Only deselect if left click
5662 if (evt && evt.button !== 0) return;
5663 while (multiDragElements.length) {
5664 var el = multiDragElements[0];
5665 toggleClass(el, this.options.selectedClass, false);
5666 multiDragElements.shift();
5667 dispatchEvent({
5668 sortable: this.sortable,
5669 rootEl: this.sortable.el,
5670 name: 'deselect',
5671 targetEl: el,
5672 originalEvent: evt
5673 });
5674 }
5675 },
5676 _checkKeyDown: function _checkKeyDown(evt) {
5677 if (evt.key === this.options.multiDragKey) {
5678 this.multiDragKeyDown = true;
5679 }
5680 },
5681 _checkKeyUp: function _checkKeyUp(evt) {
5682 if (evt.key === this.options.multiDragKey) {
5683 this.multiDragKeyDown = false;
5684 }
5685 }
5686 };
5687 return _extends(MultiDrag, {
5688 // Static methods & properties
5689 pluginName: 'multiDrag',
5690 utils: {
5691 /**
5692 * Selects the provided multi-drag item
5693 * @param {HTMLElement} el The element to be selected
5694 */
5695 select: function select(el) {
5696 var sortable = el.parentNode[expando];
5697 if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return;
5698 if (multiDragSortable && multiDragSortable !== sortable) {
5699 multiDragSortable.multiDrag._deselectMultiDrag();
5700 multiDragSortable = sortable;
5701 }
5702 toggleClass(el, sortable.options.selectedClass, true);
5703 multiDragElements.push(el);
5704 },
5705 /**
5706 * Deselects the provided multi-drag item
5707 * @param {HTMLElement} el The element to be deselected
5708 */
5709 deselect: function deselect(el) {
5710 var sortable = el.parentNode[expando],
5711 index = multiDragElements.indexOf(el);
5712 if (!sortable || !sortable.options.multiDrag || !~index) return;
5713 toggleClass(el, sortable.options.selectedClass, false);
5714 multiDragElements.splice(index, 1);
5715 }
5716 },
5717 eventProperties: function eventProperties() {
5718 var _this3 = this;
5719 var oldIndicies = [],
5720 newIndicies = [];
5721 multiDragElements.forEach(function (multiDragElement) {
5722 oldIndicies.push({
5723 multiDragElement: multiDragElement,
5724 index: multiDragElement.sortableIndex
5725 });
5726
5727 // multiDragElements will already be sorted if folding
5728 var newIndex;
5729 if (folding && multiDragElement !== dragEl$1) {
5730 newIndex = -1;
5731 } else if (folding) {
5732 newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')');
5733 } else {
5734 newIndex = index(multiDragElement);
5735 }
5736 newIndicies.push({
5737 multiDragElement: multiDragElement,
5738 index: newIndex
5739 });
5740 });
5741 return {
5742 items: _toConsumableArray(multiDragElements),
5743 clones: [].concat(multiDragClones),
5744 oldIndicies: oldIndicies,
5745 newIndicies: newIndicies
5746 };
5747 },
5748 optionListeners: {
5749 multiDragKey: function multiDragKey(key) {
5750 key = key.toLowerCase();
5751 if (key === 'ctrl') {
5752 key = 'Control';
5753 } else if (key.length > 1) {
5754 key = key.charAt(0).toUpperCase() + key.substr(1);
5755 }
5756 return key;
5757 }
5758 }
5759 });
5760 }
5761 function insertMultiDragElements(clonesInserted, rootEl) {
5762 multiDragElements.forEach(function (multiDragElement, i) {
5763 var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)];
5764 if (target) {
5765 rootEl.insertBefore(multiDragElement, target);
5766 } else {
5767 rootEl.appendChild(multiDragElement);
5768 }
5769 });
5770 }
5771
5772 /**
5773 * Insert multi-drag clones
5774 * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted
5775 * @param {HTMLElement} rootEl
5776 */
5777 function insertMultiDragClones(elementsInserted, rootEl) {
5778 multiDragClones.forEach(function (clone, i) {
5779 var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)];
5780 if (target) {
5781 rootEl.insertBefore(clone, target);
5782 } else {
5783 rootEl.appendChild(clone);
5784 }
5785 });
5786 }
5787 function removeMultiDragElements() {
5788 multiDragElements.forEach(function (multiDragElement) {
5789 if (multiDragElement === dragEl$1) return;
5790 multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement);
5791 });
5792 }
5793
5794 Sortable.mount(new AutoScrollPlugin());
5795 Sortable.mount(Remove, Revert);
5796
5797 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Sortable);
5798
5799
5800
5801 /***/ },
5802
5803 /***/ "./node_modules/toastify-js/src/toastify.css"
5804 /*!***************************************************!*\
5805 !*** ./node_modules/toastify-js/src/toastify.css ***!
5806 \***************************************************/
5807 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
5808
5809 "use strict";
5810 __webpack_require__.r(__webpack_exports__);
5811 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5812 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
5813 /* harmony export */ });
5814 /* 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");
5815 /* 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__);
5816 /* 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");
5817 /* 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__);
5818 /* 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");
5819 /* 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__);
5820 /* 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");
5821 /* 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__);
5822 /* 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");
5823 /* 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__);
5824 /* 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");
5825 /* 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__);
5826 /* 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");
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838 var options = {};
5839
5840 options.styleTagTransform = (_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
5841 options.setAttributes = (_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());
5842
5843 options.insert = _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
5844
5845 options.domAPI = (_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
5846 options.insertStyleElement = (_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());
5847
5848 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);
5849
5850
5851
5852
5853 /* 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);
5854
5855
5856 /***/ },
5857
5858 /***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js"
5859 /*!****************************************************************************!*\
5860 !*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
5861 \****************************************************************************/
5862 (module) {
5863
5864 "use strict";
5865
5866
5867 var stylesInDOM = [];
5868 function getIndexByIdentifier(identifier) {
5869 var result = -1;
5870 for (var i = 0; i < stylesInDOM.length; i++) {
5871 if (stylesInDOM[i].identifier === identifier) {
5872 result = i;
5873 break;
5874 }
5875 }
5876 return result;
5877 }
5878 function modulesToDom(list, options) {
5879 var idCountMap = {};
5880 var identifiers = [];
5881 for (var i = 0; i < list.length; i++) {
5882 var item = list[i];
5883 var id = options.base ? item[0] + options.base : item[0];
5884 var count = idCountMap[id] || 0;
5885 var identifier = "".concat(id, " ").concat(count);
5886 idCountMap[id] = count + 1;
5887 var indexByIdentifier = getIndexByIdentifier(identifier);
5888 var obj = {
5889 css: item[1],
5890 media: item[2],
5891 sourceMap: item[3],
5892 supports: item[4],
5893 layer: item[5]
5894 };
5895 if (indexByIdentifier !== -1) {
5896 stylesInDOM[indexByIdentifier].references++;
5897 stylesInDOM[indexByIdentifier].updater(obj);
5898 } else {
5899 var updater = addElementStyle(obj, options);
5900 options.byIndex = i;
5901 stylesInDOM.splice(i, 0, {
5902 identifier: identifier,
5903 updater: updater,
5904 references: 1
5905 });
5906 }
5907 identifiers.push(identifier);
5908 }
5909 return identifiers;
5910 }
5911 function addElementStyle(obj, options) {
5912 var api = options.domAPI(options);
5913 api.update(obj);
5914 var updater = function updater(newObj) {
5915 if (newObj) {
5916 if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap && newObj.supports === obj.supports && newObj.layer === obj.layer) {
5917 return;
5918 }
5919 api.update(obj = newObj);
5920 } else {
5921 api.remove();
5922 }
5923 };
5924 return updater;
5925 }
5926 module.exports = function (list, options) {
5927 options = options || {};
5928 list = list || [];
5929 var lastIdentifiers = modulesToDom(list, options);
5930 return function update(newList) {
5931 newList = newList || [];
5932 for (var i = 0; i < lastIdentifiers.length; i++) {
5933 var identifier = lastIdentifiers[i];
5934 var index = getIndexByIdentifier(identifier);
5935 stylesInDOM[index].references--;
5936 }
5937 var newLastIdentifiers = modulesToDom(newList, options);
5938 for (var _i = 0; _i < lastIdentifiers.length; _i++) {
5939 var _identifier = lastIdentifiers[_i];
5940 var _index = getIndexByIdentifier(_identifier);
5941 if (stylesInDOM[_index].references === 0) {
5942 stylesInDOM[_index].updater();
5943 stylesInDOM.splice(_index, 1);
5944 }
5945 }
5946 lastIdentifiers = newLastIdentifiers;
5947 };
5948 };
5949
5950 /***/ },
5951
5952 /***/ "./node_modules/style-loader/dist/runtime/insertBySelector.js"
5953 /*!********************************************************************!*\
5954 !*** ./node_modules/style-loader/dist/runtime/insertBySelector.js ***!
5955 \********************************************************************/
5956 (module) {
5957
5958 "use strict";
5959
5960
5961 var memo = {};
5962
5963 /* istanbul ignore next */
5964 function getTarget(target) {
5965 if (typeof memo[target] === "undefined") {
5966 var styleTarget = document.querySelector(target);
5967
5968 // Special case to return head of iframe instead of iframe itself
5969 if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
5970 try {
5971 // This will throw an exception if access to iframe is blocked
5972 // due to cross-origin restrictions
5973 styleTarget = styleTarget.contentDocument.head;
5974 } catch (e) {
5975 // istanbul ignore next
5976 styleTarget = null;
5977 }
5978 }
5979 memo[target] = styleTarget;
5980 }
5981 return memo[target];
5982 }
5983
5984 /* istanbul ignore next */
5985 function insertBySelector(insert, style) {
5986 var target = getTarget(insert);
5987 if (!target) {
5988 throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
5989 }
5990 target.appendChild(style);
5991 }
5992 module.exports = insertBySelector;
5993
5994 /***/ },
5995
5996 /***/ "./node_modules/style-loader/dist/runtime/insertStyleElement.js"
5997 /*!**********************************************************************!*\
5998 !*** ./node_modules/style-loader/dist/runtime/insertStyleElement.js ***!
5999 \**********************************************************************/
6000 (module) {
6001
6002 "use strict";
6003
6004
6005 /* istanbul ignore next */
6006 function insertStyleElement(options) {
6007 var element = document.createElement("style");
6008 options.setAttributes(element, options.attributes);
6009 options.insert(element, options.options);
6010 return element;
6011 }
6012 module.exports = insertStyleElement;
6013
6014 /***/ },
6015
6016 /***/ "./node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js"
6017 /*!**********************************************************************************!*\
6018 !*** ./node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js ***!
6019 \**********************************************************************************/
6020 (module, __unused_webpack_exports, __webpack_require__) {
6021
6022 "use strict";
6023
6024
6025 /* istanbul ignore next */
6026 function setAttributesWithoutAttributes(styleElement) {
6027 var nonce = true ? __webpack_require__.nc : 0;
6028 if (nonce) {
6029 styleElement.setAttribute("nonce", nonce);
6030 }
6031 }
6032 module.exports = setAttributesWithoutAttributes;
6033
6034 /***/ },
6035
6036 /***/ "./node_modules/style-loader/dist/runtime/styleDomAPI.js"
6037 /*!***************************************************************!*\
6038 !*** ./node_modules/style-loader/dist/runtime/styleDomAPI.js ***!
6039 \***************************************************************/
6040 (module) {
6041
6042 "use strict";
6043
6044
6045 /* istanbul ignore next */
6046 function apply(styleElement, options, obj) {
6047 var css = "";
6048 if (obj.supports) {
6049 css += "@supports (".concat(obj.supports, ") {");
6050 }
6051 if (obj.media) {
6052 css += "@media ".concat(obj.media, " {");
6053 }
6054 var needLayer = typeof obj.layer !== "undefined";
6055 if (needLayer) {
6056 css += "@layer".concat(obj.layer.length > 0 ? " ".concat(obj.layer) : "", " {");
6057 }
6058 css += obj.css;
6059 if (needLayer) {
6060 css += "}";
6061 }
6062 if (obj.media) {
6063 css += "}";
6064 }
6065 if (obj.supports) {
6066 css += "}";
6067 }
6068 var sourceMap = obj.sourceMap;
6069 if (sourceMap && typeof btoa !== "undefined") {
6070 css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
6071 }
6072
6073 // For old IE
6074 /* istanbul ignore if */
6075 options.styleTagTransform(css, styleElement, options.options);
6076 }
6077 function removeStyleElement(styleElement) {
6078 // istanbul ignore if
6079 if (styleElement.parentNode === null) {
6080 return false;
6081 }
6082 styleElement.parentNode.removeChild(styleElement);
6083 }
6084
6085 /* istanbul ignore next */
6086 function domAPI(options) {
6087 if (typeof document === "undefined") {
6088 return {
6089 update: function update() {},
6090 remove: function remove() {}
6091 };
6092 }
6093 var styleElement = options.insertStyleElement(options);
6094 return {
6095 update: function update(obj) {
6096 apply(styleElement, options, obj);
6097 },
6098 remove: function remove() {
6099 removeStyleElement(styleElement);
6100 }
6101 };
6102 }
6103 module.exports = domAPI;
6104
6105 /***/ },
6106
6107 /***/ "./node_modules/style-loader/dist/runtime/styleTagTransform.js"
6108 /*!*********************************************************************!*\
6109 !*** ./node_modules/style-loader/dist/runtime/styleTagTransform.js ***!
6110 \*********************************************************************/
6111 (module) {
6112
6113 "use strict";
6114
6115
6116 /* istanbul ignore next */
6117 function styleTagTransform(css, styleElement) {
6118 if (styleElement.styleSheet) {
6119 styleElement.styleSheet.cssText = css;
6120 } else {
6121 while (styleElement.firstChild) {
6122 styleElement.removeChild(styleElement.firstChild);
6123 }
6124 styleElement.appendChild(document.createTextNode(css));
6125 }
6126 }
6127 module.exports = styleTagTransform;
6128
6129 /***/ },
6130
6131 /***/ "./node_modules/sweetalert2/dist/sweetalert2.all.js"
6132 /*!**********************************************************!*\
6133 !*** ./node_modules/sweetalert2/dist/sweetalert2.all.js ***!
6134 \**********************************************************/
6135 (module) {
6136
6137 /*!
6138 * sweetalert2 v11.26.25
6139 * Released under the MIT License.
6140 */
6141 (function (global, factory) {
6142 true ? module.exports = factory() :
6143 0;
6144 })(this, (function () { 'use strict';
6145
6146 function _assertClassBrand(e, t, n) {
6147 if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
6148 throw new TypeError("Private element is not present on this object");
6149 }
6150 function _checkPrivateRedeclaration(e, t) {
6151 if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
6152 }
6153 function _classPrivateFieldGet2(s, a) {
6154 return s.get(_assertClassBrand(s, a));
6155 }
6156 function _classPrivateFieldInitSpec(e, t, a) {
6157 _checkPrivateRedeclaration(e, t), t.set(e, a);
6158 }
6159 function _classPrivateFieldSet2(s, a, r) {
6160 return s.set(_assertClassBrand(s, a), r), r;
6161 }
6162
6163 const RESTORE_FOCUS_TIMEOUT = 100;
6164
6165 /** @type {GlobalState} */
6166 const globalState = {};
6167 const focusPreviousActiveElement = () => {
6168 if (globalState.previousActiveElement instanceof HTMLElement) {
6169 globalState.previousActiveElement.focus();
6170 globalState.previousActiveElement = null;
6171 } else if (document.body) {
6172 document.body.focus();
6173 }
6174 };
6175
6176 /**
6177 * Restore previous active (focused) element
6178 *
6179 * @param {boolean} returnFocus
6180 * @returns {Promise<void>}
6181 */
6182 const restoreActiveElement = returnFocus => {
6183 return new Promise(resolve => {
6184 if (!returnFocus) {
6185 return resolve();
6186 }
6187 const x = window.scrollX;
6188 const y = window.scrollY;
6189 globalState.restoreFocusTimeout = setTimeout(() => {
6190 focusPreviousActiveElement();
6191 resolve();
6192 }, RESTORE_FOCUS_TIMEOUT); // issues/900
6193
6194 window.scrollTo(x, y);
6195 });
6196 };
6197
6198 const swalPrefix = 'swal2-';
6199
6200 /**
6201 * @typedef {Record<SwalClass, string>} SwalClasses
6202 */
6203
6204 /**
6205 * @typedef {'success' | 'warning' | 'info' | 'question' | 'error'} SwalIcon
6206 * @typedef {Record<SwalIcon, string>} SwalIcons
6207 */
6208
6209 /** @type {SwalClass[]} */
6210 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'];
6211 const swalClasses = classNames.reduce((acc, className) => {
6212 acc[className] = swalPrefix + className;
6213 return acc;
6214 }, /** @type {SwalClasses} */{});
6215
6216 /** @type {SwalIcon[]} */
6217 const icons = ['success', 'warning', 'info', 'question', 'error'];
6218 const iconTypes = icons.reduce((acc, icon) => {
6219 acc[icon] = swalPrefix + icon;
6220 return acc;
6221 }, /** @type {SwalIcons} */{});
6222
6223 const consolePrefix = 'SweetAlert2:';
6224
6225 /**
6226 * Capitalize the first letter of a string
6227 *
6228 * @param {string} str
6229 * @returns {string}
6230 */
6231 const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
6232
6233 /**
6234 * Standardize console warnings
6235 *
6236 * @param {string | string[]} message
6237 */
6238 const warn = message => {
6239 console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`);
6240 };
6241
6242 /**
6243 * Standardize console errors
6244 *
6245 * @param {string} message
6246 */
6247 const error = message => {
6248 console.error(`${consolePrefix} ${message}`);
6249 };
6250
6251 /**
6252 * Private global state for `warnOnce`
6253 *
6254 * @type {string[]}
6255 * @private
6256 */
6257 const previousWarnOnceMessages = [];
6258
6259 /**
6260 * Show a console warning, but only if it hasn't already been shown
6261 *
6262 * @param {string} message
6263 */
6264 const warnOnce = message => {
6265 if (!previousWarnOnceMessages.includes(message)) {
6266 previousWarnOnceMessages.push(message);
6267 warn(message);
6268 }
6269 };
6270
6271 /**
6272 * Show a one-time console warning about deprecated params/methods
6273 *
6274 * @param {string} deprecatedParam
6275 * @param {string?} useInstead
6276 */
6277 const warnAboutDeprecation = (deprecatedParam, useInstead = null) => {
6278 warnOnce(`"${deprecatedParam}" is deprecated and will be removed in the next major release.${useInstead ? ` Use "${useInstead}" instead.` : ''}`);
6279 };
6280
6281 /**
6282 * If `arg` is a function, call it (with no arguments or context) and return the result.
6283 * Otherwise, just pass the value through
6284 *
6285 * @param {(() => *) | *} arg
6286 * @returns {*}
6287 */
6288 const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
6289
6290 /**
6291 * @param {*} arg
6292 * @returns {boolean}
6293 */
6294 const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
6295
6296 /**
6297 * @param {*} arg
6298 * @returns {Promise<*>}
6299 */
6300 const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
6301
6302 /**
6303 * @param {*} arg
6304 * @returns {boolean}
6305 */
6306 const isPromise = arg => arg && Promise.resolve(arg) === arg;
6307
6308 /**
6309 * @returns {boolean}
6310 */
6311 const isFirefox = () => navigator.userAgent.includes('Firefox');
6312
6313 /**
6314 * Gets the popup container which contains the backdrop and the popup itself.
6315 *
6316 * @returns {HTMLElement | null}
6317 */
6318 const getContainer = () => document.body.querySelector(`.${swalClasses.container}`);
6319
6320 /**
6321 * @param {string} selectorString
6322 * @returns {HTMLElement | null}
6323 */
6324 const elementBySelector = selectorString => {
6325 const container = getContainer();
6326 return container ? container.querySelector(selectorString) : null;
6327 };
6328
6329 /**
6330 * @param {string} className
6331 * @returns {HTMLElement | null}
6332 */
6333 const elementByClass = className => {
6334 return elementBySelector(`.${className}`);
6335 };
6336
6337 /**
6338 * @returns {HTMLElement | null}
6339 */
6340 const getPopup = () => elementByClass(swalClasses.popup);
6341
6342 /**
6343 * @returns {HTMLElement | null}
6344 */
6345 const getIcon = () => elementByClass(swalClasses.icon);
6346
6347 /**
6348 * @returns {HTMLElement | null}
6349 */
6350 const getIconContent = () => elementByClass(swalClasses['icon-content']);
6351
6352 /**
6353 * @returns {HTMLElement | null}
6354 */
6355 const getTitle = () => elementByClass(swalClasses.title);
6356
6357 /**
6358 * @returns {HTMLElement | null}
6359 */
6360 const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
6361
6362 /**
6363 * @returns {HTMLElement | null}
6364 */
6365 const getImage = () => elementByClass(swalClasses.image);
6366
6367 /**
6368 * @returns {HTMLElement | null}
6369 */
6370 const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
6371
6372 /**
6373 * @returns {HTMLElement | null}
6374 */
6375 const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
6376
6377 /**
6378 * @returns {HTMLButtonElement | null}
6379 */
6380 const getConfirmButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`));
6381
6382 /**
6383 * @returns {HTMLButtonElement | null}
6384 */
6385 const getCancelButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`));
6386
6387 /**
6388 * @returns {HTMLButtonElement | null}
6389 */
6390 const getDenyButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`));
6391
6392 /**
6393 * @returns {HTMLElement | null}
6394 */
6395 const getInputLabel = () => elementByClass(swalClasses['input-label']);
6396
6397 /**
6398 * @returns {HTMLElement | null}
6399 */
6400 const getLoader = () => elementBySelector(`.${swalClasses.loader}`);
6401
6402 /**
6403 * @returns {HTMLElement | null}
6404 */
6405 const getActions = () => elementByClass(swalClasses.actions);
6406
6407 /**
6408 * @returns {HTMLElement | null}
6409 */
6410 const getFooter = () => elementByClass(swalClasses.footer);
6411
6412 /**
6413 * @returns {HTMLElement | null}
6414 */
6415 const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
6416
6417 /**
6418 * @returns {HTMLElement | null}
6419 */
6420 const getCloseButton = () => elementByClass(swalClasses.close);
6421
6422 // https://github.com/jkup/focusable/blob/master/index.js
6423 const focusable = `
6424 a[href],
6425 area[href],
6426 input:not([disabled]),
6427 select:not([disabled]),
6428 textarea:not([disabled]),
6429 button:not([disabled]),
6430 iframe,
6431 object,
6432 embed,
6433 [tabindex="0"],
6434 [contenteditable],
6435 audio[controls],
6436 video[controls],
6437 summary
6438 `;
6439 /**
6440 * @returns {HTMLElement[]}
6441 */
6442 const getFocusableElements = () => {
6443 const popup = getPopup();
6444 if (!popup) {
6445 return [];
6446 }
6447 /** @type {NodeListOf<HTMLElement>} */
6448 const focusableElementsWithTabindex = popup.querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])');
6449 const focusableElementsWithTabindexSorted = Array.from(focusableElementsWithTabindex)
6450 // sort according to tabindex
6451 .sort((a, b) => {
6452 const tabindexA = parseInt(a.getAttribute('tabindex') || '0');
6453 const tabindexB = parseInt(b.getAttribute('tabindex') || '0');
6454 if (tabindexA > tabindexB) {
6455 return 1;
6456 } else if (tabindexA < tabindexB) {
6457 return -1;
6458 }
6459 return 0;
6460 });
6461
6462 /** @type {NodeListOf<HTMLElement>} */
6463 const otherFocusableElements = popup.querySelectorAll(focusable);
6464 const otherFocusableElementsFiltered = Array.from(otherFocusableElements).filter(el => el.getAttribute('tabindex') !== '-1');
6465 return [...new Set(focusableElementsWithTabindexSorted.concat(otherFocusableElementsFiltered))].filter(el => isVisible$1(el));
6466 };
6467
6468 /**
6469 * @returns {boolean}
6470 */
6471 const isModal = () => {
6472 return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
6473 };
6474
6475 /**
6476 * @returns {boolean}
6477 */
6478 const isToast = () => {
6479 const popup = getPopup();
6480 if (!popup) {
6481 return false;
6482 }
6483 return hasClass(popup, swalClasses.toast);
6484 };
6485
6486 /**
6487 * @returns {boolean}
6488 */
6489 const isLoading = () => {
6490 const popup = getPopup();
6491 if (!popup) {
6492 return false;
6493 }
6494 return popup.hasAttribute('data-loading');
6495 };
6496
6497 /**
6498 * Securely set innerHTML of an element
6499 * https://github.com/sweetalert2/sweetalert2/issues/1926
6500 *
6501 * @param {HTMLElement} elem
6502 * @param {string} html
6503 */
6504 const setInnerHtml = (elem, html) => {
6505 elem.textContent = '';
6506 if (html) {
6507 const parser = new DOMParser();
6508 const parsed = parser.parseFromString(html, `text/html`);
6509 const head = parsed.querySelector('head');
6510 if (head) {
6511 Array.from(head.childNodes).forEach(child => {
6512 elem.appendChild(child);
6513 });
6514 }
6515 const body = parsed.querySelector('body');
6516 if (body) {
6517 Array.from(body.childNodes).forEach(child => {
6518 if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) {
6519 elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507
6520 } else {
6521 elem.appendChild(child);
6522 }
6523 });
6524 }
6525 }
6526 };
6527
6528 /**
6529 * @param {HTMLElement} elem
6530 * @param {string} className
6531 * @returns {boolean}
6532 */
6533 const hasClass = (elem, className) => {
6534 if (!className) {
6535 return false;
6536 }
6537 return className.split(/\s+/).every(cls => elem.classList.contains(cls));
6538 };
6539
6540 /**
6541 * @param {HTMLElement} elem
6542 * @param {SweetAlertOptions} params
6543 */
6544 const removeCustomClasses = (elem, params) => {
6545 Array.from(elem.classList).forEach(className => {
6546 if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass || {}).includes(className)) {
6547 elem.classList.remove(className);
6548 }
6549 });
6550 };
6551
6552 /**
6553 * @param {HTMLElement} elem
6554 * @param {SweetAlertOptions} params
6555 * @param {string} className
6556 */
6557 const applyCustomClass = (elem, params, className) => {
6558 removeCustomClasses(elem, params);
6559 if (!params.customClass) {
6560 return;
6561 }
6562 const customClass = params.customClass[(/** @type {keyof SweetAlertCustomClass} */className)];
6563 if (!customClass) {
6564 return;
6565 }
6566 if (typeof customClass !== 'string' && !customClass.forEach) {
6567 warn(`Invalid type of customClass.${className}! Expected string or iterable object, got "${typeof customClass}"`);
6568 return;
6569 }
6570 addClass(elem, customClass);
6571 };
6572
6573 /**
6574 * @param {HTMLElement} popup
6575 * @param {import('./renderers/renderInput').InputClass | SweetAlertInput} inputClass
6576 * @returns {HTMLInputElement | null}
6577 */
6578 const getInput$1 = (popup, inputClass) => {
6579 if (!inputClass) {
6580 return null;
6581 }
6582 switch (inputClass) {
6583 case 'select':
6584 case 'textarea':
6585 case 'file':
6586 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`);
6587 case 'checkbox':
6588 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`);
6589 case 'radio':
6590 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`);
6591 case 'range':
6592 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`);
6593 default:
6594 return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`);
6595 }
6596 };
6597
6598 /**
6599 * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input
6600 */
6601 const focusInput = input => {
6602 input.focus();
6603
6604 // place cursor at end of text in text input
6605 if (input.type !== 'file') {
6606 // http://stackoverflow.com/a/2345915
6607 const val = input.value;
6608 input.value = '';
6609 input.value = val;
6610 }
6611 };
6612
6613 /**
6614 * @param {HTMLElement | HTMLElement[] | null} target
6615 * @param {string | string[] | readonly string[] | undefined} classList
6616 * @param {boolean} condition
6617 */
6618 const toggleClass = (target, classList, condition) => {
6619 if (!target || !classList) {
6620 return;
6621 }
6622 const classes = typeof classList === 'string' ? classList.split(/\s+/).filter(Boolean) : classList;
6623 const targets = Array.isArray(target) ? target : [target];
6624 targets.forEach(elem => {
6625 classes.forEach(className => {
6626 if (condition) {
6627 elem.classList.add(className);
6628 } else {
6629 elem.classList.remove(className);
6630 }
6631 });
6632 });
6633 };
6634
6635 /**
6636 * @param {HTMLElement | HTMLElement[] | null} target
6637 * @param {string | string[] | readonly string[] | undefined} classList
6638 */
6639 const addClass = (target, classList) => {
6640 toggleClass(target, classList, true);
6641 };
6642
6643 /**
6644 * @param {HTMLElement | HTMLElement[] | null} target
6645 * @param {string | string[] | readonly string[] | undefined} classList
6646 */
6647 const removeClass = (target, classList) => {
6648 toggleClass(target, classList, false);
6649 };
6650
6651 /**
6652 * Get direct child of an element by class name
6653 *
6654 * @param {HTMLElement} elem
6655 * @param {string} className
6656 * @returns {HTMLElement | undefined}
6657 */
6658 const getDirectChildByClass = (elem, className) => (/** @type {HTMLElement | undefined} */
6659 Array.from(elem.children).find(child => child instanceof HTMLElement && hasClass(child, className)));
6660
6661 /**
6662 * @param {HTMLElement} elem
6663 * @param {string} property
6664 * @param {string | number | null | undefined} value
6665 */
6666 const applyNumericalStyle = (elem, property, value) => {
6667 if (value === `${parseInt(`${value}`)}`) {
6668 value = parseInt(value);
6669 }
6670 if (value || value === 0) {
6671 elem.style.setProperty(property, typeof value === 'number' ? `${value}px` : (/** @type {string} */value));
6672 } else {
6673 elem.style.removeProperty(property);
6674 }
6675 };
6676
6677 /**
6678 * @param {HTMLElement | null} elem
6679 * @param {string} display
6680 */
6681 const show = (elem, display = 'flex') => {
6682 if (!elem) {
6683 return;
6684 }
6685 elem.style.display = display;
6686 };
6687
6688 /**
6689 * @param {HTMLElement | null} elem
6690 */
6691 const hide = elem => {
6692 if (!elem) {
6693 return;
6694 }
6695 elem.style.display = 'none';
6696 };
6697
6698 /**
6699 * @param {HTMLElement | null} elem
6700 * @param {string} display
6701 */
6702 const showWhenInnerHtmlPresent = (elem, display = 'block') => {
6703 if (!elem) {
6704 return;
6705 }
6706 new MutationObserver(() => {
6707 toggle(elem, elem.innerHTML, display);
6708 }).observe(elem, {
6709 childList: true,
6710 subtree: true
6711 });
6712 };
6713
6714 /**
6715 * @param {HTMLElement} parent
6716 * @param {string} selector
6717 * @param {string} property
6718 * @param {string} value
6719 */
6720 const setStyle = (parent, selector, property, value) => {
6721 /** @type {HTMLElement | null} */
6722 const el = parent.querySelector(selector);
6723 if (el) {
6724 el.style.setProperty(property, value);
6725 }
6726 };
6727
6728 /**
6729 * @param {HTMLElement} elem
6730 * @param {boolean | string | null | undefined} condition
6731 * @param {string} display
6732 */
6733 const toggle = (elem, condition, display = 'flex') => {
6734 if (condition) {
6735 show(elem, display);
6736 } else {
6737 hide(elem);
6738 }
6739 };
6740
6741 /**
6742 * borrowed from jquery $(elem).is(':visible') implementation
6743 *
6744 * @param {HTMLElement | null} elem
6745 * @returns {boolean}
6746 */
6747 const isVisible$1 = elem => Boolean(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
6748
6749 /**
6750 * @returns {boolean}
6751 */
6752 const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton());
6753
6754 /**
6755 * @param {HTMLElement} elem
6756 * @returns {boolean}
6757 */
6758 const isScrollable = elem => Boolean(elem.scrollHeight > elem.clientHeight);
6759
6760 /**
6761 * @param {HTMLElement} element
6762 * @param {HTMLElement} stopElement
6763 * @returns {boolean}
6764 */
6765 const selfOrParentIsScrollable = (element, stopElement) => {
6766 let parent = /** @type {HTMLElement | null} */element;
6767 while (parent && parent !== stopElement) {
6768 if (isScrollable(parent)) {
6769 return true;
6770 }
6771 parent = parent.parentElement;
6772 }
6773 return false;
6774 };
6775
6776 /**
6777 * borrowed from https://stackoverflow.com/a/46352119
6778 *
6779 * @param {HTMLElement} elem
6780 * @returns {boolean}
6781 */
6782 const hasCssAnimation = elem => {
6783 const style = window.getComputedStyle(elem);
6784 const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
6785 const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
6786 return animDuration > 0 || transDuration > 0;
6787 };
6788
6789 /**
6790 * @param {number} timer
6791 * @param {boolean} reset
6792 */
6793 const animateTimerProgressBar = (timer, reset = false) => {
6794 const timerProgressBar = getTimerProgressBar();
6795 if (!timerProgressBar) {
6796 return;
6797 }
6798 if (isVisible$1(timerProgressBar)) {
6799 if (reset) {
6800 timerProgressBar.style.transition = 'none';
6801 timerProgressBar.style.width = '100%';
6802 }
6803 setTimeout(() => {
6804 timerProgressBar.style.transition = `width ${timer / 1000}s linear`;
6805 timerProgressBar.style.width = '0%';
6806 }, 10);
6807 }
6808 };
6809 const stopTimerProgressBar = () => {
6810 const timerProgressBar = getTimerProgressBar();
6811 if (!timerProgressBar) {
6812 return;
6813 }
6814 const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
6815 timerProgressBar.style.removeProperty('transition');
6816 timerProgressBar.style.width = '100%';
6817 const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
6818 const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
6819 timerProgressBar.style.width = `${timerProgressBarPercent}%`;
6820 };
6821
6822 /**
6823 * Detect Node env
6824 *
6825 * @returns {boolean}
6826 */
6827 const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
6828
6829 const sweetHTML = `
6830 <div aria-labelledby="${swalClasses.title}" aria-describedby="${swalClasses['html-container']}" class="${swalClasses.popup}" tabindex="-1">
6831 <button type="button" class="${swalClasses.close}"></button>
6832 <ul class="${swalClasses['progress-steps']}"></ul>
6833 <div class="${swalClasses.icon}"></div>
6834 <img class="${swalClasses.image}" />
6835 <h2 class="${swalClasses.title}" id="${swalClasses.title}"></h2>
6836 <div class="${swalClasses['html-container']}" id="${swalClasses['html-container']}"></div>
6837 <input class="${swalClasses.input}" id="${swalClasses.input}" />
6838 <input type="file" class="${swalClasses.file}" />
6839 <div class="${swalClasses.range}">
6840 <input type="range" />
6841 <output></output>
6842 </div>
6843 <select class="${swalClasses.select}" id="${swalClasses.select}"></select>
6844 <div class="${swalClasses.radio}"></div>
6845 <label class="${swalClasses.checkbox}">
6846 <input type="checkbox" id="${swalClasses.checkbox}" />
6847 <span class="${swalClasses.label}"></span>
6848 </label>
6849 <textarea class="${swalClasses.textarea}" id="${swalClasses.textarea}"></textarea>
6850 <div class="${swalClasses['validation-message']}" id="${swalClasses['validation-message']}"></div>
6851 <div class="${swalClasses.actions}">
6852 <div class="${swalClasses.loader}"></div>
6853 <button type="button" class="${swalClasses.confirm}"></button>
6854 <button type="button" class="${swalClasses.deny}"></button>
6855 <button type="button" class="${swalClasses.cancel}"></button>
6856 </div>
6857 <div class="${swalClasses.footer}"></div>
6858 <div class="${swalClasses['timer-progress-bar-container']}">
6859 <div class="${swalClasses['timer-progress-bar']}"></div>
6860 </div>
6861 </div>
6862 `.replace(/(^|\n)\s*/g, '');
6863
6864 /**
6865 * @returns {boolean}
6866 */
6867 const resetOldContainer = () => {
6868 const oldContainer = getContainer();
6869 if (!oldContainer) {
6870 return false;
6871 }
6872 oldContainer.remove();
6873 removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'],
6874 // @ts-ignore: 'has-column' is not defined in swalClasses but may be set dynamically
6875 swalClasses['has-column']]);
6876 return true;
6877 };
6878 const resetValidationMessage$1 = () => {
6879 if (globalState.currentInstance) {
6880 globalState.currentInstance.resetValidationMessage();
6881 }
6882 };
6883 const addInputChangeListeners = () => {
6884 const popup = getPopup();
6885 if (!popup) {
6886 return;
6887 }
6888 const input = getDirectChildByClass(popup, swalClasses.input);
6889 const file = getDirectChildByClass(popup, swalClasses.file);
6890 /** @type {HTMLInputElement | null} */
6891 const range = popup.querySelector(`.${swalClasses.range} input`);
6892 /** @type {HTMLOutputElement | null} */
6893 const rangeOutput = popup.querySelector(`.${swalClasses.range} output`);
6894 const select = getDirectChildByClass(popup, swalClasses.select);
6895 /** @type {HTMLInputElement | null} */
6896 const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`);
6897 const textarea = getDirectChildByClass(popup, swalClasses.textarea);
6898 if (input) {
6899 input.oninput = resetValidationMessage$1;
6900 }
6901 if (file) {
6902 file.onchange = resetValidationMessage$1;
6903 }
6904 if (select) {
6905 select.onchange = resetValidationMessage$1;
6906 }
6907 if (checkbox) {
6908 checkbox.onchange = resetValidationMessage$1;
6909 }
6910 if (textarea) {
6911 textarea.oninput = resetValidationMessage$1;
6912 }
6913 if (range && rangeOutput) {
6914 range.oninput = () => {
6915 resetValidationMessage$1();
6916 rangeOutput.value = range.value;
6917 };
6918 range.onchange = () => {
6919 resetValidationMessage$1();
6920 rangeOutput.value = range.value;
6921 };
6922 }
6923 };
6924
6925 /**
6926 * @param {string | HTMLElement} target
6927 * @returns {HTMLElement}
6928 */
6929 const getTarget = target => {
6930 if (typeof target === 'string') {
6931 const element = document.querySelector(target);
6932 if (!element) {
6933 throw new Error(`Target element "${target}" not found`);
6934 }
6935 return /** @type {HTMLElement} */element;
6936 }
6937 return target;
6938 };
6939
6940 /**
6941 * @param {SweetAlertOptions} params
6942 */
6943 const setupAccessibility = params => {
6944 const popup = getPopup();
6945 if (!popup) {
6946 return;
6947 }
6948 popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
6949 popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
6950 if (!params.toast) {
6951 popup.setAttribute('aria-modal', 'true');
6952 }
6953 };
6954
6955 /**
6956 * @param {HTMLElement} targetElement
6957 */
6958 const setupRTL = targetElement => {
6959 if (window.getComputedStyle(targetElement).direction === 'rtl') {
6960 addClass(getContainer(), swalClasses.rtl);
6961 globalState.isRTL = true;
6962 }
6963 };
6964
6965 /**
6966 * Add modal + backdrop to DOM
6967 *
6968 * @param {SweetAlertOptions} params
6969 */
6970 const init = params => {
6971 // Clean up the old popup container if it exists
6972 const oldContainerExisted = resetOldContainer();
6973 if (isNodeEnv()) {
6974 error('SweetAlert2 requires document to initialize');
6975 return;
6976 }
6977 const container = document.createElement('div');
6978 container.className = swalClasses.container;
6979 if (oldContainerExisted) {
6980 addClass(container, swalClasses['no-transition']);
6981 }
6982 setInnerHtml(container, sweetHTML);
6983 container.dataset['swal2Theme'] = params.theme;
6984 const targetElement = getTarget(params.target || 'body');
6985 targetElement.appendChild(container);
6986 if (params.topLayer) {
6987 container.setAttribute('popover', '');
6988 container.showPopover();
6989 }
6990 setupAccessibility(params);
6991 setupRTL(targetElement);
6992 addInputChangeListeners();
6993 };
6994
6995 /**
6996 * @param {HTMLElement | object | string} param
6997 * @param {HTMLElement} target
6998 */
6999 const parseHtmlToContainer = (param, target) => {
7000 // DOM element
7001 if (param instanceof HTMLElement) {
7002 target.appendChild(param);
7003 }
7004
7005 // Object
7006 else if (typeof param === 'object') {
7007 handleObject(param, target);
7008 }
7009
7010 // Plain string
7011 else if (param) {
7012 setInnerHtml(target, param);
7013 }
7014 };
7015
7016 /**
7017 * @param {object} param
7018 * @param {HTMLElement} target
7019 */
7020 const handleObject = (param, target) => {
7021 // JQuery element(s)
7022 if ('jquery' in param) {
7023 handleJqueryElem(target, param);
7024 }
7025
7026 // For other objects use their string representation
7027 else {
7028 setInnerHtml(target, param.toString());
7029 }
7030 };
7031
7032 /**
7033 * @param {HTMLElement} target
7034 * @param {any} elem
7035 */
7036 const handleJqueryElem = (target, elem) => {
7037 target.textContent = '';
7038 if (0 in elem) {
7039 for (let i = 0; i in elem; i++) {
7040 target.appendChild(elem[i].cloneNode(true));
7041 }
7042 } else {
7043 target.appendChild(elem.cloneNode(true));
7044 }
7045 };
7046
7047 /**
7048 * @param {SweetAlert} instance
7049 * @param {SweetAlertOptions} params
7050 */
7051 const renderActions = (instance, params) => {
7052 const actions = getActions();
7053 const loader = getLoader();
7054 if (!actions || !loader) {
7055 return;
7056 }
7057
7058 // Actions (buttons) wrapper
7059 if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
7060 hide(actions);
7061 } else {
7062 show(actions);
7063 }
7064
7065 // Custom class
7066 applyCustomClass(actions, params, 'actions');
7067
7068 // Render all the buttons
7069 renderButtons(actions, loader, params);
7070
7071 // Loader
7072 setInnerHtml(loader, params.loaderHtml || '');
7073 applyCustomClass(loader, params, 'loader');
7074 };
7075
7076 /**
7077 * @param {HTMLElement} actions
7078 * @param {HTMLElement} loader
7079 * @param {SweetAlertOptions} params
7080 */
7081 function renderButtons(actions, loader, params) {
7082 const confirmButton = getConfirmButton();
7083 const denyButton = getDenyButton();
7084 const cancelButton = getCancelButton();
7085 if (!confirmButton || !denyButton || !cancelButton) {
7086 return;
7087 }
7088
7089 // Render buttons
7090 renderButton(confirmButton, 'confirm', params);
7091 renderButton(denyButton, 'deny', params);
7092 renderButton(cancelButton, 'cancel', params);
7093 handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
7094 if (params.reverseButtons) {
7095 if (params.toast) {
7096 actions.insertBefore(cancelButton, confirmButton);
7097 actions.insertBefore(denyButton, confirmButton);
7098 } else {
7099 actions.insertBefore(cancelButton, loader);
7100 actions.insertBefore(denyButton, loader);
7101 actions.insertBefore(confirmButton, loader);
7102 }
7103 }
7104 }
7105
7106 /**
7107 * @param {HTMLElement} confirmButton
7108 * @param {HTMLElement} denyButton
7109 * @param {HTMLElement} cancelButton
7110 * @param {SweetAlertOptions} params
7111 */
7112 function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
7113 if (!params.buttonsStyling) {
7114 removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
7115 return;
7116 }
7117 addClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
7118
7119 // Apply custom background colors and outline colors to action buttons
7120 /** @type {[HTMLElement, string, string | undefined][]} */
7121 const buttons = [[confirmButton, 'confirm', params.confirmButtonColor], [denyButton, 'deny', params.denyButtonColor], [cancelButton, 'cancel', params.cancelButtonColor]];
7122 buttons.forEach(([button, type, color]) => {
7123 if (color) {
7124 button.style.setProperty(`--swal2-${type}-button-background-color`, color);
7125 }
7126 applyOutlineColor(button);
7127 });
7128 }
7129
7130 /**
7131 * @param {HTMLElement} button
7132 */
7133 function applyOutlineColor(button) {
7134 const buttonStyle = window.getComputedStyle(button);
7135 if (buttonStyle.getPropertyValue('--swal2-action-button-focus-box-shadow')) {
7136 // If the button already has a custom outline color, no need to change it
7137 return;
7138 }
7139 const outlineColor = buttonStyle.backgroundColor.replace(/rgba?\((\d+), (\d+), (\d+).*/, 'rgba($1, $2, $3, 0.5)');
7140 button.style.setProperty('--swal2-action-button-focus-box-shadow', buttonStyle.getPropertyValue('--swal2-outline').replace(/ rgba\(.*/, ` ${outlineColor}`));
7141 }
7142
7143 /**
7144 * @param {HTMLElement} button
7145 * @param {'confirm' | 'deny' | 'cancel'} buttonType
7146 * @param {SweetAlertOptions} params
7147 */
7148 function renderButton(button, buttonType, params) {
7149 const buttonName = /** @type {'Confirm' | 'Deny' | 'Cancel'} */capitalizeFirstLetter(buttonType);
7150 toggle(button, params[`show${buttonName}Button`], 'inline-block');
7151 setInnerHtml(button, params[`${buttonType}ButtonText`] || ''); // Set caption text
7152 button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`] || ''); // ARIA label
7153
7154 // Add buttons custom classes
7155 button.className = swalClasses[buttonType];
7156 applyCustomClass(button, params, `${buttonType}Button`);
7157 }
7158
7159 /**
7160 * @param {SweetAlert} instance
7161 * @param {SweetAlertOptions} params
7162 */
7163 const renderCloseButton = (instance, params) => {
7164 const closeButton = getCloseButton();
7165 if (!closeButton) {
7166 return;
7167 }
7168 setInnerHtml(closeButton, params.closeButtonHtml || '');
7169
7170 // Custom class
7171 applyCustomClass(closeButton, params, 'closeButton');
7172 toggle(closeButton, params.showCloseButton);
7173 closeButton.setAttribute('aria-label', params.closeButtonAriaLabel || '');
7174 };
7175
7176 /**
7177 * @param {SweetAlert} instance
7178 * @param {SweetAlertOptions} params
7179 */
7180 const renderContainer = (instance, params) => {
7181 const container = getContainer();
7182 if (!container) {
7183 return;
7184 }
7185 handleBackdropParam(container, params.backdrop);
7186 handlePositionParam(container, params.position);
7187 handleGrowParam(container, params.grow);
7188
7189 // Custom class
7190 applyCustomClass(container, params, 'container');
7191 };
7192
7193 /**
7194 * @param {HTMLElement} container
7195 * @param {SweetAlertOptions['backdrop']} backdrop
7196 */
7197 function handleBackdropParam(container, backdrop) {
7198 if (typeof backdrop === 'string') {
7199 container.style.background = backdrop;
7200 } else if (!backdrop) {
7201 addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
7202 }
7203 }
7204
7205 /**
7206 * @param {HTMLElement} container
7207 * @param {SweetAlertOptions['position']} position
7208 */
7209 function handlePositionParam(container, position) {
7210 if (!position) {
7211 return;
7212 }
7213 if (position in swalClasses) {
7214 addClass(container, swalClasses[position]);
7215 } else {
7216 warn('The "position" parameter is not valid, defaulting to "center"');
7217 addClass(container, swalClasses.center);
7218 }
7219 }
7220
7221 /**
7222 * @param {HTMLElement} container
7223 * @param {SweetAlertOptions['grow']} grow
7224 */
7225 function handleGrowParam(container, grow) {
7226 if (!grow) {
7227 return;
7228 }
7229 addClass(container, swalClasses[`grow-${grow}`]);
7230 }
7231
7232 /**
7233 * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
7234 * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
7235 * This is the approach that Babel will probably take to implement private methods/fields
7236 * https://github.com/tc39/proposal-private-methods
7237 * https://github.com/babel/babel/pull/7555
7238 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
7239 * then we can use that language feature.
7240 */
7241
7242 var privateProps = {
7243 innerParams: new WeakMap(),
7244 domCache: new WeakMap(),
7245 focusedElement: new WeakMap()
7246 };
7247
7248 /// <reference path="../../../../sweetalert2.d.ts"/>
7249
7250
7251 /** @type {InputClass[]} */
7252 const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
7253
7254 /**
7255 * @param {SweetAlert} instance
7256 * @param {SweetAlertOptions} params
7257 */
7258 const renderInput = (instance, params) => {
7259 const popup = getPopup();
7260 if (!popup) {
7261 return;
7262 }
7263 const innerParams = privateProps.innerParams.get(instance);
7264 const rerender = !innerParams || params.input !== innerParams.input;
7265 inputClasses.forEach(inputClass => {
7266 const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]);
7267 if (!inputContainer) {
7268 return;
7269 }
7270
7271 // set attributes
7272 setAttributes(inputClass, params.inputAttributes);
7273
7274 // set class
7275 inputContainer.className = swalClasses[inputClass];
7276 if (rerender) {
7277 hide(inputContainer);
7278 }
7279 });
7280 if (params.input) {
7281 if (rerender) {
7282 showInput(params);
7283 }
7284 // set custom class
7285 setCustomClass(params);
7286 }
7287 };
7288
7289 /**
7290 * @param {SweetAlertOptions} params
7291 */
7292 const showInput = params => {
7293 if (!params.input) {
7294 return;
7295 }
7296 if (!renderInputType[params.input]) {
7297 error(`Unexpected type of input! Expected ${Object.keys(renderInputType).join(' | ')}, got "${params.input}"`);
7298 return;
7299 }
7300 const inputContainer = getInputContainer(params.input);
7301 if (!inputContainer) {
7302 return;
7303 }
7304 const input = renderInputType[params.input](inputContainer, params);
7305 show(inputContainer);
7306
7307 // input autofocus
7308 if (params.inputAutoFocus) {
7309 setTimeout(() => {
7310 focusInput(input);
7311 });
7312 }
7313 };
7314
7315 /**
7316 * @param {HTMLInputElement} input
7317 */
7318 const removeAttributes = input => {
7319 for (const {
7320 name
7321 } of Array.from(input.attributes)) {
7322 if (!['id', 'type', 'value', 'style'].includes(name)) {
7323 input.removeAttribute(name);
7324 }
7325 }
7326 };
7327
7328 /**
7329 * @param {InputClass} inputClass
7330 * @param {SweetAlertOptions['inputAttributes']} inputAttributes
7331 */
7332 const setAttributes = (inputClass, inputAttributes) => {
7333 const popup = getPopup();
7334 if (!popup) {
7335 return;
7336 }
7337 const input = getInput$1(popup, inputClass);
7338 if (!input) {
7339 return;
7340 }
7341 removeAttributes(input);
7342 for (const attr in inputAttributes) {
7343 input.setAttribute(attr, inputAttributes[attr]);
7344 }
7345 };
7346
7347 /**
7348 * @param {SweetAlertOptions} params
7349 */
7350 const setCustomClass = params => {
7351 if (!params.input) {
7352 return;
7353 }
7354 const inputContainer = getInputContainer(params.input);
7355 if (inputContainer) {
7356 applyCustomClass(inputContainer, params, 'input');
7357 }
7358 };
7359
7360 /**
7361 * @param {HTMLInputElement | HTMLTextAreaElement} input
7362 * @param {SweetAlertOptions} params
7363 */
7364 const setInputPlaceholder = (input, params) => {
7365 if (!input.placeholder && params.inputPlaceholder) {
7366 input.placeholder = params.inputPlaceholder;
7367 }
7368 };
7369
7370 /**
7371 * @param {Input} input
7372 * @param {Input} prependTo
7373 * @param {SweetAlertOptions} params
7374 */
7375 const setInputLabel = (input, prependTo, params) => {
7376 if (params.inputLabel) {
7377 const label = document.createElement('label');
7378 const labelClass = swalClasses['input-label'];
7379 label.setAttribute('for', input.id);
7380 label.className = labelClass;
7381 if (typeof params.customClass === 'object') {
7382 addClass(label, params.customClass.inputLabel);
7383 }
7384 label.innerText = params.inputLabel;
7385 prependTo.insertAdjacentElement('beforebegin', label);
7386 }
7387 };
7388
7389 /**
7390 * @param {SweetAlertInput} inputType
7391 * @returns {HTMLElement | undefined}
7392 */
7393 const getInputContainer = inputType => {
7394 const popup = getPopup();
7395 if (!popup) {
7396 return;
7397 }
7398 return getDirectChildByClass(popup, swalClasses[(/** @type {SwalClass} */inputType)] || swalClasses.input);
7399 };
7400
7401 /**
7402 * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input
7403 * @param {SweetAlertOptions['inputValue']} inputValue
7404 */
7405 const checkAndSetInputValue = (input, inputValue) => {
7406 if (['string', 'number'].includes(typeof inputValue)) {
7407 input.value = `${inputValue}`;
7408 } else if (!isPromise(inputValue)) {
7409 warn(`Unexpected type of inputValue! Expected "string", "number" or "Promise", got "${typeof inputValue}"`);
7410 }
7411 };
7412
7413 /** @type {Record<SweetAlertInput, (input: Input | HTMLElement, params: SweetAlertOptions) => Input>} */
7414 const renderInputType = {};
7415
7416 /**
7417 * @param {Input | HTMLElement} input
7418 * @param {SweetAlertOptions} params
7419 * @returns {Input}
7420 */
7421 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} */
7422 (input, params) => {
7423 // oxfmt-ignore
7424 const inputElement = /** @type {HTMLInputElement} */input;
7425 checkAndSetInputValue(inputElement, params.inputValue);
7426 setInputLabel(inputElement, inputElement, params);
7427 setInputPlaceholder(inputElement, params);
7428 // oxfmt-ignore
7429 inputElement.type = /** @type {string} */params.input;
7430 return inputElement;
7431 };
7432
7433 /**
7434 * @param {Input | HTMLElement} input
7435 * @param {SweetAlertOptions} params
7436 * @returns {Input}
7437 */
7438 renderInputType.file = (input, params) => {
7439 const inputElement = /** @type {HTMLInputElement} */input;
7440 setInputLabel(inputElement, inputElement, params);
7441 setInputPlaceholder(inputElement, params);
7442 return inputElement;
7443 };
7444
7445 /**
7446 * @param {Input | HTMLElement} range
7447 * @param {SweetAlertOptions} params
7448 * @returns {Input}
7449 */
7450 renderInputType.range = (range, params) => {
7451 const rangeContainer = /** @type {HTMLElement} */range;
7452 const rangeInput = rangeContainer.querySelector('input');
7453 const rangeOutput = rangeContainer.querySelector('output');
7454 if (rangeInput) {
7455 checkAndSetInputValue(rangeInput, params.inputValue);
7456 rangeInput.type = /** @type {string} */params.input;
7457 setInputLabel(rangeInput, /** @type {Input} */range, params);
7458 }
7459 if (rangeOutput) {
7460 checkAndSetInputValue(rangeOutput, params.inputValue);
7461 }
7462 return /** @type {Input} */range;
7463 };
7464
7465 /**
7466 * @param {Input | HTMLElement} select
7467 * @param {SweetAlertOptions} params
7468 * @returns {Input}
7469 */
7470 renderInputType.select = (select, params) => {
7471 const selectElement = /** @type {HTMLSelectElement} */select;
7472 selectElement.textContent = '';
7473 if (params.inputPlaceholder) {
7474 const placeholder = document.createElement('option');
7475 setInnerHtml(placeholder, params.inputPlaceholder);
7476 placeholder.value = '';
7477 placeholder.disabled = true;
7478 placeholder.selected = true;
7479 selectElement.appendChild(placeholder);
7480 }
7481 setInputLabel(selectElement, selectElement, params);
7482 return selectElement;
7483 };
7484
7485 /**
7486 * @param {Input | HTMLElement} radio
7487 * @returns {Input}
7488 */
7489 renderInputType.radio = radio => {
7490 const radioElement = /** @type {HTMLElement} */radio;
7491 radioElement.textContent = '';
7492 return /** @type {Input} */radio;
7493 };
7494
7495 /**
7496 * @param {Input | HTMLElement} checkboxContainer
7497 * @param {SweetAlertOptions} params
7498 * @returns {Input}
7499 */
7500 renderInputType.checkbox = (checkboxContainer, params) => {
7501 const popup = getPopup();
7502 if (!popup) {
7503 throw new Error('Popup not found');
7504 }
7505 const checkbox = getInput$1(popup, 'checkbox');
7506 if (!checkbox) {
7507 throw new Error('Checkbox input not found');
7508 }
7509 checkbox.value = '1';
7510 checkbox.checked = Boolean(params.inputValue);
7511 const containerElement = /** @type {HTMLElement} */checkboxContainer;
7512 const label = containerElement.querySelector('span');
7513 if (label) {
7514 const placeholderOrLabel = params.inputPlaceholder || params.inputLabel;
7515 if (placeholderOrLabel) {
7516 setInnerHtml(label, placeholderOrLabel);
7517 }
7518 }
7519 return checkbox;
7520 };
7521
7522 /**
7523 * @param {Input | HTMLElement} textarea
7524 * @param {SweetAlertOptions} params
7525 * @returns {Input}
7526 */
7527 renderInputType.textarea = (textarea, params) => {
7528 const textareaElement = /** @type {HTMLTextAreaElement} */textarea;
7529 checkAndSetInputValue(textareaElement, params.inputValue);
7530 setInputPlaceholder(textareaElement, params);
7531 setInputLabel(textareaElement, textareaElement, params);
7532
7533 /**
7534 * @param {HTMLElement} el
7535 * @returns {number}
7536 */
7537 const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);
7538
7539 // https://github.com/sweetalert2/sweetalert2/issues/2291
7540 setTimeout(() => {
7541 // https://github.com/sweetalert2/sweetalert2/issues/1699
7542 if ('MutationObserver' in window) {
7543 const popup = getPopup();
7544 if (!popup) {
7545 return;
7546 }
7547 const initialPopupWidth = parseInt(window.getComputedStyle(popup).width);
7548 const textareaResizeHandler = () => {
7549 // check if texarea is still in document (i.e. popup wasn't closed in the meantime)
7550 if (!document.body.contains(textareaElement)) {
7551 return;
7552 }
7553 const textareaWidth = textareaElement.offsetWidth + getMargin(textareaElement);
7554 const popupElement = getPopup();
7555 if (popupElement) {
7556 if (textareaWidth > initialPopupWidth) {
7557 popupElement.style.width = `${textareaWidth}px`;
7558 } else {
7559 applyNumericalStyle(popupElement, 'width', params.width);
7560 }
7561 }
7562 };
7563 new MutationObserver(textareaResizeHandler).observe(textareaElement, {
7564 attributes: true,
7565 attributeFilter: ['style']
7566 });
7567 }
7568 });
7569 return textareaElement;
7570 };
7571
7572 /**
7573 * @param {SweetAlert} instance
7574 * @param {SweetAlertOptions} params
7575 */
7576 const renderContent = (instance, params) => {
7577 const htmlContainer = getHtmlContainer();
7578 if (!htmlContainer) {
7579 return;
7580 }
7581 showWhenInnerHtmlPresent(htmlContainer);
7582 applyCustomClass(htmlContainer, params, 'htmlContainer');
7583
7584 // Content as HTML
7585 if (params.html) {
7586 parseHtmlToContainer(params.html, htmlContainer);
7587 show(htmlContainer, 'block');
7588 }
7589
7590 // Content as plain text
7591 else if (params.text) {
7592 htmlContainer.textContent = params.text;
7593 show(htmlContainer, 'block');
7594 }
7595
7596 // No content
7597 else {
7598 hide(htmlContainer);
7599 }
7600 renderInput(instance, params);
7601 };
7602
7603 /**
7604 * @param {SweetAlert} instance
7605 * @param {SweetAlertOptions} params
7606 */
7607 const renderFooter = (instance, params) => {
7608 const footer = getFooter();
7609 if (!footer) {
7610 return;
7611 }
7612 showWhenInnerHtmlPresent(footer);
7613 toggle(footer, Boolean(params.footer), 'block');
7614 if (params.footer) {
7615 parseHtmlToContainer(params.footer, footer);
7616 }
7617
7618 // Custom class
7619 applyCustomClass(footer, params, 'footer');
7620 };
7621
7622 /**
7623 * @param {SweetAlert} instance
7624 * @param {SweetAlertOptions} params
7625 */
7626 const renderIcon = (instance, params) => {
7627 const innerParams = privateProps.innerParams.get(instance);
7628 const icon = getIcon();
7629 if (!icon) {
7630 return;
7631 }
7632
7633 // if the given icon already rendered, apply the styling without re-rendering the icon
7634 if (innerParams && params.icon === innerParams.icon) {
7635 // Custom or default content
7636 setContent(icon, params);
7637 applyStyles(icon, params);
7638 return;
7639 }
7640 if (!params.icon && !params.iconHtml) {
7641 hide(icon);
7642 return;
7643 }
7644 if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
7645 error(`Unknown icon! Expected "success", "error", "warning", "info" or "question", got "${params.icon}"`);
7646 hide(icon);
7647 return;
7648 }
7649 show(icon);
7650
7651 // Custom or default content
7652 setContent(icon, params);
7653 applyStyles(icon, params);
7654
7655 // Animate icon
7656 addClass(icon, params.showClass && params.showClass.icon);
7657
7658 // Re-adjust the success icon on system theme change
7659 const colorSchemeQueryList = window.matchMedia('(prefers-color-scheme: dark)');
7660 colorSchemeQueryList.addEventListener('change', adjustSuccessIconBackgroundColor);
7661 };
7662
7663 /**
7664 * @param {HTMLElement} icon
7665 * @param {SweetAlertOptions} params
7666 */
7667 const applyStyles = (icon, params) => {
7668 for (const [iconType, iconClassName] of Object.entries(iconTypes)) {
7669 if (params.icon !== iconType) {
7670 removeClass(icon, iconClassName);
7671 }
7672 }
7673 addClass(icon, params.icon && iconTypes[params.icon]);
7674
7675 // Icon color
7676 setColor(icon, params);
7677
7678 // Success icon background color
7679 adjustSuccessIconBackgroundColor();
7680
7681 // Custom class
7682 applyCustomClass(icon, params, 'icon');
7683 };
7684
7685 // Adjust success icon background color to match the popup background color
7686 const adjustSuccessIconBackgroundColor = () => {
7687 const popup = getPopup();
7688 if (!popup) {
7689 return;
7690 }
7691 const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
7692 /** @type {NodeListOf<HTMLElement>} */
7693 const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
7694 successIconParts.forEach(part => {
7695 part.style.backgroundColor = popupBackgroundColor;
7696 });
7697 };
7698
7699 /**
7700 *
7701 * @param {SweetAlertOptions} params
7702 * @returns {string}
7703 */
7704 const successIconHtml = params => `
7705 ${params.animation ? '<div class="swal2-success-circular-line-left"></div>' : ''}
7706 <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>
7707 <div class="swal2-success-ring"></div>
7708 ${params.animation ? '<div class="swal2-success-fix"></div>' : ''}
7709 ${params.animation ? '<div class="swal2-success-circular-line-right"></div>' : ''}
7710 `;
7711 const errorIconHtml = `
7712 <span class="swal2-x-mark">
7713 <span class="swal2-x-mark-line-left"></span>
7714 <span class="swal2-x-mark-line-right"></span>
7715 </span>
7716 `;
7717
7718 /**
7719 * @param {HTMLElement} icon
7720 * @param {SweetAlertOptions} params
7721 */
7722 const setContent = (icon, params) => {
7723 if (!params.icon && !params.iconHtml) {
7724 return;
7725 }
7726 let oldContent = icon.innerHTML;
7727 let newContent = '';
7728 if (params.iconHtml) {
7729 newContent = iconContent(params.iconHtml);
7730 } else if (params.icon === 'success') {
7731 newContent = successIconHtml(params);
7732 oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor()
7733 } else if (params.icon === 'error') {
7734 newContent = errorIconHtml;
7735 } else if (params.icon) {
7736 const defaultIconHtml = {
7737 question: '?',
7738 warning: '!',
7739 info: 'i'
7740 };
7741 newContent = iconContent(defaultIconHtml[params.icon]);
7742 }
7743 if (oldContent.trim() !== newContent.trim()) {
7744 setInnerHtml(icon, newContent);
7745 }
7746 };
7747
7748 /**
7749 * @param {HTMLElement} icon
7750 * @param {SweetAlertOptions} params
7751 */
7752 const setColor = (icon, params) => {
7753 if (!params.iconColor) {
7754 return;
7755 }
7756 icon.style.color = params.iconColor;
7757 icon.style.borderColor = params.iconColor;
7758 for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
7759 setStyle(icon, sel, 'background-color', params.iconColor);
7760 }
7761 setStyle(icon, '.swal2-success-ring', 'border-color', params.iconColor);
7762 };
7763
7764 /**
7765 * @param {string} content
7766 * @returns {string}
7767 */
7768 const iconContent = content => `<div class="${swalClasses['icon-content']}">${content}</div>`;
7769
7770 /**
7771 * @param {SweetAlert} instance
7772 * @param {SweetAlertOptions} params
7773 */
7774 const renderImage = (instance, params) => {
7775 const image = getImage();
7776 if (!image) {
7777 return;
7778 }
7779 if (!params.imageUrl) {
7780 hide(image);
7781 return;
7782 }
7783 show(image, '');
7784
7785 // Src, alt
7786 image.setAttribute('src', params.imageUrl);
7787 image.setAttribute('alt', params.imageAlt || '');
7788
7789 // Width, height
7790 applyNumericalStyle(image, 'width', params.imageWidth);
7791 applyNumericalStyle(image, 'height', params.imageHeight);
7792
7793 // Class
7794 image.className = swalClasses.image;
7795 applyCustomClass(image, params, 'image');
7796 };
7797
7798 let dragging = false;
7799 let mousedownX = 0;
7800 let mousedownY = 0;
7801 let initialX = 0;
7802 let initialY = 0;
7803
7804 /**
7805 * @param {HTMLElement} popup
7806 */
7807 const addDraggableListeners = popup => {
7808 popup.addEventListener('mousedown', down);
7809 document.body.addEventListener('mousemove', move);
7810 popup.addEventListener('mouseup', up);
7811 popup.addEventListener('touchstart', down);
7812 document.body.addEventListener('touchmove', move);
7813 popup.addEventListener('touchend', up);
7814 };
7815
7816 /**
7817 * @param {HTMLElement} popup
7818 */
7819 const removeDraggableListeners = popup => {
7820 popup.removeEventListener('mousedown', down);
7821 document.body.removeEventListener('mousemove', move);
7822 popup.removeEventListener('mouseup', up);
7823 popup.removeEventListener('touchstart', down);
7824 document.body.removeEventListener('touchmove', move);
7825 popup.removeEventListener('touchend', up);
7826 };
7827
7828 /**
7829 * @param {MouseEvent | TouchEvent} event
7830 */
7831 const down = event => {
7832 const popup = getPopup();
7833 if (!popup) {
7834 return;
7835 }
7836 const icon = getIcon();
7837 if (event.target === popup || icon && icon.contains(/** @type {HTMLElement} */event.target)) {
7838 dragging = true;
7839 const clientXY = getClientXY(event);
7840 mousedownX = clientXY.clientX;
7841 mousedownY = clientXY.clientY;
7842 initialX = parseInt(popup.style.insetInlineStart) || 0;
7843 initialY = parseInt(popup.style.insetBlockStart) || 0;
7844 addClass(popup, 'swal2-dragging');
7845 }
7846 };
7847
7848 /**
7849 * @param {MouseEvent | TouchEvent} event
7850 */
7851 const move = event => {
7852 const popup = getPopup();
7853 if (!popup) {
7854 return;
7855 }
7856 if (dragging) {
7857 let {
7858 clientX,
7859 clientY
7860 } = getClientXY(event);
7861 const deltaX = clientX - mousedownX;
7862 // In RTL mode, negate the horizontal delta since insetInlineStart refers to the right edge
7863 popup.style.insetInlineStart = `${initialX + (globalState.isRTL ? -deltaX : deltaX)}px`;
7864 popup.style.insetBlockStart = `${initialY + (clientY - mousedownY)}px`;
7865 }
7866 };
7867 const up = () => {
7868 const popup = getPopup();
7869 dragging = false;
7870 removeClass(popup, 'swal2-dragging');
7871 };
7872
7873 /**
7874 * @param {MouseEvent | TouchEvent} event
7875 * @returns {{ clientX: number, clientY: number }}
7876 */
7877 const getClientXY = event => {
7878 const source = event.type.startsWith('touch') ? /** @type {TouchEvent} */event.touches[0] : (/** @type {MouseEvent} */event);
7879 return {
7880 clientX: source.clientX,
7881 clientY: source.clientY
7882 };
7883 };
7884
7885 /**
7886 * @param {SweetAlert} instance
7887 * @param {SweetAlertOptions} params
7888 */
7889 const renderPopup = (instance, params) => {
7890 const container = getContainer();
7891 const popup = getPopup();
7892 if (!container || !popup) {
7893 return;
7894 }
7895
7896 // Width
7897 // https://github.com/sweetalert2/sweetalert2/issues/2170
7898 if (params.toast) {
7899 applyNumericalStyle(container, 'width', params.width);
7900 popup.style.width = '100%';
7901 const loader = getLoader();
7902 if (loader) {
7903 popup.insertBefore(loader, getIcon());
7904 }
7905 } else {
7906 applyNumericalStyle(popup, 'width', params.width);
7907 }
7908
7909 // Padding
7910 applyNumericalStyle(popup, 'padding', params.padding);
7911
7912 // Color
7913 if (params.color) {
7914 popup.style.color = params.color;
7915 }
7916
7917 // Background
7918 if (params.background) {
7919 popup.style.background = params.background;
7920 }
7921 hide(getValidationMessage());
7922
7923 // Classes
7924 addClasses$1(popup, params);
7925 if (params.draggable && !params.toast) {
7926 addClass(popup, swalClasses.draggable);
7927 addDraggableListeners(popup);
7928 } else {
7929 removeClass(popup, swalClasses.draggable);
7930 removeDraggableListeners(popup);
7931 }
7932 };
7933
7934 /**
7935 * @param {HTMLElement} popup
7936 * @param {SweetAlertOptions} params
7937 */
7938 const addClasses$1 = (popup, params) => {
7939 const showClass = params.showClass || {};
7940 // Default Class + showClass when updating Swal.update({})
7941 popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? showClass.popup : ''}`;
7942 if (params.toast) {
7943 addClass([document.documentElement, document.body], swalClasses['toast-shown']);
7944 addClass(popup, swalClasses.toast);
7945 } else {
7946 addClass(popup, swalClasses.modal);
7947 }
7948
7949 // Custom class
7950 applyCustomClass(popup, params, 'popup');
7951 // TODO: remove in the next major
7952 if (typeof params.customClass === 'string') {
7953 addClass(popup, params.customClass);
7954 }
7955
7956 // Icon class (#1842)
7957 if (params.icon) {
7958 addClass(popup, swalClasses[`icon-${params.icon}`]);
7959 }
7960 };
7961
7962 /**
7963 * @param {SweetAlert} instance
7964 * @param {SweetAlertOptions} params
7965 */
7966 const renderProgressSteps = (instance, params) => {
7967 const progressStepsContainer = getProgressSteps();
7968 if (!progressStepsContainer) {
7969 return;
7970 }
7971 const {
7972 progressSteps,
7973 currentProgressStep
7974 } = params;
7975 if (!progressSteps || progressSteps.length === 0 || currentProgressStep === undefined) {
7976 hide(progressStepsContainer);
7977 return;
7978 }
7979 show(progressStepsContainer);
7980 progressStepsContainer.textContent = '';
7981 if (currentProgressStep >= progressSteps.length) {
7982 warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
7983 }
7984 progressSteps.forEach((step, index) => {
7985 const stepEl = createStepElement(step);
7986 progressStepsContainer.appendChild(stepEl);
7987 if (index === currentProgressStep) {
7988 addClass(stepEl, swalClasses['active-progress-step']);
7989 }
7990 if (index !== progressSteps.length - 1) {
7991 const lineEl = createLineElement(params);
7992 progressStepsContainer.appendChild(lineEl);
7993 }
7994 });
7995 };
7996
7997 /**
7998 * @param {string} step
7999 * @returns {HTMLLIElement}
8000 */
8001 const createStepElement = step => {
8002 const stepEl = document.createElement('li');
8003 addClass(stepEl, swalClasses['progress-step']);
8004 setInnerHtml(stepEl, step);
8005 return stepEl;
8006 };
8007
8008 /**
8009 * @param {SweetAlertOptions} params
8010 * @returns {HTMLLIElement}
8011 */
8012 const createLineElement = params => {
8013 const lineEl = document.createElement('li');
8014 addClass(lineEl, swalClasses['progress-step-line']);
8015 if (params.progressStepsDistance) {
8016 applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);
8017 }
8018 return lineEl;
8019 };
8020
8021 /**
8022 * @param {SweetAlert} instance
8023 * @param {SweetAlertOptions} params
8024 */
8025 const renderTitle = (instance, params) => {
8026 const title = getTitle();
8027 if (!title) {
8028 return;
8029 }
8030 showWhenInnerHtmlPresent(title);
8031 toggle(title, Boolean(params.title || params.titleText), 'block');
8032 if (params.title) {
8033 parseHtmlToContainer(params.title, title);
8034 }
8035 if (params.titleText) {
8036 title.innerText = params.titleText;
8037 }
8038
8039 // Custom class
8040 applyCustomClass(title, params, 'title');
8041 };
8042
8043 /**
8044 * @param {SweetAlert} instance
8045 * @param {SweetAlertOptions} params
8046 */
8047 const render = (instance, params) => {
8048 var _globalState$eventEmi;
8049 renderPopup(instance, params);
8050 renderContainer(instance, params);
8051 renderProgressSteps(instance, params);
8052 renderIcon(instance, params);
8053 renderImage(instance, params);
8054 renderTitle(instance, params);
8055 renderCloseButton(instance, params);
8056 renderContent(instance, params);
8057 renderActions(instance, params);
8058 renderFooter(instance, params);
8059 const popup = getPopup();
8060 if (typeof params.didRender === 'function' && popup) {
8061 params.didRender(popup);
8062 }
8063 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('didRender', popup);
8064 };
8065
8066 /*
8067 * Global function to determine if SweetAlert2 popup is shown
8068 */
8069 const isVisible = () => {
8070 return isVisible$1(getPopup());
8071 };
8072
8073 /*
8074 * Global function to click 'Confirm' button
8075 */
8076 const clickConfirm = () => {
8077 var _dom$getConfirmButton;
8078 return (_dom$getConfirmButton = getConfirmButton()) === null || _dom$getConfirmButton === void 0 ? void 0 : _dom$getConfirmButton.click();
8079 };
8080
8081 /*
8082 * Global function to click 'Deny' button
8083 */
8084 const clickDeny = () => {
8085 var _dom$getDenyButton;
8086 return (_dom$getDenyButton = getDenyButton()) === null || _dom$getDenyButton === void 0 ? void 0 : _dom$getDenyButton.click();
8087 };
8088
8089 /*
8090 * Global function to click 'Cancel' button
8091 */
8092 const clickCancel = () => {
8093 var _dom$getCancelButton;
8094 return (_dom$getCancelButton = getCancelButton()) === null || _dom$getCancelButton === void 0 ? void 0 : _dom$getCancelButton.click();
8095 };
8096
8097 /** @type {Record<DismissReason, DismissReason>} */
8098 const DismissReason = Object.freeze({
8099 cancel: 'cancel',
8100 backdrop: 'backdrop',
8101 close: 'close',
8102 esc: 'esc',
8103 timer: 'timer'
8104 });
8105
8106 /**
8107 * @param {GlobalState} globalState
8108 */
8109 const removeKeydownHandler = globalState => {
8110 if (globalState.keydownTarget && globalState.keydownHandlerAdded && globalState.keydownHandler) {
8111 const handler = /** @type {EventListenerOrEventListenerObject} */
8112 /** @type {unknown} */globalState.keydownHandler;
8113 globalState.keydownTarget.removeEventListener('keydown', handler, {
8114 capture: globalState.keydownListenerCapture
8115 });
8116 globalState.keydownHandlerAdded = false;
8117 }
8118 };
8119
8120 /**
8121 * @param {GlobalState} globalState
8122 * @param {SweetAlertOptions} innerParams
8123 * @param {(dismiss: DismissReason) => void} dismissWith
8124 */
8125 const addKeydownHandler = (globalState, innerParams, dismissWith) => {
8126 removeKeydownHandler(globalState);
8127 if (!innerParams.toast) {
8128 /** @type {(this: HTMLElement, event: KeyboardEvent) => void} */
8129 const handler = e => keydownHandler(innerParams, e, dismissWith);
8130 globalState.keydownHandler = handler;
8131 const target = innerParams.keydownListenerCapture ? window : getPopup();
8132 if (target) {
8133 globalState.keydownTarget = target;
8134 globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
8135 const eventHandler = /** @type {EventListenerOrEventListenerObject} */ /** @type {unknown} */handler;
8136 globalState.keydownTarget.addEventListener('keydown', eventHandler, {
8137 capture: globalState.keydownListenerCapture
8138 });
8139 globalState.keydownHandlerAdded = true;
8140 }
8141 }
8142 };
8143
8144 /**
8145 * @param {number} index
8146 * @param {number} increment
8147 * @returns {boolean} shouldPreventDefault
8148 */
8149 const setFocus = (index, increment) => {
8150 var _dom$getPopup;
8151 const focusableElements = getFocusableElements();
8152 // search for visible elements and select the next possible match
8153 if (focusableElements.length) {
8154 index = index + increment;
8155
8156 // shift + tab when .swal2-popup is focused
8157 if (index === -2) {
8158 index = focusableElements.length - 1;
8159 }
8160
8161 // rollover to first item
8162 if (index === focusableElements.length) {
8163 index = 0;
8164
8165 // go to last item
8166 } else if (index === -1) {
8167 index = focusableElements.length - 1;
8168 }
8169 focusableElements[index].focus();
8170
8171 // don't prevent default for iframes (Firefox fix)
8172 // https://github.com/sweetalert2/sweetalert2/issues/2931
8173 if (isFirefox() && focusableElements[index] instanceof HTMLIFrameElement) {
8174 return false;
8175 }
8176 return true;
8177 }
8178 // no visible focusable elements, focus the popup
8179 (_dom$getPopup = getPopup()) === null || _dom$getPopup === void 0 || _dom$getPopup.focus();
8180 return true;
8181 };
8182 const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
8183 const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
8184
8185 /**
8186 * @param {SweetAlertOptions} innerParams
8187 * @param {KeyboardEvent} event
8188 * @param {(dismiss: DismissReason) => void} dismissWith
8189 */
8190 const keydownHandler = (innerParams, event, dismissWith) => {
8191 if (!innerParams) {
8192 return; // This instance has already been destroyed
8193 }
8194
8195 // Ignore keydown during IME composition
8196 // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition
8197 // https://github.com/sweetalert2/sweetalert2/issues/720
8198 // https://github.com/sweetalert2/sweetalert2/issues/2406
8199 if (event.isComposing || event.keyCode === 229) {
8200 return;
8201 }
8202 if (innerParams.stopKeydownPropagation) {
8203 event.stopPropagation();
8204 }
8205
8206 // ENTER
8207 if (event.key === 'Enter') {
8208 handleEnter(event, innerParams);
8209 }
8210
8211 // TAB
8212 else if (event.key === 'Tab') {
8213 handleTab(event);
8214 }
8215
8216 // ARROWS - switch focus between buttons
8217 else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) {
8218 handleArrows(event.key);
8219 }
8220
8221 // ESC
8222 else if (event.key === 'Escape') {
8223 handleEsc(event, innerParams, dismissWith);
8224 }
8225 };
8226
8227 /**
8228 * @param {KeyboardEvent} event
8229 * @param {SweetAlertOptions} innerParams
8230 */
8231 const handleEnter = (event, innerParams) => {
8232 // https://github.com/sweetalert2/sweetalert2/issues/2386
8233 if (!callIfFunction(innerParams.allowEnterKey)) {
8234 return;
8235 }
8236 const popup = getPopup();
8237 if (!popup || !innerParams.input) {
8238 return;
8239 }
8240 const input = getInput$1(popup, innerParams.input);
8241 if (event.target && input && event.target instanceof HTMLElement && event.target.outerHTML === input.outerHTML) {
8242 if (['textarea', 'file'].includes(innerParams.input)) {
8243 return; // do not submit
8244 }
8245 clickConfirm();
8246 event.preventDefault();
8247 }
8248 };
8249
8250 /**
8251 * @param {KeyboardEvent} event
8252 */
8253 const handleTab = event => {
8254 const targetElement = event.target;
8255 const focusableElements = getFocusableElements();
8256 const btnIndex = focusableElements.findIndex(el => el === targetElement);
8257
8258 // don't prevent default for iframes (Firefox fix)
8259 // https://github.com/sweetalert2/sweetalert2/issues/2931
8260 let shouldPreventDefault = true;
8261
8262 // Cycle to the next button
8263 if (!event.shiftKey) {
8264 shouldPreventDefault = setFocus(btnIndex, 1);
8265 }
8266
8267 // Cycle to the prev button
8268 else {
8269 shouldPreventDefault = setFocus(btnIndex, -1);
8270 }
8271 event.stopPropagation();
8272 if (shouldPreventDefault) {
8273 event.preventDefault();
8274 }
8275 };
8276
8277 /**
8278 * @param {string} key
8279 */
8280 const handleArrows = key => {
8281 const actions = getActions();
8282 const confirmButton = getConfirmButton();
8283 const denyButton = getDenyButton();
8284 const cancelButton = getCancelButton();
8285 if (!actions || !confirmButton || !denyButton || !cancelButton) {
8286 return;
8287 }
8288 /** @type HTMLElement[] */
8289 const buttons = [confirmButton, denyButton, cancelButton];
8290 if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) {
8291 return;
8292 }
8293 const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
8294 let buttonToFocus = document.activeElement;
8295 if (!buttonToFocus) {
8296 return;
8297 }
8298 for (let i = 0; i < actions.children.length; i++) {
8299 buttonToFocus = buttonToFocus[sibling];
8300 if (!buttonToFocus) {
8301 return;
8302 }
8303 if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) {
8304 break;
8305 }
8306 }
8307 if (buttonToFocus instanceof HTMLButtonElement) {
8308 buttonToFocus.focus();
8309 }
8310 };
8311
8312 /**
8313 * @param {KeyboardEvent} event
8314 * @param {SweetAlertOptions} innerParams
8315 * @param {(dismiss: DismissReason) => void} dismissWith
8316 */
8317 const handleEsc = (event, innerParams, dismissWith) => {
8318 event.preventDefault();
8319 if (callIfFunction(innerParams.allowEscapeKey)) {
8320 dismissWith(DismissReason.esc);
8321 }
8322 };
8323
8324 /**
8325 * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
8326 * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
8327 * This is the approach that Babel will probably take to implement private methods/fields
8328 * https://github.com/tc39/proposal-private-methods
8329 * https://github.com/babel/babel/pull/7555
8330 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
8331 * then we can use that language feature.
8332 */
8333
8334 var privateMethods = {
8335 swalPromiseResolve: new WeakMap(),
8336 swalPromiseReject: new WeakMap()
8337 };
8338
8339 // From https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/
8340 // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
8341 // elements not within the active modal dialog will not be surfaced if a user opens a screen
8342 // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
8343
8344 const setAriaHidden = () => {
8345 const container = getContainer();
8346 const bodyChildren = Array.from(document.body.children);
8347 bodyChildren.forEach(el => {
8348 if (el.contains(container)) {
8349 return;
8350 }
8351 if (el.hasAttribute('aria-hidden')) {
8352 el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden') || '');
8353 }
8354 el.setAttribute('aria-hidden', 'true');
8355 });
8356 };
8357 const unsetAriaHidden = () => {
8358 const bodyChildren = Array.from(document.body.children);
8359 bodyChildren.forEach(el => {
8360 if (el.hasAttribute('data-previous-aria-hidden')) {
8361 el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden') || '');
8362 el.removeAttribute('data-previous-aria-hidden');
8363 } else {
8364 el.removeAttribute('aria-hidden');
8365 }
8366 });
8367 };
8368
8369 // @ts-ignore
8370 const isSafariOrIOS = typeof window !== 'undefined' && Boolean(window.GestureEvent); // true for Safari desktop + all iOS browsers https://stackoverflow.com/a/70585394
8371
8372 // @ts-ignore
8373 const isIOS = isSafariOrIOS && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
8374
8375 /**
8376 * Fix iOS scrolling
8377 * http://stackoverflow.com/q/39626302
8378 */
8379 const iOSfix = () => {
8380 if (isSafariOrIOS && !hasClass(document.body, swalClasses.iosfix)) {
8381 const offset = document.body.scrollTop;
8382 document.body.style.top = `${offset * -1}px`;
8383 addClass(document.body, swalClasses.iosfix);
8384 lockBodyScroll();
8385 }
8386 };
8387
8388 /**
8389 * https://github.com/sweetalert2/sweetalert2/issues/1246
8390 */
8391 const lockBodyScroll = () => {
8392 const container = getContainer();
8393 if (!container) {
8394 return;
8395 }
8396 /** @type {boolean} */
8397 let preventTouchMove;
8398 /**
8399 * @param {TouchEvent} event
8400 */
8401 container.ontouchstart = event => {
8402 preventTouchMove = shouldPreventTouchMove(event);
8403 };
8404 /**
8405 * @param {TouchEvent} event
8406 */
8407 container.ontouchmove = event => {
8408 if (preventTouchMove) {
8409 event.preventDefault();
8410 event.stopPropagation();
8411 }
8412 };
8413 };
8414
8415 /**
8416 * @param {TouchEvent} event
8417 * @returns {boolean}
8418 */
8419 const shouldPreventTouchMove = event => {
8420 const target = event.target;
8421 const container = getContainer();
8422 const htmlContainer = getHtmlContainer();
8423 if (!container || !htmlContainer) {
8424 return false;
8425 }
8426 if (isStylus(event) || isZoom(event)) {
8427 return false;
8428 }
8429 if (target === container) {
8430 return true;
8431 }
8432 if (!isScrollable(container) && target instanceof HTMLElement && !selfOrParentIsScrollable(target, htmlContainer) &&
8433 // #2823
8434 target.tagName !== 'INPUT' &&
8435 // #1603
8436 target.tagName !== 'TEXTAREA' &&
8437 // #2266
8438 !(isScrollable(htmlContainer) &&
8439 // #1944
8440 htmlContainer.contains(target))) {
8441 return true;
8442 }
8443 return false;
8444 };
8445
8446 /**
8447 * https://github.com/sweetalert2/sweetalert2/issues/1786
8448 *
8449 * @param {TouchEvent} event
8450 * @returns {boolean}
8451 */
8452 const isStylus = event => {
8453 return Boolean(event.touches && event.touches.length &&
8454 // @ts-ignore - touchType is not a standard property
8455 event.touches[0].touchType === 'stylus');
8456 };
8457
8458 /**
8459 * https://github.com/sweetalert2/sweetalert2/issues/1891
8460 *
8461 * @param {TouchEvent} event
8462 * @returns {boolean}
8463 */
8464 const isZoom = event => {
8465 return event.touches && event.touches.length > 1;
8466 };
8467 const undoIOSfix = () => {
8468 if (hasClass(document.body, swalClasses.iosfix)) {
8469 const offset = parseInt(document.body.style.top, 10);
8470 removeClass(document.body, swalClasses.iosfix);
8471 document.body.style.top = '';
8472 document.body.scrollTop = offset * -1;
8473 }
8474 };
8475
8476 /**
8477 * Measure scrollbar width for padding body during modal show/hide
8478 * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
8479 *
8480 * @returns {number}
8481 */
8482 const measureScrollbar = () => {
8483 const scrollDiv = document.createElement('div');
8484 scrollDiv.className = swalClasses['scrollbar-measure'];
8485 document.body.appendChild(scrollDiv);
8486 const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
8487 document.body.removeChild(scrollDiv);
8488 return scrollbarWidth;
8489 };
8490
8491 /**
8492 * Remember state in cases where opening and handling a modal will fiddle with it.
8493 * @type {number | null}
8494 */
8495 let previousBodyPadding = null;
8496
8497 /**
8498 * @param {string} initialBodyOverflow
8499 */
8500 const replaceScrollbarWithPadding = initialBodyOverflow => {
8501 // for queues, do not do this more than once
8502 if (previousBodyPadding !== null) {
8503 return;
8504 }
8505 // if the body has overflow
8506 if (document.body.scrollHeight > window.innerHeight || initialBodyOverflow === 'scroll' // https://github.com/sweetalert2/sweetalert2/issues/2663
8507 ) {
8508 // add padding so the content doesn't shift after removal of scrollbar
8509 previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
8510 document.body.style.paddingRight = `${previousBodyPadding + measureScrollbar()}px`;
8511 }
8512 };
8513 const undoReplaceScrollbarWithPadding = () => {
8514 if (previousBodyPadding !== null) {
8515 document.body.style.paddingRight = `${previousBodyPadding}px`;
8516 previousBodyPadding = null;
8517 }
8518 };
8519
8520 /**
8521 * @param {SweetAlert} instance
8522 * @param {HTMLElement} container
8523 * @param {boolean} returnFocus
8524 * @param {(() => void) | undefined} didClose
8525 */
8526 function removePopupAndResetState(instance, container, returnFocus, didClose) {
8527 if (isToast()) {
8528 triggerDidCloseAndDispose(instance, didClose);
8529 } else {
8530 restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
8531 removeKeydownHandler(globalState);
8532 }
8533
8534 // workaround for https://github.com/sweetalert2/sweetalert2/issues/2088
8535 // for some reason removing the container in Safari will scroll the document to bottom
8536 if (isSafariOrIOS) {
8537 container.setAttribute('style', 'display:none !important');
8538 container.removeAttribute('class');
8539 container.innerHTML = '';
8540 } else {
8541 container.remove();
8542 }
8543 if (isModal()) {
8544 undoReplaceScrollbarWithPadding();
8545 undoIOSfix();
8546 unsetAriaHidden();
8547 }
8548 removeBodyClasses();
8549 }
8550
8551 /**
8552 * Remove SweetAlert2 classes from body
8553 */
8554 function removeBodyClasses() {
8555 removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
8556 }
8557
8558 /**
8559 * Instance method to close sweetAlert
8560 *
8561 * @param {SweetAlertResult | undefined} resolveValue
8562 * @this {SweetAlert}
8563 */
8564 function close(resolveValue) {
8565 resolveValue = prepareResolveValue(resolveValue);
8566 const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
8567 const didClose = triggerClosePopup(this);
8568 if (this.isAwaitingPromise) {
8569 // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
8570 if (!resolveValue.isDismissed) {
8571 handleAwaitingPromise(this);
8572 swalPromiseResolve(resolveValue);
8573 }
8574 } else if (didClose) {
8575 // Resolve Swal promise
8576 swalPromiseResolve(resolveValue);
8577 }
8578 }
8579
8580 /**
8581 * @param {SweetAlert} instance
8582 * @returns {boolean}
8583 */
8584 const triggerClosePopup = instance => {
8585 const popup = getPopup();
8586 if (!popup) {
8587 return false;
8588 }
8589 const innerParams = privateProps.innerParams.get(instance);
8590 if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
8591 return false;
8592 }
8593 removeClass(popup, innerParams.showClass.popup);
8594 addClass(popup, innerParams.hideClass.popup);
8595 const backdrop = getContainer();
8596 removeClass(backdrop, innerParams.showClass.backdrop);
8597 addClass(backdrop, innerParams.hideClass.backdrop);
8598 handlePopupAnimation(instance, popup, innerParams);
8599 return true;
8600 };
8601
8602 /**
8603 * @param {Error | string} error
8604 * @this {SweetAlert}
8605 */
8606 function rejectPromise(error) {
8607 const rejectPromise = privateMethods.swalPromiseReject.get(this);
8608 handleAwaitingPromise(this);
8609 if (rejectPromise) {
8610 // Reject Swal promise
8611 rejectPromise(error);
8612 }
8613 }
8614
8615 /**
8616 * @param {SweetAlert} instance
8617 */
8618 const handleAwaitingPromise = instance => {
8619 if (instance.isAwaitingPromise) {
8620 // @ts-ignore
8621 delete instance.isAwaitingPromise;
8622 // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
8623 if (!privateProps.innerParams.get(instance)) {
8624 instance._destroy();
8625 }
8626 }
8627 };
8628
8629 /**
8630 * @param {SweetAlertResult | undefined} resolveValue
8631 * @returns {SweetAlertResult}
8632 */
8633 const prepareResolveValue = resolveValue => {
8634 // When user calls Swal.close()
8635 if (typeof resolveValue === 'undefined') {
8636 return {
8637 isConfirmed: false,
8638 isDenied: false,
8639 isDismissed: true
8640 };
8641 }
8642 return Object.assign({
8643 isConfirmed: false,
8644 isDenied: false,
8645 isDismissed: false
8646 }, resolveValue);
8647 };
8648
8649 /**
8650 * @param {SweetAlert} instance
8651 * @param {HTMLElement} popup
8652 * @param {SweetAlertOptions} innerParams
8653 */
8654 const handlePopupAnimation = (instance, popup, innerParams) => {
8655 var _globalState$eventEmi;
8656 const container = getContainer();
8657 // If animation is supported, animate
8658 const animationIsSupported = hasCssAnimation(popup);
8659 if (typeof innerParams.willClose === 'function') {
8660 innerParams.willClose(popup);
8661 }
8662 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('willClose', popup);
8663 if (animationIsSupported && container) {
8664 animatePopup(instance, popup, container, Boolean(innerParams.returnFocus), innerParams.didClose);
8665 } else if (container) {
8666 // Otherwise, remove immediately
8667 removePopupAndResetState(instance, container, Boolean(innerParams.returnFocus), innerParams.didClose);
8668 }
8669 };
8670
8671 /**
8672 * @param {SweetAlert} instance
8673 * @param {HTMLElement} popup
8674 * @param {HTMLElement} container
8675 * @param {boolean} returnFocus
8676 * @param {(() => void) | undefined} didClose
8677 */
8678 const animatePopup = (instance, popup, container, returnFocus, didClose) => {
8679 globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
8680 /**
8681 * @param {AnimationEvent | TransitionEvent} e
8682 */
8683 const swalCloseAnimationFinished = function (e) {
8684 if (e.target === popup) {
8685 var _globalState$swalClos;
8686 (_globalState$swalClos = globalState.swalCloseEventFinishedCallback) === null || _globalState$swalClos === void 0 || _globalState$swalClos.call(globalState);
8687 delete globalState.swalCloseEventFinishedCallback;
8688 popup.removeEventListener('animationend', swalCloseAnimationFinished);
8689 popup.removeEventListener('transitionend', swalCloseAnimationFinished);
8690 }
8691 };
8692 popup.addEventListener('animationend', swalCloseAnimationFinished);
8693 popup.addEventListener('transitionend', swalCloseAnimationFinished);
8694 };
8695
8696 /**
8697 * @param {SweetAlert} instance
8698 * @param {(() => void) | undefined} didClose
8699 */
8700 const triggerDidCloseAndDispose = (instance, didClose) => {
8701 setTimeout(() => {
8702 var _globalState$eventEmi2;
8703 if (typeof didClose === 'function') {
8704 didClose.bind(instance.params)();
8705 }
8706 (_globalState$eventEmi2 = globalState.eventEmitter) === null || _globalState$eventEmi2 === void 0 || _globalState$eventEmi2.emit('didClose');
8707 // instance might have been destroyed already
8708 if (instance._destroy) {
8709 instance._destroy();
8710 }
8711 });
8712 };
8713
8714 /**
8715 * Shows loader (spinner), this is useful with AJAX requests.
8716 * By default the loader be shown instead of the "Confirm" button.
8717 *
8718 * @param {HTMLButtonElement | null} [buttonToReplace]
8719 */
8720 const showLoading = buttonToReplace => {
8721 let popup = getPopup();
8722 if (!popup) {
8723 new Swal();
8724 }
8725 popup = getPopup();
8726 if (!popup) {
8727 return;
8728 }
8729 const loader = getLoader();
8730 if (isToast()) {
8731 hide(getIcon());
8732 } else {
8733 replaceButton(popup, buttonToReplace);
8734 }
8735 show(loader);
8736 popup.setAttribute('data-loading', 'true');
8737 popup.setAttribute('aria-busy', 'true');
8738 popup.focus();
8739 };
8740
8741 /**
8742 * @param {HTMLElement} popup
8743 * @param {HTMLButtonElement | null} [buttonToReplace]
8744 */
8745 const replaceButton = (popup, buttonToReplace) => {
8746 const actions = getActions();
8747 const loader = getLoader();
8748 if (!actions || !loader) {
8749 return;
8750 }
8751 if (!buttonToReplace && isVisible$1(getConfirmButton())) {
8752 buttonToReplace = getConfirmButton();
8753 }
8754 show(actions);
8755 if (buttonToReplace) {
8756 hide(buttonToReplace);
8757 loader.setAttribute('data-button-to-replace', buttonToReplace.className);
8758 actions.insertBefore(loader, buttonToReplace);
8759 }
8760 addClass([popup, actions], swalClasses.loading);
8761 };
8762
8763 /**
8764 * @param {SweetAlert} instance
8765 * @param {SweetAlertOptions} params
8766 */
8767 const handleInputOptionsAndValue = (instance, params) => {
8768 if (params.input === 'select' || params.input === 'radio') {
8769 handleInputOptions(instance, params);
8770 } else if (['text', 'email', 'number', 'tel', 'textarea'].some(i => i === params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
8771 showLoading(getConfirmButton());
8772 handleInputValue(instance, params);
8773 }
8774 };
8775
8776 /**
8777 * @param {SweetAlert} instance
8778 * @param {SweetAlertOptions} innerParams
8779 * @returns {SweetAlertInputValue}
8780 */
8781 const getInputValue = (instance, innerParams) => {
8782 const input = instance.getInput();
8783 if (!input) {
8784 return null;
8785 }
8786 switch (innerParams.input) {
8787 case 'checkbox':
8788 return getCheckboxValue(input);
8789 case 'radio':
8790 return getRadioValue(input);
8791 case 'file':
8792 return getFileValue(input);
8793 default:
8794 return innerParams.inputAutoTrim ? input.value.trim() : input.value;
8795 }
8796 };
8797
8798 /**
8799 * @param {HTMLInputElement} input
8800 * @returns {number}
8801 */
8802 const getCheckboxValue = input => input.checked ? 1 : 0;
8803
8804 /**
8805 * @param {HTMLInputElement} input
8806 * @returns {string | null}
8807 */
8808 const getRadioValue = input => input.checked ? input.value : null;
8809
8810 /**
8811 * @param {HTMLInputElement} input
8812 * @returns {FileList | File | null}
8813 */
8814 const getFileValue = input => input.files && input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
8815
8816 /**
8817 * @param {SweetAlert} instance
8818 * @param {SweetAlertOptions} params
8819 */
8820 const handleInputOptions = (instance, params) => {
8821 const popup = getPopup();
8822 if (!popup) {
8823 return;
8824 }
8825 /**
8826 * @param {*} inputOptions
8827 */
8828 const processInputOptions = inputOptions => {
8829 if (params.input === 'select') {
8830 populateSelectOptions(popup, formatInputOptions(inputOptions), params);
8831 } else if (params.input === 'radio') {
8832 populateRadioOptions(popup, formatInputOptions(inputOptions), params);
8833 }
8834 };
8835 if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
8836 showLoading(getConfirmButton());
8837 asPromise(params.inputOptions).then(inputOptions => {
8838 instance.hideLoading();
8839 processInputOptions(inputOptions);
8840 });
8841 } else if (typeof params.inputOptions === 'object') {
8842 processInputOptions(params.inputOptions);
8843 } else {
8844 error(`Unexpected type of inputOptions! Expected object, Map or Promise, got ${typeof params.inputOptions}`);
8845 }
8846 };
8847
8848 /**
8849 * @param {SweetAlert} instance
8850 * @param {SweetAlertOptions} params
8851 */
8852 const handleInputValue = (instance, params) => {
8853 const input = instance.getInput();
8854 if (!input) {
8855 return;
8856 }
8857 hide(input);
8858 asPromise(params.inputValue).then(inputValue => {
8859 input.value = params.input === 'number' ? `${parseFloat(inputValue) || 0}` : `${inputValue}`;
8860 show(input);
8861 input.focus();
8862 instance.hideLoading();
8863 }).catch(err => {
8864 error(`Error in inputValue promise: ${err}`);
8865 input.value = '';
8866 show(input);
8867 input.focus();
8868 instance.hideLoading();
8869 });
8870 };
8871
8872 /**
8873 * @param {HTMLElement} popup
8874 * @param {InputOptionFlattened[]} inputOptions
8875 * @param {SweetAlertOptions} params
8876 */
8877 function populateSelectOptions(popup, inputOptions, params) {
8878 const select = getDirectChildByClass(popup, swalClasses.select);
8879 if (!select) {
8880 return;
8881 }
8882 /**
8883 * @param {HTMLElement} parent
8884 * @param {string} optionLabel
8885 * @param {string} optionValue
8886 */
8887 const renderOption = (parent, optionLabel, optionValue) => {
8888 const option = document.createElement('option');
8889 option.value = optionValue;
8890 setInnerHtml(option, optionLabel);
8891 option.selected = isSelected(optionValue, params.inputValue);
8892 parent.appendChild(option);
8893 };
8894 inputOptions.forEach(inputOption => {
8895 const optionValue = inputOption[0];
8896 const optionLabel = inputOption[1];
8897 // <optgroup> spec:
8898 // https://www.w3.org/TR/html401/interact/forms.html#h-17.6
8899 // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
8900 // check whether this is a <optgroup>
8901 if (Array.isArray(optionLabel)) {
8902 // if it is an array, then it is an <optgroup>
8903 const optgroup = document.createElement('optgroup');
8904 optgroup.label = optionValue;
8905 optgroup.disabled = false; // not configurable for now
8906 select.appendChild(optgroup);
8907 optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
8908 } else {
8909 // case of <option>
8910 renderOption(select, optionLabel, optionValue);
8911 }
8912 });
8913 select.focus();
8914 }
8915
8916 /**
8917 * @param {HTMLElement} popup
8918 * @param {InputOptionFlattened[]} inputOptions
8919 * @param {SweetAlertOptions} params
8920 */
8921 function populateRadioOptions(popup, inputOptions, params) {
8922 const radio = getDirectChildByClass(popup, swalClasses.radio);
8923 if (!radio) {
8924 return;
8925 }
8926 inputOptions.forEach(inputOption => {
8927 const radioValue = inputOption[0];
8928 const radioLabel = inputOption[1];
8929 const radioInput = document.createElement('input');
8930 const radioLabelElement = document.createElement('label');
8931 radioInput.type = 'radio';
8932 radioInput.name = swalClasses.radio;
8933 radioInput.value = radioValue;
8934 if (isSelected(radioValue, params.inputValue)) {
8935 radioInput.checked = true;
8936 }
8937 const label = document.createElement('span');
8938 setInnerHtml(label, radioLabel);
8939 label.className = swalClasses.label;
8940 radioLabelElement.appendChild(radioInput);
8941 radioLabelElement.appendChild(label);
8942 radio.appendChild(radioLabelElement);
8943 });
8944 const radios = radio.querySelectorAll('input');
8945 if (radios.length) {
8946 radios[0].focus();
8947 }
8948 }
8949
8950 /**
8951 * Converts `inputOptions` into an array of `[value, label]`s
8952 *
8953 * @param {*} inputOptions
8954 * @typedef {string[]} InputOptionFlattened
8955 * @returns {InputOptionFlattened[]}
8956 */
8957 const formatInputOptions = inputOptions => {
8958 const entries = inputOptions instanceof Map ? Array.from(inputOptions) : Object.entries(inputOptions);
8959 return entries.map(([key, value]) => [key, typeof value === 'object' ? formatInputOptions(value) : value]); // case of <optgroup>
8960 };
8961
8962 /**
8963 * @param {string} optionValue
8964 * @param {SweetAlertInputValue} inputValue
8965 * @returns {boolean}
8966 */
8967 const isSelected = (optionValue, inputValue) => Boolean(inputValue) && inputValue != null && inputValue.toString() === optionValue.toString();
8968
8969 /**
8970 * @param {SweetAlert} instance
8971 */
8972 const handleConfirmButtonClick = instance => {
8973 const innerParams = privateProps.innerParams.get(instance);
8974 instance.disableButtons();
8975 if (innerParams.input) {
8976 handleConfirmOrDenyWithInput(instance, 'confirm');
8977 } else {
8978 confirm(instance, true);
8979 }
8980 };
8981
8982 /**
8983 * @param {SweetAlert} instance
8984 */
8985 const handleDenyButtonClick = instance => {
8986 const innerParams = privateProps.innerParams.get(instance);
8987 instance.disableButtons();
8988 if (innerParams.returnInputValueOnDeny) {
8989 handleConfirmOrDenyWithInput(instance, 'deny');
8990 } else {
8991 deny(instance, false);
8992 }
8993 };
8994
8995 /**
8996 * @param {SweetAlert} instance
8997 * @param {(dismiss: DismissReason) => void} dismissWith
8998 */
8999 const handleCancelButtonClick = (instance, dismissWith) => {
9000 instance.disableButtons();
9001 dismissWith(DismissReason.cancel);
9002 };
9003
9004 /**
9005 * @param {SweetAlert} instance
9006 * @param {'confirm' | 'deny'} type
9007 */
9008 const handleConfirmOrDenyWithInput = (instance, type) => {
9009 const innerParams = privateProps.innerParams.get(instance);
9010 if (!innerParams.input) {
9011 error(`The "input" parameter is needed to be set when using returnInputValueOn${capitalizeFirstLetter(type)}`);
9012 return;
9013 }
9014 const input = instance.getInput();
9015 const inputValue = getInputValue(instance, innerParams);
9016 if (innerParams.inputValidator) {
9017 handleInputValidator(instance, inputValue, type);
9018 } else if (input && !input.checkValidity()) {
9019 instance.enableButtons();
9020 instance.showValidationMessage(innerParams.validationMessage || input.validationMessage);
9021 } else if (type === 'deny') {
9022 deny(instance, inputValue);
9023 } else {
9024 confirm(instance, inputValue);
9025 }
9026 };
9027
9028 /**
9029 * @param {SweetAlert} instance
9030 * @param {SweetAlertInputValue} inputValue
9031 * @param {'confirm' | 'deny'} type
9032 */
9033 const handleInputValidator = (instance, inputValue, type) => {
9034 const innerParams = privateProps.innerParams.get(instance);
9035 instance.disableInput();
9036 const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
9037 validationPromise.then(validationMessage => {
9038 instance.enableButtons();
9039 instance.enableInput();
9040 if (validationMessage) {
9041 instance.showValidationMessage(validationMessage);
9042 } else if (type === 'deny') {
9043 deny(instance, inputValue);
9044 } else {
9045 confirm(instance, inputValue);
9046 }
9047 });
9048 };
9049
9050 /**
9051 * @param {SweetAlert} instance
9052 * @param {*} value
9053 */
9054 const deny = (instance, value) => {
9055 const innerParams = privateProps.innerParams.get(instance);
9056 if (innerParams.showLoaderOnDeny) {
9057 showLoading(getDenyButton());
9058 }
9059 if (innerParams.preDeny) {
9060 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
9061 const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
9062 preDenyPromise.then(preDenyValue => {
9063 if (preDenyValue === false) {
9064 instance.hideLoading();
9065 handleAwaitingPromise(instance);
9066 } else {
9067 instance.close(/** @type SweetAlertResult */{
9068 isDenied: true,
9069 value: typeof preDenyValue === 'undefined' ? value : preDenyValue
9070 });
9071 }
9072 }).catch(error => rejectWith(instance, error));
9073 } else {
9074 instance.close(/** @type SweetAlertResult */{
9075 isDenied: true,
9076 value
9077 });
9078 }
9079 };
9080
9081 /**
9082 * @param {SweetAlert} instance
9083 * @param {*} value
9084 */
9085 const succeedWith = (instance, value) => {
9086 instance.close(/** @type SweetAlertResult */{
9087 isConfirmed: true,
9088 value
9089 });
9090 };
9091
9092 /**
9093 *
9094 * @param {SweetAlert} instance
9095 * @param {string} error
9096 */
9097 const rejectWith = (instance, error) => {
9098 instance.rejectPromise(error);
9099 };
9100
9101 /**
9102 *
9103 * @param {SweetAlert} instance
9104 * @param {*} value
9105 */
9106 const confirm = (instance, value) => {
9107 const innerParams = privateProps.innerParams.get(instance);
9108 if (innerParams.showLoaderOnConfirm) {
9109 showLoading();
9110 }
9111 if (innerParams.preConfirm) {
9112 instance.resetValidationMessage();
9113 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
9114 const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
9115 preConfirmPromise.then(preConfirmValue => {
9116 if (isVisible$1(getValidationMessage()) || preConfirmValue === false) {
9117 instance.hideLoading();
9118 handleAwaitingPromise(instance);
9119 } else {
9120 succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
9121 }
9122 }).catch(error => rejectWith(instance, error));
9123 } else {
9124 succeedWith(instance, value);
9125 }
9126 };
9127
9128 /**
9129 * Hides loader and shows back the button which was hidden by .showLoading()
9130 * @this {SweetAlert}
9131 */
9132 function hideLoading() {
9133 // do nothing if popup is closed
9134 const innerParams = privateProps.innerParams.get(this);
9135 if (!innerParams) {
9136 return;
9137 }
9138 const domCache = privateProps.domCache.get(this);
9139 hide(domCache.loader);
9140 if (isToast()) {
9141 if (innerParams.icon) {
9142 show(getIcon());
9143 }
9144 } else {
9145 showRelatedButton(domCache);
9146 }
9147 removeClass([domCache.popup, domCache.actions], swalClasses.loading);
9148 domCache.popup.removeAttribute('aria-busy');
9149 domCache.popup.removeAttribute('data-loading');
9150 this.enableButtons();
9151 }
9152
9153 /**
9154 * @param {DomCache} domCache
9155 */
9156 const showRelatedButton = domCache => {
9157 const dataButtonToReplace = domCache.loader.getAttribute('data-button-to-replace');
9158 const buttonToReplace = dataButtonToReplace ? domCache.popup.getElementsByClassName(dataButtonToReplace) : [];
9159 if (buttonToReplace.length) {
9160 show(/** @type {HTMLElement} */buttonToReplace[0], 'inline-block');
9161 } else if (allButtonsAreHidden()) {
9162 hide(domCache.actions);
9163 }
9164 };
9165
9166 /**
9167 * Gets the input DOM node, this method works with input parameter.
9168 *
9169 * @returns {HTMLInputElement | null}
9170 * @this {SweetAlert}
9171 */
9172 function getInput() {
9173 const innerParams = privateProps.innerParams.get(this);
9174 const domCache = privateProps.domCache.get(this);
9175 if (!domCache) {
9176 return null;
9177 }
9178 return getInput$1(domCache.popup, innerParams.input);
9179 }
9180
9181 /**
9182 * @param {SweetAlert} instance
9183 * @param {string[]} buttons
9184 * @param {boolean} disabled
9185 */
9186 function setButtonsDisabled(instance, buttons, disabled) {
9187 const domCache = privateProps.domCache.get(instance);
9188 buttons.forEach(button => {
9189 domCache[button].disabled = disabled;
9190 });
9191 }
9192
9193 /**
9194 * @param {HTMLInputElement | null} input
9195 * @param {boolean} disabled
9196 */
9197 function setInputDisabled(input, disabled) {
9198 const popup = getPopup();
9199 if (!popup || !input) {
9200 return;
9201 }
9202 if (input.type === 'radio') {
9203 /** @type {NodeListOf<HTMLInputElement>} */
9204 const radios = popup.querySelectorAll(`[name="${swalClasses.radio}"]`);
9205 radios.forEach(radio => {
9206 radio.disabled = disabled;
9207 });
9208 } else {
9209 input.disabled = disabled;
9210 }
9211 }
9212
9213 /**
9214 * Enable all the buttons
9215 * @this {SweetAlert}
9216 */
9217 function enableButtons() {
9218 setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
9219 const focusedElement = privateProps.focusedElement.get(this);
9220 if (focusedElement instanceof HTMLElement && document.activeElement === document.body) {
9221 focusedElement.focus();
9222 }
9223 privateProps.focusedElement.delete(this);
9224 }
9225
9226 /**
9227 * Disable all the buttons
9228 * @this {SweetAlert}
9229 */
9230 function disableButtons() {
9231 privateProps.focusedElement.set(this, document.activeElement);
9232 setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
9233 }
9234
9235 /**
9236 * Enable the input field
9237 * @this {SweetAlert}
9238 */
9239 function enableInput() {
9240 setInputDisabled(this.getInput(), false);
9241 }
9242
9243 /**
9244 * Disable the input field
9245 * @this {SweetAlert}
9246 */
9247 function disableInput() {
9248 setInputDisabled(this.getInput(), true);
9249 }
9250
9251 /**
9252 * Show block with validation message
9253 *
9254 * @param {string} error
9255 * @this {SweetAlert}
9256 */
9257 function showValidationMessage(error) {
9258 const domCache = privateProps.domCache.get(this);
9259 const params = privateProps.innerParams.get(this);
9260 setInnerHtml(domCache.validationMessage, error);
9261 domCache.validationMessage.className = swalClasses['validation-message'];
9262 if (params.customClass && params.customClass.validationMessage) {
9263 addClass(domCache.validationMessage, params.customClass.validationMessage);
9264 }
9265 show(domCache.validationMessage);
9266 const input = this.getInput();
9267 if (input) {
9268 input.setAttribute('aria-invalid', 'true');
9269 input.setAttribute('aria-describedby', swalClasses['validation-message']);
9270 focusInput(input);
9271 addClass(input, swalClasses.inputerror);
9272 }
9273 }
9274
9275 /**
9276 * Hide block with validation message
9277 *
9278 * @this {SweetAlert}
9279 */
9280 function resetValidationMessage() {
9281 const domCache = privateProps.domCache.get(this);
9282 if (domCache.validationMessage) {
9283 hide(domCache.validationMessage);
9284 }
9285 const input = this.getInput();
9286 if (input) {
9287 input.removeAttribute('aria-invalid');
9288 input.removeAttribute('aria-describedby');
9289 removeClass(input, swalClasses.inputerror);
9290 }
9291 }
9292
9293 const defaultParams = {
9294 title: '',
9295 titleText: '',
9296 text: '',
9297 html: '',
9298 footer: '',
9299 icon: undefined,
9300 iconColor: undefined,
9301 iconHtml: undefined,
9302 template: undefined,
9303 toast: false,
9304 draggable: false,
9305 animation: true,
9306 theme: 'light',
9307 showClass: {
9308 popup: 'swal2-show',
9309 backdrop: 'swal2-backdrop-show',
9310 icon: 'swal2-icon-show'
9311 },
9312 hideClass: {
9313 popup: 'swal2-hide',
9314 backdrop: 'swal2-backdrop-hide',
9315 icon: 'swal2-icon-hide'
9316 },
9317 customClass: {},
9318 target: 'body',
9319 color: undefined,
9320 backdrop: true,
9321 heightAuto: true,
9322 allowOutsideClick: true,
9323 allowEscapeKey: true,
9324 allowEnterKey: true,
9325 stopKeydownPropagation: true,
9326 keydownListenerCapture: false,
9327 showConfirmButton: true,
9328 showDenyButton: false,
9329 showCancelButton: false,
9330 preConfirm: undefined,
9331 preDeny: undefined,
9332 confirmButtonText: 'OK',
9333 confirmButtonAriaLabel: '',
9334 confirmButtonColor: undefined,
9335 denyButtonText: 'No',
9336 denyButtonAriaLabel: '',
9337 denyButtonColor: undefined,
9338 cancelButtonText: 'Cancel',
9339 cancelButtonAriaLabel: '',
9340 cancelButtonColor: undefined,
9341 buttonsStyling: true,
9342 reverseButtons: false,
9343 focusConfirm: true,
9344 focusDeny: false,
9345 focusCancel: false,
9346 returnFocus: true,
9347 showCloseButton: false,
9348 closeButtonHtml: '&times;',
9349 closeButtonAriaLabel: 'Close this dialog',
9350 loaderHtml: '',
9351 showLoaderOnConfirm: false,
9352 showLoaderOnDeny: false,
9353 imageUrl: undefined,
9354 imageWidth: undefined,
9355 imageHeight: undefined,
9356 imageAlt: '',
9357 timer: undefined,
9358 timerProgressBar: false,
9359 width: undefined,
9360 padding: undefined,
9361 background: undefined,
9362 input: undefined,
9363 inputPlaceholder: '',
9364 inputLabel: '',
9365 inputValue: '',
9366 inputOptions: {},
9367 inputAutoFocus: true,
9368 inputAutoTrim: true,
9369 inputAttributes: {},
9370 inputValidator: undefined,
9371 returnInputValueOnDeny: false,
9372 validationMessage: undefined,
9373 grow: false,
9374 position: 'center',
9375 progressSteps: [],
9376 currentProgressStep: undefined,
9377 progressStepsDistance: undefined,
9378 willOpen: undefined,
9379 didOpen: undefined,
9380 didRender: undefined,
9381 willClose: undefined,
9382 didClose: undefined,
9383 didDestroy: undefined,
9384 scrollbarPadding: true,
9385 topLayer: false
9386 };
9387 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'];
9388
9389 /** @type {Record<string, string | undefined>} */
9390 const deprecatedParams = {
9391 allowEnterKey: undefined
9392 };
9393 const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'draggable', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
9394
9395 /**
9396 * Is valid parameter
9397 *
9398 * @param {string} paramName
9399 * @returns {boolean}
9400 */
9401 const isValidParameter = paramName => {
9402 return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
9403 };
9404
9405 /**
9406 * Is valid parameter for Swal.update() method
9407 *
9408 * @param {string} paramName
9409 * @returns {boolean}
9410 */
9411 const isUpdatableParameter = paramName => {
9412 return updatableParams.indexOf(paramName) !== -1;
9413 };
9414
9415 /**
9416 * Is deprecated parameter
9417 *
9418 * @param {string} paramName
9419 * @returns {string | undefined}
9420 */
9421 const isDeprecatedParameter = paramName => {
9422 return deprecatedParams[paramName];
9423 };
9424
9425 /**
9426 * @param {string} param
9427 */
9428 const checkIfParamIsValid = param => {
9429 if (!isValidParameter(param)) {
9430 warn(`Unknown parameter "${param}"`);
9431 }
9432 };
9433
9434 /**
9435 * @param {string} param
9436 */
9437 const checkIfToastParamIsValid = param => {
9438 if (toastIncompatibleParams.includes(param)) {
9439 warn(`The parameter "${param}" is incompatible with toasts`);
9440 }
9441 };
9442
9443 /**
9444 * @param {string} param
9445 */
9446 const checkIfParamIsDeprecated = param => {
9447 const isDeprecated = isDeprecatedParameter(param);
9448 if (isDeprecated) {
9449 warnAboutDeprecation(param, isDeprecated);
9450 }
9451 };
9452
9453 /**
9454 * Show relevant warnings for given params
9455 *
9456 * @param {SweetAlertOptions} params
9457 */
9458 const showWarningsForParams = params => {
9459 if (params.backdrop === false && params.allowOutsideClick) {
9460 warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
9461 }
9462 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)) {
9463 warn(`Invalid theme "${params.theme}"`);
9464 }
9465 for (const param in params) {
9466 checkIfParamIsValid(param);
9467 if (params.toast) {
9468 checkIfToastParamIsValid(param);
9469 }
9470 checkIfParamIsDeprecated(param);
9471 }
9472 };
9473
9474 /**
9475 * Updates popup parameters.
9476 *
9477 * @this {any}
9478 * @param {SweetAlertOptions} params
9479 */
9480 function update(params) {
9481 const container = getContainer();
9482 const popup = getPopup();
9483 const innerParams = privateProps.innerParams.get(this);
9484 if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
9485 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.`);
9486 return;
9487 }
9488 const validUpdatableParams = filterValidParams(params);
9489 const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
9490 showWarningsForParams(updatedParams);
9491 if (container) {
9492 container.dataset['swal2Theme'] = updatedParams.theme;
9493 }
9494 render(this, updatedParams);
9495 privateProps.innerParams.set(this, updatedParams);
9496 Object.defineProperties(this, {
9497 params: {
9498 value: Object.assign({}, this.params, params),
9499 writable: false,
9500 enumerable: true
9501 }
9502 });
9503 }
9504
9505 /**
9506 * @param {SweetAlertOptions} params
9507 * @returns {SweetAlertOptions}
9508 */
9509 const filterValidParams = params => {
9510 /** @type {Record<string, any>} */
9511 const validUpdatableParams = {};
9512 Object.keys(params).forEach(param => {
9513 if (isUpdatableParameter(param)) {
9514 const typedParams = /** @type {Record<string, any>} */params;
9515 validUpdatableParams[param] = typedParams[param];
9516 } else {
9517 warn(`Invalid parameter to update: ${param}`);
9518 }
9519 });
9520 return validUpdatableParams;
9521 };
9522
9523 /**
9524 * Dispose the current SweetAlert2 instance
9525 * @this {SweetAlert}
9526 */
9527 function _destroy() {
9528 var _globalState$eventEmi;
9529 const domCache = privateProps.domCache.get(this);
9530 const innerParams = privateProps.innerParams.get(this);
9531 if (!innerParams) {
9532 disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
9533 return; // This instance has already been destroyed
9534 }
9535
9536 // Check if there is another Swal closing
9537 if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
9538 globalState.swalCloseEventFinishedCallback();
9539 delete globalState.swalCloseEventFinishedCallback;
9540 }
9541 if (typeof innerParams.didDestroy === 'function') {
9542 innerParams.didDestroy();
9543 }
9544 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('didDestroy');
9545 disposeSwal(this);
9546 }
9547
9548 /**
9549 * @param {SweetAlert} instance
9550 */
9551 const disposeSwal = instance => {
9552 disposeWeakMaps(instance);
9553 // Unset this.params so GC will dispose it (#1569)
9554 // @ts-ignore
9555 delete instance.params;
9556 // Unset globalState props so GC will dispose globalState (#1569)
9557 delete globalState.keydownHandler;
9558 delete globalState.keydownTarget;
9559 // Unset currentInstance
9560 delete globalState.currentInstance;
9561 };
9562
9563 /**
9564 * @param {SweetAlert} instance
9565 */
9566 const disposeWeakMaps = instance => {
9567 // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
9568 if (instance.isAwaitingPromise) {
9569 unsetWeakMaps(privateProps, instance);
9570 instance.isAwaitingPromise = true;
9571 } else {
9572 unsetWeakMaps(privateMethods, instance);
9573 unsetWeakMaps(privateProps, instance);
9574
9575 // @ts-ignore
9576 delete instance.isAwaitingPromise;
9577 // Unset instance methods
9578 // @ts-ignore
9579 delete instance.disableButtons;
9580 // @ts-ignore
9581 delete instance.enableButtons;
9582 // @ts-ignore
9583 delete instance.getInput;
9584 // @ts-ignore
9585 delete instance.disableInput;
9586 // @ts-ignore
9587 delete instance.enableInput;
9588 // @ts-ignore
9589 delete instance.hideLoading;
9590 // @ts-ignore
9591 delete instance.disableLoading;
9592 // @ts-ignore
9593 delete instance.showValidationMessage;
9594 // @ts-ignore
9595 delete instance.resetValidationMessage;
9596 // @ts-ignore
9597 delete instance.close;
9598 // @ts-ignore
9599 delete instance.closePopup;
9600 // @ts-ignore
9601 delete instance.closeModal;
9602 // @ts-ignore
9603 delete instance.closeToast;
9604 // @ts-ignore
9605 delete instance.rejectPromise;
9606 // @ts-ignore
9607 delete instance.update;
9608 // @ts-ignore
9609 delete instance._destroy;
9610 }
9611 };
9612
9613 /**
9614 * @param {Record<string, WeakMap<any, any>>} obj
9615 * @param {SweetAlert} instance
9616 */
9617 const unsetWeakMaps = (obj, instance) => {
9618 for (const i in obj) {
9619 obj[i].delete(instance);
9620 }
9621 };
9622
9623 var instanceMethods = /*#__PURE__*/Object.freeze({
9624 __proto__: null,
9625 _destroy: _destroy,
9626 close: close,
9627 closeModal: close,
9628 closePopup: close,
9629 closeToast: close,
9630 disableButtons: disableButtons,
9631 disableInput: disableInput,
9632 disableLoading: hideLoading,
9633 enableButtons: enableButtons,
9634 enableInput: enableInput,
9635 getInput: getInput,
9636 handleAwaitingPromise: handleAwaitingPromise,
9637 hideLoading: hideLoading,
9638 rejectPromise: rejectPromise,
9639 resetValidationMessage: resetValidationMessage,
9640 showValidationMessage: showValidationMessage,
9641 update: update
9642 });
9643
9644 /**
9645 * @param {SweetAlertOptions} innerParams
9646 * @param {DomCache} domCache
9647 * @param {(dismiss: DismissReason) => void} dismissWith
9648 */
9649 const handlePopupClick = (innerParams, domCache, dismissWith) => {
9650 if (innerParams.toast) {
9651 handleToastClick(innerParams, domCache, dismissWith);
9652 } else {
9653 // Ignore click events that had mousedown on the popup but mouseup on the container
9654 // This can happen when the user drags a slider
9655 handleModalMousedown(domCache);
9656
9657 // Ignore click events that had mousedown on the container but mouseup on the popup
9658 handleContainerMousedown(domCache);
9659 handleModalClick(innerParams, domCache, dismissWith);
9660 }
9661 };
9662
9663 /**
9664 * @param {SweetAlertOptions} innerParams
9665 * @param {DomCache} domCache
9666 * @param {(dismiss: DismissReason) => void} dismissWith
9667 */
9668 const handleToastClick = (innerParams, domCache, dismissWith) => {
9669 // Closing toast by internal click
9670 domCache.popup.onclick = () => {
9671 if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
9672 return;
9673 }
9674 dismissWith(DismissReason.close);
9675 };
9676 };
9677
9678 /**
9679 * @param {SweetAlertOptions} innerParams
9680 * @returns {boolean}
9681 */
9682 const isAnyButtonShown = innerParams => {
9683 return Boolean(innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton);
9684 };
9685 let ignoreOutsideClick = false;
9686
9687 /**
9688 * @param {DomCache} domCache
9689 */
9690 const handleModalMousedown = domCache => {
9691 domCache.popup.onmousedown = () => {
9692 domCache.container.onmouseup = function (e) {
9693 domCache.container.onmouseup = () => {};
9694 // We only check if the mouseup target is the container because usually it doesn't
9695 // have any other direct children aside of the popup
9696 if (e.target === domCache.container) {
9697 ignoreOutsideClick = true;
9698 }
9699 };
9700 };
9701 };
9702
9703 /**
9704 * @param {DomCache} domCache
9705 */
9706 const handleContainerMousedown = domCache => {
9707 domCache.container.onmousedown = e => {
9708 // prevent the modal text from being selected on double click on the container (allowOutsideClick: false)
9709 if (e.target === domCache.container) {
9710 e.preventDefault();
9711 }
9712 domCache.popup.onmouseup = function (e) {
9713 domCache.popup.onmouseup = () => {};
9714 // We also need to check if the mouseup target is a child of the popup
9715 if (e.target === domCache.popup || e.target instanceof HTMLElement && domCache.popup.contains(e.target)) {
9716 ignoreOutsideClick = true;
9717 }
9718 };
9719 };
9720 };
9721
9722 /**
9723 * @param {SweetAlertOptions} innerParams
9724 * @param {DomCache} domCache
9725 * @param {(dismiss: DismissReason) => void} dismissWith
9726 */
9727 const handleModalClick = (innerParams, domCache, dismissWith) => {
9728 domCache.container.onclick = e => {
9729 if (ignoreOutsideClick) {
9730 ignoreOutsideClick = false;
9731 return;
9732 }
9733 if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
9734 dismissWith(DismissReason.backdrop);
9735 }
9736 };
9737 };
9738
9739 /**
9740 * @param {unknown} elem
9741 * @returns {boolean}
9742 */
9743 const isJqueryElement = elem => typeof elem === 'object' && elem !== null && 'jquery' in elem;
9744
9745 /**
9746 * @param {unknown} elem
9747 * @returns {boolean}
9748 */
9749 const isElement = elem => elem instanceof Element || isJqueryElement(elem);
9750
9751 /**
9752 * @param {ReadonlyArray<unknown>} args
9753 * @returns {SweetAlertOptions}
9754 */
9755 const argsToParams = args => {
9756 /** @type {Record<string, unknown>} */
9757 const params = {};
9758 if (typeof args[0] === 'object' && !isElement(args[0])) {
9759 Object.assign(params, args[0]);
9760 } else {
9761 ['title', 'html', 'icon'].forEach((name, index) => {
9762 const arg = args[index];
9763 if (typeof arg === 'string' || isElement(arg)) {
9764 params[name] = arg;
9765 } else if (arg !== undefined) {
9766 error(`Unexpected type of ${name}! Expected "string" or "Element", got ${typeof arg}`);
9767 }
9768 });
9769 }
9770 return /** @type {SweetAlertOptions} */params;
9771 };
9772
9773 /**
9774 * Main method to create a new SweetAlert2 popup
9775 *
9776 * @this {new (...args: any[]) => any}
9777 * @param {...SweetAlertOptions} args
9778 * @returns {Promise<SweetAlertResult>}
9779 */
9780 function fire(...args) {
9781 return new this(...args);
9782 }
9783
9784 /**
9785 * Returns an extended version of `Swal` containing `params` as defaults.
9786 * Useful for reusing Swal configuration.
9787 *
9788 * For example:
9789 *
9790 * Before:
9791 * const textPromptOptions = { input: 'text', showCancelButton: true }
9792 * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
9793 * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
9794 *
9795 * After:
9796 * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
9797 * const {value: firstName} = await TextPrompt('What is your first name?')
9798 * const {value: lastName} = await TextPrompt('What is your last name?')
9799 *
9800 * @param {SweetAlertOptions} mixinParams
9801 * @returns {SweetAlert}
9802 * @this {typeof import('../SweetAlert.js').SweetAlert}
9803 */
9804 function mixin(mixinParams) {
9805 // @ts-ignore: 'this' refers to the SweetAlert constructor
9806 class MixinSwal extends this {
9807 /**
9808 * @param {any} params
9809 * @param {any} priorityMixinParams
9810 */
9811 _main(params, priorityMixinParams) {
9812 return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
9813 }
9814 }
9815 // @ts-ignore
9816 return MixinSwal;
9817 }
9818
9819 /**
9820 * If `timer` parameter is set, returns number of milliseconds of timer remained.
9821 * Otherwise, returns undefined.
9822 *
9823 * @returns {number | undefined}
9824 */
9825 const getTimerLeft = () => {
9826 return globalState.timeout && globalState.timeout.getTimerLeft();
9827 };
9828
9829 /**
9830 * Stop timer. Returns number of milliseconds of timer remained.
9831 * If `timer` parameter isn't set, returns undefined.
9832 *
9833 * @returns {number | undefined}
9834 */
9835 const stopTimer = () => {
9836 if (globalState.timeout) {
9837 stopTimerProgressBar();
9838 return globalState.timeout.stop();
9839 }
9840 };
9841
9842 /**
9843 * Resume timer. Returns number of milliseconds of timer remained.
9844 * If `timer` parameter isn't set, returns undefined.
9845 *
9846 * @returns {number | undefined}
9847 */
9848 const resumeTimer = () => {
9849 if (globalState.timeout) {
9850 const remaining = globalState.timeout.start();
9851 animateTimerProgressBar(remaining);
9852 return remaining;
9853 }
9854 };
9855
9856 /**
9857 * Resume timer. Returns number of milliseconds of timer remained.
9858 * If `timer` parameter isn't set, returns undefined.
9859 *
9860 * @returns {number | undefined}
9861 */
9862 const toggleTimer = () => {
9863 const timer = globalState.timeout;
9864 return timer && (timer.running ? stopTimer() : resumeTimer());
9865 };
9866
9867 /**
9868 * Increase timer. Returns number of milliseconds of an updated timer.
9869 * If `timer` parameter isn't set, returns undefined.
9870 *
9871 * @param {number} ms
9872 * @returns {number | undefined}
9873 */
9874 const increaseTimer = ms => {
9875 if (globalState.timeout) {
9876 const remaining = globalState.timeout.increase(ms);
9877 animateTimerProgressBar(remaining, true);
9878 return remaining;
9879 }
9880 };
9881
9882 /**
9883 * Check if timer is running. Returns true if timer is running
9884 * or false if timer is paused or stopped.
9885 * If `timer` parameter isn't set, returns undefined
9886 *
9887 * @returns {boolean}
9888 */
9889 const isTimerRunning = () => {
9890 return Boolean(globalState.timeout && globalState.timeout.isRunning());
9891 };
9892
9893 let bodyClickListenerAdded = false;
9894 /** @type {Record<string, any>} */
9895 const clickHandlers = {};
9896
9897 /**
9898 * @this {any}
9899 * @param {string} attr
9900 */
9901 function bindClickHandler(attr = 'data-swal-template') {
9902 clickHandlers[attr] = this;
9903 if (!bodyClickListenerAdded) {
9904 document.body.addEventListener('click', bodyClickListener);
9905 bodyClickListenerAdded = true;
9906 }
9907 }
9908
9909 /**
9910 * @param {MouseEvent} event
9911 */
9912 const bodyClickListener = event => {
9913 for (let el = /** @type {any} */event.target; el && el !== document; el = el.parentNode) {
9914 for (const attr in clickHandlers) {
9915 const template = el.getAttribute && el.getAttribute(attr);
9916 if (template) {
9917 clickHandlers[attr].fire({
9918 template
9919 });
9920 return;
9921 }
9922 }
9923 }
9924 };
9925
9926 // Source: https://gist.github.com/mudge/5830382?permalink_comment_id=2691957#gistcomment-2691957
9927
9928 class EventEmitter {
9929 constructor() {
9930 /** @type {Events} */
9931 this.events = {};
9932 }
9933
9934 /**
9935 * @param {string} eventName
9936 * @returns {EventHandlers}
9937 */
9938 _getHandlersByEventName(eventName) {
9939 if (typeof this.events[eventName] === 'undefined') {
9940 // not Set because we need to keep the FIFO order
9941 // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1748990334
9942 this.events[eventName] = [];
9943 }
9944 return this.events[eventName];
9945 }
9946
9947 /**
9948 * @param {string} eventName
9949 * @param {EventHandler} eventHandler
9950 */
9951 on(eventName, eventHandler) {
9952 const currentHandlers = this._getHandlersByEventName(eventName);
9953 if (!currentHandlers.includes(eventHandler)) {
9954 currentHandlers.push(eventHandler);
9955 }
9956 }
9957
9958 /**
9959 * @param {string} eventName
9960 * @param {EventHandler} eventHandler
9961 */
9962 once(eventName, eventHandler) {
9963 /**
9964 * @param {...any} args
9965 */
9966 const onceFn = (...args) => {
9967 this.removeListener(eventName, onceFn);
9968 // @ts-ignore
9969 eventHandler.apply(this, args);
9970 };
9971 this.on(eventName, onceFn);
9972 }
9973
9974 /**
9975 * @param {string} eventName
9976 * @param {...any} args
9977 */
9978 emit(eventName, ...args) {
9979 this._getHandlersByEventName(eventName).forEach(
9980 /**
9981 * @param {EventHandler} eventHandler
9982 */
9983 eventHandler => {
9984 try {
9985 // @ts-ignore
9986 eventHandler.apply(this, args);
9987 } catch (error) {
9988 console.error(error);
9989 }
9990 });
9991 }
9992
9993 /**
9994 * @param {string} eventName
9995 * @param {EventHandler} eventHandler
9996 */
9997 removeListener(eventName, eventHandler) {
9998 const currentHandlers = this._getHandlersByEventName(eventName);
9999 const index = currentHandlers.indexOf(eventHandler);
10000 if (index > -1) {
10001 currentHandlers.splice(index, 1);
10002 }
10003 }
10004
10005 /**
10006 * @param {string} eventName
10007 */
10008 removeAllListeners(eventName) {
10009 if (this.events[eventName] !== undefined) {
10010 // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1749239222
10011 this.events[eventName].length = 0;
10012 }
10013 }
10014 reset() {
10015 this.events = {};
10016 }
10017 }
10018
10019 globalState.eventEmitter = new EventEmitter();
10020
10021 /**
10022 * @param {string} eventName
10023 * @param {EventHandler} eventHandler
10024 */
10025 const on = (eventName, eventHandler) => {
10026 if (globalState.eventEmitter) {
10027 globalState.eventEmitter.on(eventName, eventHandler);
10028 }
10029 };
10030
10031 /**
10032 * @param {string} eventName
10033 * @param {EventHandler} eventHandler
10034 */
10035 const once = (eventName, eventHandler) => {
10036 if (globalState.eventEmitter) {
10037 globalState.eventEmitter.once(eventName, eventHandler);
10038 }
10039 };
10040
10041 /**
10042 * @param {string} [eventName]
10043 * @param {EventHandler} [eventHandler]
10044 */
10045 const off = (eventName, eventHandler) => {
10046 if (!globalState.eventEmitter) {
10047 return;
10048 }
10049
10050 // Remove all handlers for all events
10051 if (!eventName) {
10052 globalState.eventEmitter.reset();
10053 return;
10054 }
10055 if (eventHandler) {
10056 // Remove a specific handler
10057 globalState.eventEmitter.removeListener(eventName, eventHandler);
10058 } else {
10059 // Remove all handlers for a specific event
10060 globalState.eventEmitter.removeAllListeners(eventName);
10061 }
10062 };
10063
10064 var staticMethods = /*#__PURE__*/Object.freeze({
10065 __proto__: null,
10066 argsToParams: argsToParams,
10067 bindClickHandler: bindClickHandler,
10068 clickCancel: clickCancel,
10069 clickConfirm: clickConfirm,
10070 clickDeny: clickDeny,
10071 enableLoading: showLoading,
10072 fire: fire,
10073 getActions: getActions,
10074 getCancelButton: getCancelButton,
10075 getCloseButton: getCloseButton,
10076 getConfirmButton: getConfirmButton,
10077 getContainer: getContainer,
10078 getDenyButton: getDenyButton,
10079 getFocusableElements: getFocusableElements,
10080 getFooter: getFooter,
10081 getHtmlContainer: getHtmlContainer,
10082 getIcon: getIcon,
10083 getIconContent: getIconContent,
10084 getImage: getImage,
10085 getInputLabel: getInputLabel,
10086 getLoader: getLoader,
10087 getPopup: getPopup,
10088 getProgressSteps: getProgressSteps,
10089 getTimerLeft: getTimerLeft,
10090 getTimerProgressBar: getTimerProgressBar,
10091 getTitle: getTitle,
10092 getValidationMessage: getValidationMessage,
10093 increaseTimer: increaseTimer,
10094 isDeprecatedParameter: isDeprecatedParameter,
10095 isLoading: isLoading,
10096 isTimerRunning: isTimerRunning,
10097 isUpdatableParameter: isUpdatableParameter,
10098 isValidParameter: isValidParameter,
10099 isVisible: isVisible,
10100 mixin: mixin,
10101 off: off,
10102 on: on,
10103 once: once,
10104 resumeTimer: resumeTimer,
10105 showLoading: showLoading,
10106 stopTimer: stopTimer,
10107 toggleTimer: toggleTimer
10108 });
10109
10110 class Timer {
10111 /**
10112 * @param {() => void} callback
10113 * @param {number} delay
10114 */
10115 constructor(callback, delay) {
10116 this.callback = callback;
10117 this.remaining = delay;
10118 this.running = false;
10119 this.start();
10120 }
10121
10122 /**
10123 * @returns {number}
10124 */
10125 start() {
10126 if (!this.running) {
10127 this.running = true;
10128 this.started = new Date();
10129 this.id = setTimeout(this.callback, this.remaining);
10130 }
10131 return this.remaining;
10132 }
10133
10134 /**
10135 * @returns {number}
10136 */
10137 stop() {
10138 if (this.started && this.running) {
10139 this.running = false;
10140 clearTimeout(this.id);
10141 this.remaining -= new Date().getTime() - this.started.getTime();
10142 }
10143 return this.remaining;
10144 }
10145
10146 /**
10147 * @param {number} n
10148 * @returns {number}
10149 */
10150 increase(n) {
10151 const running = this.running;
10152 if (running) {
10153 this.stop();
10154 }
10155 this.remaining += n;
10156 if (running) {
10157 this.start();
10158 }
10159 return this.remaining;
10160 }
10161
10162 /**
10163 * @returns {number}
10164 */
10165 getTimerLeft() {
10166 if (this.running) {
10167 this.stop();
10168 this.start();
10169 }
10170 return this.remaining;
10171 }
10172
10173 /**
10174 * @returns {boolean}
10175 */
10176 isRunning() {
10177 return this.running;
10178 }
10179 }
10180
10181 const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
10182
10183 /**
10184 * @param {SweetAlertOptions} params
10185 * @returns {SweetAlertOptions}
10186 */
10187 const getTemplateParams = params => {
10188 const template = typeof params.template === 'string' ? (/** @type {HTMLTemplateElement} */document.querySelector(params.template)) : params.template;
10189 if (!template) {
10190 return {};
10191 }
10192 /** @type {DocumentFragment} */
10193 const templateContent = template.content;
10194 showWarningsForElements(templateContent);
10195 const result = Object.assign(getSwalParams(templateContent), getSwalFunctionParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
10196 return result;
10197 };
10198
10199 /**
10200 * @param {DocumentFragment} templateContent
10201 * @returns {Record<string, string | boolean | number>}
10202 */
10203 const getSwalParams = templateContent => {
10204 /** @type {Record<string, string | boolean | number>} */
10205 const result = {};
10206 /** @type {HTMLElement[]} */
10207 const swalParams = Array.from(templateContent.querySelectorAll('swal-param'));
10208 swalParams.forEach(param => {
10209 showWarningsForAttributes(param, ['name', 'value']);
10210 const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
10211 const value = param.getAttribute('value');
10212 if (!paramName || !value) {
10213 return;
10214 }
10215 if (paramName in defaultParams && typeof defaultParams[(/** @type {keyof typeof defaultParams} */paramName)] === 'boolean') {
10216 result[paramName] = value !== 'false';
10217 } else if (paramName in defaultParams && typeof defaultParams[(/** @type {keyof typeof defaultParams} */paramName)] === 'object') {
10218 result[paramName] = JSON.parse(value);
10219 } else {
10220 result[paramName] = value;
10221 }
10222 });
10223 return result;
10224 };
10225
10226 /**
10227 * @param {DocumentFragment} templateContent
10228 * @returns {Record<string, () => void>}
10229 */
10230 const getSwalFunctionParams = templateContent => {
10231 /** @type {Record<string, () => void>} */
10232 const result = {};
10233 /** @type {HTMLElement[]} */
10234 const swalFunctions = Array.from(templateContent.querySelectorAll('swal-function-param'));
10235 swalFunctions.forEach(param => {
10236 const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
10237 const value = param.getAttribute('value');
10238 if (!paramName || !value) {
10239 return;
10240 }
10241 result[paramName] = new Function(`return ${value}`)();
10242 });
10243 return result;
10244 };
10245
10246 /**
10247 * @param {DocumentFragment} templateContent
10248 * @returns {Record<string, string | boolean>}
10249 */
10250 const getSwalButtons = templateContent => {
10251 /** @type {Record<string, string | boolean>} */
10252 const result = {};
10253 /** @type {HTMLElement[]} */
10254 const swalButtons = Array.from(templateContent.querySelectorAll('swal-button'));
10255 swalButtons.forEach(button => {
10256 showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
10257 const type = button.getAttribute('type');
10258 if (!type || !['confirm', 'cancel', 'deny'].includes(type)) {
10259 return;
10260 }
10261 result[`${type}ButtonText`] = button.innerHTML;
10262 result[`show${capitalizeFirstLetter(type)}Button`] = true;
10263 const color = button.getAttribute('color');
10264 if (color !== null) {
10265 result[`${type}ButtonColor`] = color;
10266 }
10267 const ariaLabel = button.getAttribute('aria-label');
10268 if (ariaLabel !== null) {
10269 result[`${type}ButtonAriaLabel`] = ariaLabel;
10270 }
10271 });
10272 return result;
10273 };
10274
10275 /**
10276 * @param {DocumentFragment} templateContent
10277 * @returns {Pick<SweetAlertOptions, 'imageUrl' | 'imageWidth' | 'imageHeight' | 'imageAlt'>}
10278 */
10279 const getSwalImage = templateContent => {
10280 const result = {};
10281 /** @type {HTMLElement | null} */
10282 const image = templateContent.querySelector('swal-image');
10283 if (image) {
10284 showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
10285 // getAttribute returns null if attribute is absent; `|| undefined` converts empty string to undefined
10286 const src = image.getAttribute('src');
10287 if (src !== null) result.imageUrl = src || undefined;
10288 const width = image.getAttribute('width');
10289 if (width !== null) result.imageWidth = width || undefined;
10290 const height = image.getAttribute('height');
10291 if (height !== null) result.imageHeight = height || undefined;
10292 const alt = image.getAttribute('alt');
10293 if (alt !== null) result.imageAlt = alt || undefined;
10294 }
10295 return result;
10296 };
10297
10298 /**
10299 * @param {DocumentFragment} templateContent
10300 * @returns {object}
10301 */
10302 const getSwalIcon = templateContent => {
10303 const result = {};
10304 /** @type {HTMLElement | null} */
10305 const icon = templateContent.querySelector('swal-icon');
10306 if (icon) {
10307 showWarningsForAttributes(icon, ['type', 'color']);
10308 if (icon.hasAttribute('type')) {
10309 result.icon = icon.getAttribute('type');
10310 }
10311 if (icon.hasAttribute('color')) {
10312 result.iconColor = icon.getAttribute('color');
10313 }
10314 result.iconHtml = icon.innerHTML;
10315 }
10316 return result;
10317 };
10318
10319 /**
10320 * @param {DocumentFragment} templateContent
10321 * @returns {object}
10322 */
10323 const getSwalInput = templateContent => {
10324 /** @type {Record<string, any>} */
10325 const result = {};
10326 /** @type {HTMLElement | null} */
10327 const input = templateContent.querySelector('swal-input');
10328 if (input) {
10329 showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
10330 result.input = input.getAttribute('type') || 'text';
10331 if (input.hasAttribute('label')) {
10332 result.inputLabel = input.getAttribute('label');
10333 }
10334 if (input.hasAttribute('placeholder')) {
10335 result.inputPlaceholder = input.getAttribute('placeholder');
10336 }
10337 if (input.hasAttribute('value')) {
10338 result.inputValue = input.getAttribute('value');
10339 }
10340 }
10341 /** @type {HTMLElement[]} */
10342 const inputOptions = Array.from(templateContent.querySelectorAll('swal-input-option'));
10343 if (inputOptions.length) {
10344 result.inputOptions = {};
10345 inputOptions.forEach(option => {
10346 showWarningsForAttributes(option, ['value']);
10347 const optionValue = option.getAttribute('value');
10348 if (!optionValue) {
10349 return;
10350 }
10351 const optionName = option.innerHTML;
10352 result.inputOptions[optionValue] = optionName;
10353 });
10354 }
10355 return result;
10356 };
10357
10358 /**
10359 * @param {DocumentFragment} templateContent
10360 * @param {string[]} paramNames
10361 * @returns {Record<string, string>}
10362 */
10363 const getSwalStringParams = (templateContent, paramNames) => {
10364 /** @type {Record<string, string>} */
10365 const result = {};
10366 for (const i in paramNames) {
10367 const paramName = paramNames[i];
10368 /** @type {HTMLElement | null} */
10369 const tag = templateContent.querySelector(paramName);
10370 if (tag) {
10371 showWarningsForAttributes(tag, []);
10372 result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
10373 }
10374 }
10375 return result;
10376 };
10377
10378 /**
10379 * @param {DocumentFragment} templateContent
10380 */
10381 const showWarningsForElements = templateContent => {
10382 const allowedElements = swalStringParams.concat(['swal-param', 'swal-function-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
10383 Array.from(templateContent.children).forEach(el => {
10384 const tagName = el.tagName.toLowerCase();
10385 if (!allowedElements.includes(tagName)) {
10386 warn(`Unrecognized element <${tagName}>`);
10387 }
10388 });
10389 };
10390
10391 /**
10392 * @param {HTMLElement} el
10393 * @param {string[]} allowedAttributes
10394 */
10395 const showWarningsForAttributes = (el, allowedAttributes) => {
10396 Array.from(el.attributes).forEach(attribute => {
10397 if (allowedAttributes.indexOf(attribute.name) === -1) {
10398 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.'}`]);
10399 }
10400 });
10401 };
10402
10403 const SHOW_CLASS_TIMEOUT = 10;
10404
10405 /**
10406 * Open popup, add necessary classes and styles, fix scrollbar
10407 *
10408 * @param {SweetAlertOptions} params
10409 */
10410 const openPopup = params => {
10411 var _globalState$eventEmi, _globalState$eventEmi2;
10412 const container = getContainer();
10413 const popup = getPopup();
10414 if (!container || !popup) {
10415 return;
10416 }
10417 if (typeof params.willOpen === 'function') {
10418 params.willOpen(popup);
10419 }
10420 (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('willOpen', popup);
10421 const bodyStyles = window.getComputedStyle(document.body);
10422 const initialBodyOverflow = bodyStyles.overflowY;
10423 addClasses(container, popup, params);
10424
10425 // scrolling is 'hidden' until animation is done, after that 'auto'
10426 setTimeout(() => {
10427 setScrollingVisibility(container, popup);
10428 }, SHOW_CLASS_TIMEOUT);
10429 if (isModal()) {
10430 fixScrollContainer(container, params.scrollbarPadding !== undefined ? params.scrollbarPadding : false, initialBodyOverflow);
10431 setAriaHidden();
10432 }
10433
10434 // https://github.com/sweetalert2/sweetalert2/issues/2923
10435 if (isIOS && params.backdrop === false && popup.scrollHeight > container.clientHeight) {
10436 // remove pointer-events: none from container, it breaks scrolling tall popups in iOS
10437 container.style.pointerEvents = 'auto';
10438 }
10439 if (!isToast() && !globalState.previousActiveElement) {
10440 globalState.previousActiveElement = document.activeElement;
10441 }
10442 if (typeof params.didOpen === 'function') {
10443 const didOpen = params.didOpen;
10444 setTimeout(() => didOpen(popup));
10445 }
10446 (_globalState$eventEmi2 = globalState.eventEmitter) === null || _globalState$eventEmi2 === void 0 || _globalState$eventEmi2.emit('didOpen', popup);
10447 };
10448
10449 /**
10450 * @param {Event} event
10451 */
10452 const swalOpenAnimationFinished = event => {
10453 const popup = getPopup();
10454 if (!popup || event.target !== popup) {
10455 return;
10456 }
10457 const container = getContainer();
10458 if (!container) {
10459 return;
10460 }
10461 popup.removeEventListener('animationend', swalOpenAnimationFinished);
10462 popup.removeEventListener('transitionend', swalOpenAnimationFinished);
10463 container.style.overflowY = 'auto';
10464
10465 // no-transition is added in init() in case one swal is opened right after another
10466 removeClass(container, swalClasses['no-transition']);
10467 };
10468
10469 /**
10470 * @param {HTMLElement} container
10471 * @param {HTMLElement} popup
10472 */
10473 const setScrollingVisibility = (container, popup) => {
10474 if (hasCssAnimation(popup)) {
10475 container.style.overflowY = 'hidden';
10476 popup.addEventListener('animationend', swalOpenAnimationFinished);
10477 popup.addEventListener('transitionend', swalOpenAnimationFinished);
10478 } else {
10479 container.style.overflowY = 'auto';
10480 }
10481 };
10482
10483 /**
10484 * @param {HTMLElement} container
10485 * @param {boolean} scrollbarPadding
10486 * @param {string} initialBodyOverflow
10487 */
10488 const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
10489 iOSfix();
10490 if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
10491 replaceScrollbarWithPadding(initialBodyOverflow);
10492 }
10493
10494 // sweetalert2/issues/1247
10495 setTimeout(() => {
10496 container.scrollTop = 0;
10497 });
10498 };
10499
10500 /**
10501 * @param {HTMLElement} container
10502 * @param {HTMLElement} popup
10503 * @param {SweetAlertOptions} params
10504 */
10505 const addClasses = (container, popup, params) => {
10506 var _params$showClass;
10507 if ((_params$showClass = params.showClass) !== null && _params$showClass !== void 0 && _params$showClass.backdrop) {
10508 addClass(container, params.showClass.backdrop);
10509 }
10510 if (params.animation) {
10511 // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
10512 popup.style.setProperty('opacity', '0', 'important');
10513 show(popup, 'grid');
10514 setTimeout(() => {
10515 var _params$showClass2;
10516 // Animate popup right after showing it
10517 if ((_params$showClass2 = params.showClass) !== null && _params$showClass2 !== void 0 && _params$showClass2.popup) {
10518 addClass(popup, params.showClass.popup);
10519 }
10520 // and remove the opacity workaround
10521 popup.style.removeProperty('opacity');
10522 }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
10523 } else {
10524 show(popup, 'grid');
10525 }
10526 addClass([document.documentElement, document.body], swalClasses.shown);
10527 if (params.heightAuto && params.backdrop && !params.toast) {
10528 addClass([document.documentElement, document.body], swalClasses['height-auto']);
10529 }
10530 };
10531
10532 var defaultInputValidators = {
10533 /**
10534 * @param {string} string
10535 * @param {string} [validationMessage]
10536 * @returns {Promise<string | void>}
10537 */
10538 email: (string, validationMessage) => {
10539 return /^[a-zA-Z0-9.+_'-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]+$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
10540 },
10541 /**
10542 * @param {string} string
10543 * @param {string} [validationMessage]
10544 * @returns {Promise<string | void>}
10545 */
10546 url: (string, validationMessage) => {
10547 // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
10548 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');
10549 }
10550 };
10551
10552 /**
10553 * @param {SweetAlertOptions} params
10554 */
10555 function setDefaultInputValidators(params) {
10556 // Use default `inputValidator` for supported input types if not provided
10557 if (params.inputValidator) {
10558 return;
10559 }
10560 if (params.input === 'email') {
10561 params.inputValidator = defaultInputValidators['email'];
10562 }
10563 if (params.input === 'url') {
10564 params.inputValidator = defaultInputValidators['url'];
10565 }
10566 }
10567
10568 /**
10569 * @param {SweetAlertOptions} params
10570 */
10571 function validateCustomTargetElement(params) {
10572 // Determine if the custom target element is valid
10573 if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
10574 warn('Target parameter is not valid, defaulting to "body"');
10575 params.target = 'body';
10576 }
10577 }
10578
10579 /**
10580 * Set type, text and actions on popup
10581 *
10582 * @param {SweetAlertOptions} params
10583 */
10584 function setParameters(params) {
10585 setDefaultInputValidators(params);
10586
10587 // showLoaderOnConfirm && preConfirm
10588 if (params.showLoaderOnConfirm && !params.preConfirm) {
10589 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');
10590 }
10591 validateCustomTargetElement(params);
10592
10593 // Replace newlines with <br> in title
10594 if (typeof params.title === 'string') {
10595 params.title = params.title.split('\n').join('<br />');
10596 }
10597 init(params);
10598 }
10599
10600 /** @type {SweetAlert} */
10601 let currentInstance;
10602 var _promise = /*#__PURE__*/new WeakMap();
10603 class SweetAlert {
10604 /**
10605 * @param {...(SweetAlertOptions | string)} args
10606 * @this {SweetAlert}
10607 */
10608 constructor(...args) {
10609 /**
10610 * @type {Promise<SweetAlertResult>}
10611 */
10612 _classPrivateFieldInitSpec(this, _promise, /** @type {Promise<SweetAlertResult>} */
10613 Promise.resolve({
10614 isConfirmed: false,
10615 isDenied: false,
10616 isDismissed: true
10617 }));
10618 // Prevent run in Node env
10619 if (typeof window === 'undefined') {
10620 return;
10621 }
10622 currentInstance = this;
10623
10624 // @ts-ignore
10625 const outerParams = Object.freeze(this.constructor.argsToParams(args));
10626
10627 /** @type {Readonly<SweetAlertOptions>} */
10628 this.params = outerParams;
10629
10630 /** @type {boolean} */
10631 this.isAwaitingPromise = false;
10632 _classPrivateFieldSet2(_promise, this, this._main(currentInstance.params));
10633 }
10634
10635 /**
10636 * @param {any} userParams
10637 * @param {any} mixinParams
10638 */
10639 _main(userParams, mixinParams = {}) {
10640 showWarningsForParams(Object.assign({}, mixinParams, userParams));
10641 if (globalState.currentInstance) {
10642 const swalPromiseResolve = privateMethods.swalPromiseResolve.get(globalState.currentInstance);
10643 const {
10644 isAwaitingPromise
10645 } = globalState.currentInstance;
10646 globalState.currentInstance._destroy();
10647 if (!isAwaitingPromise) {
10648 swalPromiseResolve({
10649 isDismissed: true
10650 });
10651 }
10652 if (isModal()) {
10653 unsetAriaHidden();
10654 }
10655 }
10656 globalState.currentInstance = currentInstance;
10657 const innerParams = prepareParams(userParams, mixinParams);
10658 setParameters(innerParams);
10659 Object.freeze(innerParams);
10660
10661 // clear the previous timer
10662 if (globalState.timeout) {
10663 globalState.timeout.stop();
10664 delete globalState.timeout;
10665 }
10666
10667 // clear the restore focus timeout
10668 clearTimeout(globalState.restoreFocusTimeout);
10669 const domCache = populateDomCache(currentInstance);
10670 render(currentInstance, innerParams);
10671 privateProps.innerParams.set(currentInstance, innerParams);
10672 return swalPromise(currentInstance, domCache, innerParams);
10673 }
10674
10675 // `catch` cannot be the name of a module export, so we define our thenable methods here instead
10676 /**
10677 * @param {any} onFulfilled
10678 */
10679 // oxlint-disable-next-line unicorn/no-thenable
10680 then(onFulfilled) {
10681 return _classPrivateFieldGet2(_promise, this).then(onFulfilled);
10682 }
10683
10684 /**
10685 * @param {any} onFinally
10686 */
10687 finally(onFinally) {
10688 return _classPrivateFieldGet2(_promise, this).finally(onFinally);
10689 }
10690 }
10691
10692 /**
10693 * @param {SweetAlert} instance
10694 * @param {DomCache} domCache
10695 * @param {SweetAlertOptions} innerParams
10696 * @returns {Promise<SweetAlertResult>}
10697 */
10698 const swalPromise = (instance, domCache, innerParams) => {
10699 return new Promise((resolve, reject) => {
10700 // functions to handle all closings/dismissals
10701 /**
10702 * @param {DismissReason} dismiss
10703 */
10704 const dismissWith = dismiss => {
10705 instance.close({
10706 isDismissed: true,
10707 dismiss,
10708 isConfirmed: false,
10709 isDenied: false
10710 });
10711 };
10712 privateMethods.swalPromiseResolve.set(instance, resolve);
10713 privateMethods.swalPromiseReject.set(instance, reject);
10714 domCache.confirmButton.onclick = () => {
10715 handleConfirmButtonClick(instance);
10716 };
10717 domCache.denyButton.onclick = () => {
10718 handleDenyButtonClick(instance);
10719 };
10720 domCache.cancelButton.onclick = () => {
10721 handleCancelButtonClick(instance, dismissWith);
10722 };
10723 domCache.closeButton.onclick = () => {
10724 dismissWith(DismissReason.close);
10725 };
10726 handlePopupClick(innerParams, domCache, dismissWith);
10727 addKeydownHandler(globalState, innerParams, dismissWith);
10728 handleInputOptionsAndValue(instance, innerParams);
10729 openPopup(innerParams);
10730 setupTimer(globalState, innerParams, dismissWith);
10731 initFocus(domCache, innerParams);
10732
10733 // Scroll container to top on open (#1247, #1946)
10734 setTimeout(() => {
10735 domCache.container.scrollTop = 0;
10736 });
10737 });
10738 };
10739
10740 /**
10741 * @param {SweetAlertOptions} userParams
10742 * @param {SweetAlertOptions} mixinParams
10743 * @returns {SweetAlertOptions}
10744 */
10745 const prepareParams = (userParams, mixinParams) => {
10746 const templateParams = getTemplateParams(userParams);
10747 const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
10748 params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
10749 params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
10750 if (params.animation === false) {
10751 params.showClass = {
10752 backdrop: 'swal2-noanimation'
10753 };
10754 params.hideClass = {};
10755 }
10756 return params;
10757 };
10758
10759 /**
10760 * @param {SweetAlert} instance
10761 * @returns {DomCache}
10762 */
10763 const populateDomCache = instance => {
10764 const domCache = /** @type {DomCache} */{
10765 popup: (/** @type {HTMLElement} */getPopup()),
10766 container: (/** @type {HTMLElement} */getContainer()),
10767 actions: (/** @type {HTMLElement} */getActions()),
10768 confirmButton: (/** @type {HTMLElement} */getConfirmButton()),
10769 denyButton: (/** @type {HTMLElement} */getDenyButton()),
10770 cancelButton: (/** @type {HTMLElement} */getCancelButton()),
10771 loader: (/** @type {HTMLElement} */getLoader()),
10772 closeButton: (/** @type {HTMLElement} */getCloseButton()),
10773 validationMessage: (/** @type {HTMLElement} */getValidationMessage()),
10774 progressSteps: (/** @type {HTMLElement} */getProgressSteps())
10775 };
10776 privateProps.domCache.set(instance, domCache);
10777 return domCache;
10778 };
10779
10780 /**
10781 * @param {GlobalState} globalState
10782 * @param {SweetAlertOptions} innerParams
10783 * @param {(dismiss: DismissReason) => void} dismissWith
10784 */
10785 const setupTimer = (globalState, innerParams, dismissWith) => {
10786 const timerProgressBar = getTimerProgressBar();
10787 hide(timerProgressBar);
10788 if (innerParams.timer) {
10789 globalState.timeout = new Timer(() => {
10790 dismissWith('timer');
10791 delete globalState.timeout;
10792 }, innerParams.timer);
10793 if (innerParams.timerProgressBar && timerProgressBar) {
10794 show(timerProgressBar);
10795 applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
10796 setTimeout(() => {
10797 if (globalState.timeout && globalState.timeout.running) {
10798 // timer can be already stopped or unset at this point
10799 animateTimerProgressBar(/** @type {number} */innerParams.timer);
10800 }
10801 });
10802 }
10803 }
10804 };
10805
10806 /**
10807 * Initialize focus in the popup:
10808 *
10809 * 1. If `toast` is `true`, don't steal focus from the document.
10810 * 2. Else if there is an [autofocus] element, focus it.
10811 * 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.
10812 * 4. Else if `focusDeny` is `true` and deny button is visible, focus it.
10813 * 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.
10814 * 6. Else focus the first focusable element in a popup (if any).
10815 *
10816 * @param {DomCache} domCache
10817 * @param {SweetAlertOptions} innerParams
10818 */
10819 const initFocus = (domCache, innerParams) => {
10820 if (innerParams.toast) {
10821 return;
10822 }
10823 // TODO: this is dumb, remove `allowEnterKey` param in the next major version
10824 if (!callIfFunction(innerParams.allowEnterKey)) {
10825 warnAboutDeprecation('allowEnterKey', 'preConfirm: () => false');
10826 domCache.popup.focus();
10827 return;
10828 }
10829 if (focusAutofocus(domCache)) {
10830 return;
10831 }
10832 if (focusButton(domCache, innerParams)) {
10833 return;
10834 }
10835 setFocus(-1, 1);
10836 };
10837
10838 /**
10839 * @param {DomCache} domCache
10840 * @returns {boolean}
10841 */
10842 const focusAutofocus = domCache => {
10843 const autofocusElements = Array.from(domCache.popup.querySelectorAll('[autofocus]'));
10844 for (const autofocusElement of autofocusElements) {
10845 if (autofocusElement instanceof HTMLElement && isVisible$1(autofocusElement)) {
10846 autofocusElement.focus();
10847 return true;
10848 }
10849 }
10850 return false;
10851 };
10852
10853 /**
10854 * @param {DomCache} domCache
10855 * @param {SweetAlertOptions} innerParams
10856 * @returns {boolean}
10857 */
10858 const focusButton = (domCache, innerParams) => {
10859 if (innerParams.focusDeny && isVisible$1(domCache.denyButton)) {
10860 domCache.denyButton.focus();
10861 return true;
10862 }
10863 if (innerParams.focusCancel && isVisible$1(domCache.cancelButton)) {
10864 domCache.cancelButton.focus();
10865 return true;
10866 }
10867 if (innerParams.focusConfirm && isVisible$1(domCache.confirmButton)) {
10868 domCache.confirmButton.focus();
10869 return true;
10870 }
10871 return false;
10872 };
10873
10874 // Assign instance methods from src/instanceMethods/*.js to prototype
10875 SweetAlert.prototype.disableButtons = disableButtons;
10876 SweetAlert.prototype.enableButtons = enableButtons;
10877 SweetAlert.prototype.getInput = getInput;
10878 SweetAlert.prototype.disableInput = disableInput;
10879 SweetAlert.prototype.enableInput = enableInput;
10880 SweetAlert.prototype.hideLoading = hideLoading;
10881 SweetAlert.prototype.disableLoading = hideLoading;
10882 SweetAlert.prototype.showValidationMessage = showValidationMessage;
10883 SweetAlert.prototype.resetValidationMessage = resetValidationMessage;
10884 SweetAlert.prototype.close = close;
10885 SweetAlert.prototype.closePopup = close;
10886 SweetAlert.prototype.closeModal = close;
10887 SweetAlert.prototype.closeToast = close;
10888 SweetAlert.prototype.rejectPromise = rejectPromise;
10889 SweetAlert.prototype.update = update;
10890 SweetAlert.prototype._destroy = _destroy;
10891
10892 // Assign static methods from src/staticMethods/*.js to constructor
10893 Object.assign(SweetAlert, staticMethods);
10894
10895 // Proxy to instance methods to constructor, for now, for backwards compatibility
10896 Object.keys(instanceMethods).forEach(key => {
10897 /**
10898 * @param {...(SweetAlertOptions | string | undefined)} args
10899 * @returns {SweetAlertResult | Promise<SweetAlertResult> | undefined}
10900 */
10901 // @ts-ignore: Dynamic property assignment for backwards compatibility
10902 SweetAlert[key] = function (...args) {
10903 // @ts-ignore
10904 if (currentInstance && currentInstance[key]) {
10905 // @ts-ignore
10906 return currentInstance[key](...args);
10907 }
10908 return undefined;
10909 };
10910 });
10911 SweetAlert.DismissReason = DismissReason;
10912 SweetAlert.version = '11.26.25';
10913
10914 const Swal = SweetAlert;
10915 // @ts-ignore
10916 Swal.default = Swal;
10917
10918 return Swal;
10919
10920 }));
10921 if (typeof this !== 'undefined' && this.Sweetalert2){this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}
10922 "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-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:auto}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}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)}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}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}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}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)}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:auto}.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}.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}}");
10923
10924 /***/ },
10925
10926 /***/ "./node_modules/toastify-js/src/toastify.js"
10927 /*!**************************************************!*\
10928 !*** ./node_modules/toastify-js/src/toastify.js ***!
10929 \**************************************************/
10930 (module) {
10931
10932 /*!
10933 * Toastify js 1.12.0
10934 * https://github.com/apvarun/toastify-js
10935 * @license MIT licensed
10936 *
10937 * Copyright (C) 2018 Varun A P
10938 */
10939 (function(root, factory) {
10940 if ( true && module.exports) {
10941 module.exports = factory();
10942 } else {
10943 root.Toastify = factory();
10944 }
10945 })(this, function(global) {
10946 // Object initialization
10947 var Toastify = function(options) {
10948 // Returning a new init object
10949 return new Toastify.lib.init(options);
10950 },
10951 // Library version
10952 version = "1.12.0";
10953
10954 // Set the default global options
10955 Toastify.defaults = {
10956 oldestFirst: true,
10957 text: "Toastify is awesome!",
10958 node: undefined,
10959 duration: 3000,
10960 selector: undefined,
10961 callback: function () {
10962 },
10963 destination: undefined,
10964 newWindow: false,
10965 close: false,
10966 gravity: "toastify-top",
10967 positionLeft: false,
10968 position: '',
10969 backgroundColor: '',
10970 avatar: "",
10971 className: "",
10972 stopOnFocus: true,
10973 onClick: function () {
10974 },
10975 offset: {x: 0, y: 0},
10976 escapeMarkup: true,
10977 ariaLive: 'polite',
10978 style: {background: ''}
10979 };
10980
10981 // Defining the prototype of the object
10982 Toastify.lib = Toastify.prototype = {
10983 toastify: version,
10984
10985 constructor: Toastify,
10986
10987 // Initializing the object with required parameters
10988 init: function(options) {
10989 // Verifying and validating the input object
10990 if (!options) {
10991 options = {};
10992 }
10993
10994 // Creating the options object
10995 this.options = {};
10996
10997 this.toastElement = null;
10998
10999 // Validating the options
11000 this.options.text = options.text || Toastify.defaults.text; // Display message
11001 this.options.node = options.node || Toastify.defaults.node; // Display content as node
11002 this.options.duration = options.duration === 0 ? 0 : options.duration || Toastify.defaults.duration; // Display duration
11003 this.options.selector = options.selector || Toastify.defaults.selector; // Parent selector
11004 this.options.callback = options.callback || Toastify.defaults.callback; // Callback after display
11005 this.options.destination = options.destination || Toastify.defaults.destination; // On-click destination
11006 this.options.newWindow = options.newWindow || Toastify.defaults.newWindow; // Open destination in new window
11007 this.options.close = options.close || Toastify.defaults.close; // Show toast close icon
11008 this.options.gravity = options.gravity === "bottom" ? "toastify-bottom" : Toastify.defaults.gravity; // toast position - top or bottom
11009 this.options.positionLeft = options.positionLeft || Toastify.defaults.positionLeft; // toast position - left or right
11010 this.options.position = options.position || Toastify.defaults.position; // toast position - left or right
11011 this.options.backgroundColor = options.backgroundColor || Toastify.defaults.backgroundColor; // toast background color
11012 this.options.avatar = options.avatar || Toastify.defaults.avatar; // img element src - url or a path
11013 this.options.className = options.className || Toastify.defaults.className; // additional class names for the toast
11014 this.options.stopOnFocus = options.stopOnFocus === undefined ? Toastify.defaults.stopOnFocus : options.stopOnFocus; // stop timeout on focus
11015 this.options.onClick = options.onClick || Toastify.defaults.onClick; // Callback after click
11016 this.options.offset = options.offset || Toastify.defaults.offset; // toast offset
11017 this.options.escapeMarkup = options.escapeMarkup !== undefined ? options.escapeMarkup : Toastify.defaults.escapeMarkup;
11018 this.options.ariaLive = options.ariaLive || Toastify.defaults.ariaLive;
11019 this.options.style = options.style || Toastify.defaults.style;
11020 if(options.backgroundColor) {
11021 this.options.style.background = options.backgroundColor;
11022 }
11023
11024 // Returning the current object for chaining functions
11025 return this;
11026 },
11027
11028 // Building the DOM element
11029 buildToast: function() {
11030 // Validating if the options are defined
11031 if (!this.options) {
11032 throw "Toastify is not initialized";
11033 }
11034
11035 // Creating the DOM object
11036 var divElement = document.createElement("div");
11037 divElement.className = "toastify on " + this.options.className;
11038
11039 // Positioning toast to left or right or center
11040 if (!!this.options.position) {
11041 divElement.className += " toastify-" + this.options.position;
11042 } else {
11043 // To be depreciated in further versions
11044 if (this.options.positionLeft === true) {
11045 divElement.className += " toastify-left";
11046 console.warn('Property `positionLeft` will be depreciated in further versions. Please use `position` instead.')
11047 } else {
11048 // Default position
11049 divElement.className += " toastify-right";
11050 }
11051 }
11052
11053 // Assigning gravity of element
11054 divElement.className += " " + this.options.gravity;
11055
11056 if (this.options.backgroundColor) {
11057 // This is being deprecated in favor of using the style HTML DOM property
11058 console.warn('DEPRECATION NOTICE: "backgroundColor" is being deprecated. Please use the "style.background" property.');
11059 }
11060
11061 // Loop through our style object and apply styles to divElement
11062 for (var property in this.options.style) {
11063 divElement.style[property] = this.options.style[property];
11064 }
11065
11066 // Announce the toast to screen readers
11067 if (this.options.ariaLive) {
11068 divElement.setAttribute('aria-live', this.options.ariaLive)
11069 }
11070
11071 // Adding the toast message/node
11072 if (this.options.node && this.options.node.nodeType === Node.ELEMENT_NODE) {
11073 // If we have a valid node, we insert it
11074 divElement.appendChild(this.options.node)
11075 } else {
11076 if (this.options.escapeMarkup) {
11077 divElement.innerText = this.options.text;
11078 } else {
11079 divElement.innerHTML = this.options.text;
11080 }
11081
11082 if (this.options.avatar !== "") {
11083 var avatarElement = document.createElement("img");
11084 avatarElement.src = this.options.avatar;
11085
11086 avatarElement.className = "toastify-avatar";
11087
11088 if (this.options.position == "left" || this.options.positionLeft === true) {
11089 // Adding close icon on the left of content
11090 divElement.appendChild(avatarElement);
11091 } else {
11092 // Adding close icon on the right of content
11093 divElement.insertAdjacentElement("afterbegin", avatarElement);
11094 }
11095 }
11096 }
11097
11098 // Adding a close icon to the toast
11099 if (this.options.close === true) {
11100 // Create a span for close element
11101 var closeElement = document.createElement("button");
11102 closeElement.type = "button";
11103 closeElement.setAttribute("aria-label", "Close");
11104 closeElement.className = "toast-close";
11105 closeElement.innerHTML = "&#10006;";
11106
11107 // Triggering the removal of toast from DOM on close click
11108 closeElement.addEventListener(
11109 "click",
11110 function(event) {
11111 event.stopPropagation();
11112 this.removeElement(this.toastElement);
11113 window.clearTimeout(this.toastElement.timeOutValue);
11114 }.bind(this)
11115 );
11116
11117 //Calculating screen width
11118 var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
11119
11120 // Adding the close icon to the toast element
11121 // Display on the right if screen width is less than or equal to 360px
11122 if ((this.options.position == "left" || this.options.positionLeft === true) && width > 360) {
11123 // Adding close icon on the left of content
11124 divElement.insertAdjacentElement("afterbegin", closeElement);
11125 } else {
11126 // Adding close icon on the right of content
11127 divElement.appendChild(closeElement);
11128 }
11129 }
11130
11131 // Clear timeout while toast is focused
11132 if (this.options.stopOnFocus && this.options.duration > 0) {
11133 var self = this;
11134 // stop countdown
11135 divElement.addEventListener(
11136 "mouseover",
11137 function(event) {
11138 window.clearTimeout(divElement.timeOutValue);
11139 }
11140 )
11141 // add back the timeout
11142 divElement.addEventListener(
11143 "mouseleave",
11144 function() {
11145 divElement.timeOutValue = window.setTimeout(
11146 function() {
11147 // Remove the toast from DOM
11148 self.removeElement(divElement);
11149 },
11150 self.options.duration
11151 )
11152 }
11153 )
11154 }
11155
11156 // Adding an on-click destination path
11157 if (typeof this.options.destination !== "undefined") {
11158 divElement.addEventListener(
11159 "click",
11160 function(event) {
11161 event.stopPropagation();
11162 if (this.options.newWindow === true) {
11163 window.open(this.options.destination, "_blank");
11164 } else {
11165 window.location = this.options.destination;
11166 }
11167 }.bind(this)
11168 );
11169 }
11170
11171 if (typeof this.options.onClick === "function" && typeof this.options.destination === "undefined") {
11172 divElement.addEventListener(
11173 "click",
11174 function(event) {
11175 event.stopPropagation();
11176 this.options.onClick();
11177 }.bind(this)
11178 );
11179 }
11180
11181 // Adding offset
11182 if(typeof this.options.offset === "object") {
11183
11184 var x = getAxisOffsetAValue("x", this.options);
11185 var y = getAxisOffsetAValue("y", this.options);
11186
11187 var xOffset = this.options.position == "left" ? x : "-" + x;
11188 var yOffset = this.options.gravity == "toastify-top" ? y : "-" + y;
11189
11190 divElement.style.transform = "translate(" + xOffset + "," + yOffset + ")";
11191
11192 }
11193
11194 // Returning the generated element
11195 return divElement;
11196 },
11197
11198 // Displaying the toast
11199 showToast: function() {
11200 // Creating the DOM object for the toast
11201 this.toastElement = this.buildToast();
11202
11203 // Getting the root element to with the toast needs to be added
11204 var rootElement;
11205 if (typeof this.options.selector === "string") {
11206 rootElement = document.getElementById(this.options.selector);
11207 } else if (this.options.selector instanceof HTMLElement || (typeof ShadowRoot !== 'undefined' && this.options.selector instanceof ShadowRoot)) {
11208 rootElement = this.options.selector;
11209 } else {
11210 rootElement = document.body;
11211 }
11212
11213 // Validating if root element is present in DOM
11214 if (!rootElement) {
11215 throw "Root element is not defined";
11216 }
11217
11218 // Adding the DOM element
11219 var elementToInsert = Toastify.defaults.oldestFirst ? rootElement.firstChild : rootElement.lastChild;
11220 rootElement.insertBefore(this.toastElement, elementToInsert);
11221
11222 // Repositioning the toasts in case multiple toasts are present
11223 Toastify.reposition();
11224
11225 if (this.options.duration > 0) {
11226 this.toastElement.timeOutValue = window.setTimeout(
11227 function() {
11228 // Remove the toast from DOM
11229 this.removeElement(this.toastElement);
11230 }.bind(this),
11231 this.options.duration
11232 ); // Binding `this` for function invocation
11233 }
11234
11235 // Supporting function chaining
11236 return this;
11237 },
11238
11239 hideToast: function() {
11240 if (this.toastElement.timeOutValue) {
11241 clearTimeout(this.toastElement.timeOutValue);
11242 }
11243 this.removeElement(this.toastElement);
11244 },
11245
11246 // Removing the element from the DOM
11247 removeElement: function(toastElement) {
11248 // Hiding the element
11249 // toastElement.classList.remove("on");
11250 toastElement.className = toastElement.className.replace(" on", "");
11251
11252 // Removing the element from DOM after transition end
11253 window.setTimeout(
11254 function() {
11255 // remove options node if any
11256 if (this.options.node && this.options.node.parentNode) {
11257 this.options.node.parentNode.removeChild(this.options.node);
11258 }
11259
11260 // Remove the element from the DOM, only when the parent node was not removed before.
11261 if (toastElement.parentNode) {
11262 toastElement.parentNode.removeChild(toastElement);
11263 }
11264
11265 // Calling the callback function
11266 this.options.callback.call(toastElement);
11267
11268 // Repositioning the toasts again
11269 Toastify.reposition();
11270 }.bind(this),
11271 400
11272 ); // Binding `this` for function invocation
11273 },
11274 };
11275
11276 // Positioning the toasts on the DOM
11277 Toastify.reposition = function() {
11278
11279 // Top margins with gravity
11280 var topLeftOffsetSize = {
11281 top: 15,
11282 bottom: 15,
11283 };
11284 var topRightOffsetSize = {
11285 top: 15,
11286 bottom: 15,
11287 };
11288 var offsetSize = {
11289 top: 15,
11290 bottom: 15,
11291 };
11292
11293 // Get all toast messages on the DOM
11294 var allToasts = document.getElementsByClassName("toastify");
11295
11296 var classUsed;
11297
11298 // Modifying the position of each toast element
11299 for (var i = 0; i < allToasts.length; i++) {
11300 // Getting the applied gravity
11301 if (containsClass(allToasts[i], "toastify-top") === true) {
11302 classUsed = "toastify-top";
11303 } else {
11304 classUsed = "toastify-bottom";
11305 }
11306
11307 var height = allToasts[i].offsetHeight;
11308 classUsed = classUsed.substr(9, classUsed.length-1)
11309 // Spacing between toasts
11310 var offset = 15;
11311
11312 var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
11313
11314 // Show toast in center if screen with less than or equal to 360px
11315 if (width <= 360) {
11316 // Setting the position
11317 allToasts[i].style[classUsed] = offsetSize[classUsed] + "px";
11318
11319 offsetSize[classUsed] += height + offset;
11320 } else {
11321 if (containsClass(allToasts[i], "toastify-left") === true) {
11322 // Setting the position
11323 allToasts[i].style[classUsed] = topLeftOffsetSize[classUsed] + "px";
11324
11325 topLeftOffsetSize[classUsed] += height + offset;
11326 } else {
11327 // Setting the position
11328 allToasts[i].style[classUsed] = topRightOffsetSize[classUsed] + "px";
11329
11330 topRightOffsetSize[classUsed] += height + offset;
11331 }
11332 }
11333 }
11334
11335 // Supporting function chaining
11336 return this;
11337 };
11338
11339 // Helper function to get offset.
11340 function getAxisOffsetAValue(axis, options) {
11341
11342 if(options.offset[axis]) {
11343 if(isNaN(options.offset[axis])) {
11344 return options.offset[axis];
11345 }
11346 else {
11347 return options.offset[axis] + 'px';
11348 }
11349 }
11350
11351 return '0px';
11352
11353 }
11354
11355 function containsClass(elem, yourClass) {
11356 if (!elem || typeof yourClass !== "string") {
11357 return false;
11358 } else if (
11359 elem.className &&
11360 elem.className
11361 .trim()
11362 .split(/\s+/gi)
11363 .indexOf(yourClass) > -1
11364 ) {
11365 return true;
11366 } else {
11367 return false;
11368 }
11369 }
11370
11371 // Setting up the prototype for the init object
11372 Toastify.lib.init.prototype = Toastify.lib;
11373
11374 // Returning the Toastify function to be assigned to the window object/module
11375 return Toastify;
11376 });
11377
11378
11379 /***/ }
11380
11381 /******/ });
11382 /************************************************************************/
11383 /******/ // The module cache
11384 /******/ const __webpack_module_cache__ = {};
11385 /******/
11386 /******/ // The require function
11387 /******/ function __webpack_require__(moduleId) {
11388 /******/ // Check if module is in cache
11389 /******/ const cachedModule = __webpack_module_cache__[moduleId];
11390 /******/ if (cachedModule !== undefined) {
11391 /******/ return cachedModule.exports;
11392 /******/ }
11393 /******/ // Create a new module (and put it into the cache)
11394 /******/ const module = __webpack_module_cache__[moduleId] = {
11395 /******/ id: moduleId,
11396 /******/ // no module.loaded needed
11397 /******/ exports: {}
11398 /******/ };
11399 /******/
11400 /******/ // Execute the module function
11401 /******/ if (!(moduleId in __webpack_modules__)) {
11402 /******/ delete __webpack_module_cache__[moduleId];
11403 /******/ const e = new Error("Cannot find module '" + moduleId + "'");
11404 /******/ e.code = 'MODULE_NOT_FOUND';
11405 /******/ throw e;
11406 /******/ }
11407 /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
11408 /******/
11409 /******/ // Return the exports of the module
11410 /******/ return module.exports;
11411 /******/ }
11412 /******/
11413 /************************************************************************/
11414 /******/ /* webpack/runtime/compat get default export */
11415 /******/ (() => {
11416 /******/ // getDefaultExport function for compatibility with non-harmony modules
11417 /******/ __webpack_require__.n = (module) => {
11418 /******/ const getter = module && module.__esModule ?
11419 /******/ () => (module['default']) :
11420 /******/ () => (module);
11421 /******/ __webpack_require__.d(getter, { a: getter });
11422 /******/ return getter;
11423 /******/ };
11424 /******/ })();
11425 /******/
11426 /******/ /* webpack/runtime/define property getters */
11427 /******/ (() => {
11428 /******/ // define getter/value functions for harmony exports
11429 /******/ __webpack_require__.d = (exports, definition) => {
11430 /******/ if(Array.isArray(definition)) {
11431 /******/ var i = 0;
11432 /******/ while(i < definition.length) {
11433 /******/ var key = definition[i++];
11434 /******/ var binding = definition[i++];
11435 /******/ if(!__webpack_require__.o(exports, key)) {
11436 /******/ if(binding === 0) {
11437 /******/ Object.defineProperty(exports, key, { enumerable: true, value: definition[i++] });
11438 /******/ } else {
11439 /******/ Object.defineProperty(exports, key, { enumerable: true, get: binding });
11440 /******/ }
11441 /******/ } else if(binding === 0) { i++; }
11442 /******/ }
11443 /******/ } else {
11444 /******/ for(var key in definition) {
11445 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
11446 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
11447 /******/ }
11448 /******/ }
11449 /******/ }
11450 /******/ };
11451 /******/ })();
11452 /******/
11453 /******/ /* webpack/runtime/hasOwnProperty shorthand */
11454 /******/ (() => {
11455 /******/ __webpack_require__.o = (obj, prop) => (Object.hasOwn(obj, prop))
11456 /******/ })();
11457 /******/
11458 /******/ /* webpack/runtime/make namespace object */
11459 /******/ (() => {
11460 /******/ // define __esModule on exports
11461 /******/ __webpack_require__.r = (exports) => {
11462 /******/ if(Symbol.toStringTag) {
11463 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
11464 /******/ }
11465 /******/ Object.defineProperty(exports, '__esModule', { value: true });
11466 /******/ };
11467 /******/ })();
11468 /******/
11469 /******/ /* webpack/runtime/nonce */
11470 /******/ (() => {
11471 /******/ __webpack_require__.nc = undefined;
11472 /******/ })();
11473 /******/
11474 /************************************************************************/
11475 let __webpack_exports__ = {};
11476 // This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
11477 (() => {
11478 "use strict";
11479 /*!******************************************!*\
11480 !*** ./assets/src/js/admin/edit-quiz.js ***!
11481 \******************************************/
11482 __webpack_require__.r(__webpack_exports__);
11483 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./assets/src/js/utils.js");
11484 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! sweetalert2 */ "./node_modules/sweetalert2/dist/sweetalert2.all.js");
11485 /* harmony import */ var sweetalert2__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(sweetalert2__WEBPACK_IMPORTED_MODULE_1__);
11486 /* harmony import */ var sortablejs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! sortablejs */ "./node_modules/sortablejs/modular/sortable.esm.js");
11487 /* harmony import */ var lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lpAssetsJsPath/lpToastify.js */ "./assets/src/js/lpToastify.js");
11488 /* 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");
11489 /* harmony import */ var _edit_question_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./edit-question.js */ "./assets/src/js/admin/edit-question.js");
11490 /* harmony import */ var lpAssetsJsPath_lpPopupSelectItemToAdd_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lpAssetsJsPath/lpPopupSelectItemToAdd.js */ "./assets/src/js/lpPopupSelectItemToAdd.js");
11491 /**
11492 * Edit Quiz JS handler as a class.
11493 *
11494 * @since 4.2.8.6
11495 * @version 1.0.3
11496 */
11497
11498
11499
11500
11501
11502
11503
11504 let editQuestion;
11505 const lpPopupSelectItemToAdd = new lpAssetsJsPath_lpPopupSelectItemToAdd_js__WEBPACK_IMPORTED_MODULE_6__.LpPopupSelectItemToAdd();
11506 lpPopupSelectItemToAdd.init();
11507 class EditQuiz {
11508 constructor() {
11509 this.idUrlHandle = 'edit-quiz-questions';
11510 this.elEditQuizWrap = null;
11511 this.elEditListQuestions = null;
11512 this.quizID = null;
11513 }
11514 static selectors = {
11515 elEditQuizWrap: '.lp-edit-quiz-wrap',
11516 elQuestionEditMain: '.lp-question-edit-main',
11517 elQuestionToggleAll: '.lp-question-toggle-all',
11518 elEditListQuestions: '.lp-edit-list-questions',
11519 elQuestionItem: '.lp-question-item',
11520 elQuestionToggle: '.lp-question-toggle',
11521 elPopupItemsToSelectClone: '.lp-popup-items-to-select.clone',
11522 elBtnAddQuestion: '.lp-btn-add-question',
11523 elBtnRemoveQuestion: '.lp-btn-remove-question',
11524 elBtnUpdateQuestionTitle: '.lp-btn-update-question-title',
11525 elBtnCancelUpdateQuestionTitle: '.lp-btn-cancel-update-question-title',
11526 elQuestionTitleNewInput: '.lp-question-title-new-input',
11527 elQuestionTitleInput: '.lp-question-title-input',
11528 elQuestionTypeLabel: '.lp-question-type-label',
11529 elQuestionTypeNew: '.lp-question-type-new',
11530 elAddNewQuestion: 'add-new-question',
11531 elQuestionClone: '.lp-question-item.clone',
11532 LPTarget: '.lp-target',
11533 elCollapse: 'lp-collapse'
11534 };
11535 init() {
11536 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpOnElementReady(EditQuiz.selectors.elEditQuizWrap, elEditQuizWrapFound => {
11537 this.elEditQuizWrap = elEditQuizWrapFound;
11538 this.elEditListQuestions = this.elEditQuizWrap.querySelector(EditQuiz.selectors.elEditListQuestions);
11539 const elLPTarget = this.elEditQuizWrap.closest(EditQuiz.selectors.LPTarget);
11540 const dataSend = window.lpAJAXG.getDataSetCurrent(elLPTarget);
11541 this.quizID = dataSend.args.quiz_id;
11542 this.sortAbleQuestion();
11543 editQuestion = new _edit_question_js__WEBPACK_IMPORTED_MODULE_5__.EditQuestion();
11544 editQuestion.init();
11545 const elQuestionEditMains = elEditQuizWrapFound.querySelectorAll(`${EditQuiz.selectors.elQuestionEditMain}`);
11546 elQuestionEditMains.forEach(elQuestionEditMain => {
11547 editQuestion.sortAbleQuestionAnswer(elQuestionEditMain);
11548 });
11549 this.events();
11550 });
11551 }
11552 events() {
11553 if (EditQuiz._loadedEvents) {
11554 return;
11555 }
11556 EditQuiz._loadedEvents = true;
11557 _utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('click', [{
11558 selector: EditQuiz.selectors.elQuestionToggleAll,
11559 class: this,
11560 callBack: this.toggleQuestionAll.name
11561 }, {
11562 selector: EditQuiz.selectors.elBtnAddQuestion,
11563 class: this,
11564 callBack: this.addQuestion.name
11565 }, {
11566 selector: EditQuiz.selectors.elBtnRemoveQuestion,
11567 class: this,
11568 callBack: this.removeQuestion.name
11569 }, {
11570 selector: EditQuiz.selectors.elBtnUpdateQuestionTitle,
11571 class: this,
11572 callBack: this.updateQuestionTitle.name
11573 }, {
11574 selector: EditQuiz.selectors.elBtnCancelUpdateQuestionTitle,
11575 class: this,
11576 callBack: this.cancelChangeTitleQuestion.name
11577 }, {
11578 selector: lpAssetsJsPath_lpPopupSelectItemToAdd_js__WEBPACK_IMPORTED_MODULE_6__.LpPopupSelectItemToAdd.selectors.elBtnAddItemsSelected,
11579 class: lpPopupSelectItemToAdd,
11580 callBack: lpPopupSelectItemToAdd.addItemsSelectedToSection.name,
11581 callBackHandle: this.addQuestionsSelectedToQuiz.bind(this)
11582 }]);
11583
11584 // Keydown
11585 _utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('keydown', [{
11586 selector: EditQuiz.selectors.elQuestionTitleInput,
11587 class: this,
11588 callBack: this.updateQuestionTitle.name,
11589 checkIsEventEnter: true
11590 }, {
11591 selector: EditQuiz.selectors.elQuestionTitleNewInput,
11592 class: this,
11593 callBack: this.addQuestion.name,
11594 checkIsEventEnter: true
11595 }]);
11596
11597 // Keyup
11598 _utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('keyup', [{
11599 selector: EditQuiz.selectors.elQuestionTitleInput,
11600 class: this,
11601 callBack: this.changeTitleQuestion.name
11602 }, {
11603 selector: `${EditQuiz.selectors.elQuestionTitleNewInput}, ${EditQuiz.selectors.elQuestionTypeNew}`,
11604 class: this,
11605 callBack: this.checkCanAddQuestion.name
11606 }]);
11607
11608 // Change
11609 _utils_js__WEBPACK_IMPORTED_MODULE_0__.eventHandlers('change', [{
11610 selector: EditQuiz.selectors.elQuestionTypeNew,
11611 class: this,
11612 callBack: this.checkCanAddQuestion.name
11613 }]);
11614
11615 // Click
11616 document.addEventListener('click', e => {
11617 const target = e.target;
11618 _utils_js__WEBPACK_IMPORTED_MODULE_0__.toggleCollapse(e, target, EditQuiz.selectors.elQuestionToggle, [], () => this.checkAllQuestionsCollapsed());
11619 });
11620 }
11621
11622 // Toggle all questions
11623 toggleQuestionAll(args) {
11624 const {
11625 e,
11626 target
11627 } = args;
11628 const elQuestionToggleAll = target.closest(`${EditQuiz.selectors.elQuestionToggleAll}`);
11629 if (!elQuestionToggleAll) {
11630 return;
11631 }
11632 const elQuestionItems = this.elEditQuizWrap.querySelectorAll(`${EditQuiz.selectors.elQuestionItem}:not(.clone)`);
11633 elQuestionToggleAll.classList.toggle(`${EditQuiz.selectors.elCollapse}`);
11634 elQuestionItems.forEach(el => {
11635 const shouldCollapse = elQuestionToggleAll.classList.contains(`${EditQuiz.selectors.elCollapse}`);
11636 el.classList.toggle(`${EditQuiz.selectors.elCollapse}`, shouldCollapse);
11637 });
11638 }
11639 checkAllQuestionsCollapsed() {
11640 const elQuestionItems = this.elEditQuizWrap.querySelectorAll(`${EditQuiz.selectors.elQuestionItem}:not(.clone)`);
11641 const elQuestionToggleAll = this.elEditQuizWrap.querySelector(`${EditQuiz.selectors.elQuestionToggleAll}`);
11642 let isAllExpand = true;
11643 elQuestionItems.forEach(el => {
11644 if (el.classList.contains(`${EditQuiz.selectors.elCollapse}`)) {
11645 isAllExpand = false;
11646 return false; // Break
11647 }
11648 });
11649 if (isAllExpand) {
11650 elQuestionToggleAll.classList.remove(`${EditQuiz.selectors.elCollapse}`);
11651 } else {
11652 elQuestionToggleAll.classList.add(`${EditQuiz.selectors.elCollapse}`);
11653 }
11654 }
11655 updateCountItems() {
11656 const elCountItemsAll = this.elEditQuizWrap.querySelector('.total-items');
11657 const elItemsAll = this.elEditQuizWrap.querySelectorAll(`${EditQuiz.selectors.elQuestionItem}:not(.clone)`);
11658 const itemsAllCount = elItemsAll.length;
11659 elCountItemsAll.dataset.count = itemsAllCount;
11660 elCountItemsAll.querySelector('.count').textContent = itemsAllCount;
11661 }
11662
11663 // Add question to quiz
11664 addQuestion(args) {
11665 const {
11666 e,
11667 target,
11668 callBackNest
11669 } = args;
11670 e.preventDefault();
11671 const elAddNewQuestion = target.closest(`.${EditQuiz.selectors.elAddNewQuestion}`);
11672 if (!elAddNewQuestion) {
11673 return;
11674 }
11675 const elQuestionTitleNewInput = elAddNewQuestion.querySelector(`${EditQuiz.selectors.elQuestionTitleNewInput}`);
11676 const questionTitle = elQuestionTitleNewInput.value.trim();
11677 if (!questionTitle) {
11678 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(elQuestionTitleNewInput.dataset.messEmptyTitle, 'error');
11679 return;
11680 }
11681 const elQuestionType = elAddNewQuestion.querySelector(`${EditQuiz.selectors.elQuestionTypeNew}`);
11682 const questionType = elQuestionType.value;
11683 if (!questionType) {
11684 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(elQuestionType.dataset.messEmptyType, 'error');
11685 return;
11686 }
11687 const elQuestionClone = this.elEditListQuestions.querySelector(`${EditQuiz.selectors.elQuestionItem}.clone`);
11688 const newQuestionItem = elQuestionClone.cloneNode(true);
11689 const elQuestionTitleInput = newQuestionItem.querySelector(`${EditQuiz.selectors.elQuestionTitleInput}`);
11690 elQuestionTitleInput.value = questionTitle;
11691 elQuestionTitleNewInput.value = '';
11692 newQuestionItem.classList.remove('clone');
11693 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(newQuestionItem, 1);
11694 elQuestionClone.insertAdjacentElement('beforebegin', newQuestionItem);
11695 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(newQuestionItem, 1);
11696 const callBack = {
11697 success: response => {
11698 const {
11699 message,
11700 status,
11701 data
11702 } = response;
11703 const {
11704 question,
11705 html_edit_question
11706 } = data;
11707 if (status === 'error') {
11708 throw `Error: ${message}`;
11709 } else if (status === 'success') {
11710 newQuestionItem.dataset.questionId = question.ID;
11711 newQuestionItem.dataset.questionType = question.meta_data._lp_type;
11712 newQuestionItem.outerHTML = html_edit_question;
11713 const elQuestionItemCreated = this.elEditListQuestions.querySelector(`${EditQuiz.selectors.elQuestionItem}[data-question-id="${question.ID}"]`);
11714 elQuestionItemCreated.classList.remove(EditQuiz.selectors.elCollapse);
11715 this.updateCountItems();
11716 editQuestion.initTinyMCE();
11717 const elQuestionEditMain = elQuestionItemCreated.querySelector(`${EditQuiz.selectors.elQuestionEditMain}`);
11718 editQuestion.sortAbleQuestionAnswer(elQuestionEditMain);
11719
11720 // Callback nest
11721 if (callBackNest && typeof callBackNest.success === 'function') {
11722 callBackNest.success({
11723 response,
11724 elQuestionItemCreated
11725 });
11726 }
11727 }
11728 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(message, status);
11729 },
11730 error: error => {
11731 newQuestionItem.remove();
11732 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(error, 'error');
11733 if (callBackNest && typeof callBackNest.error === 'function') {
11734 callBackNest.error({
11735 error,
11736 newQuestionItem
11737 });
11738 }
11739 },
11740 completed: () => {
11741 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(newQuestionItem, 0);
11742 this.checkCanAddQuestion({
11743 e,
11744 target: elQuestionTitleNewInput
11745 });
11746 if (callBackNest && typeof callBackNest.completed === 'function') {
11747 callBackNest.completed({
11748 newQuestionItem
11749 });
11750 }
11751 }
11752 };
11753 let dataSend = JSON.parse(elQuestionTitleNewInput.dataset.send);
11754 dataSend = {
11755 ...dataSend,
11756 question_title: questionTitle,
11757 question_type: questionType
11758 };
11759 window.lpAJAXG.fetchAJAX(dataSend, callBack);
11760 }
11761
11762 // Add questions selected from popup to quiz
11763 addQuestionsSelectedToQuiz(itemsSelected) {
11764 const questionIds = [];
11765 itemsSelected.forEach(item => {
11766 const elQuestionItemClone = this.elEditQuizWrap.querySelector(`${EditQuiz.selectors.elQuestionItem}.clone`);
11767 if (!elQuestionItemClone) {
11768 return;
11769 }
11770 questionIds.push(item.id);
11771 const elQuestionItemNew = elQuestionItemClone.cloneNode(true);
11772 const elQuestionItemTitleInput = elQuestionItemNew.querySelector(`${EditQuiz.selectors.elQuestionTitleInput}`);
11773 elQuestionItemNew.classList.remove('clone');
11774 elQuestionItemNew.dataset.questionId = item.id;
11775 elQuestionItemTitleInput.value = item.titleSelected;
11776 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItemNew, 1);
11777 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpShowHideEl(elQuestionItemNew, 1);
11778 elQuestionItemClone.insertAdjacentElement('beforebegin', elQuestionItemNew);
11779 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItemNew, 1);
11780 });
11781 const callBack = {
11782 success: response => {
11783 const {
11784 message,
11785 status,
11786 data
11787 } = response;
11788 if (status === 'success') {
11789 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(message, status);
11790 const {
11791 html_edit_question
11792 } = data;
11793 if (html_edit_question) {
11794 Object.entries(html_edit_question).forEach(([question_id, item_html]) => {
11795 const elQuestionItemNew = this.elEditQuizWrap.querySelector(`${EditQuiz.selectors.elQuestionItem}[data-question-id="${question_id}"]`);
11796 elQuestionItemNew.outerHTML = item_html;
11797 });
11798 }
11799 this.updateCountItems();
11800 editQuestion.initTinyMCE();
11801 } else {
11802 throw `Error: ${message}`;
11803 }
11804 },
11805 error: error => {
11806 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(error, 'error');
11807 },
11808 completed: () => {
11809 // completed handler intentionally empty
11810 }
11811 };
11812 const dataSend = {
11813 action: 'add_questions_to_quiz',
11814 quiz_id: this.quizID,
11815 question_ids: questionIds,
11816 args: {
11817 id_url: this.idUrlHandle
11818 }
11819 };
11820 window.lpAJAXG.fetchAJAX(dataSend, callBack);
11821 }
11822 checkCanAddQuestion(args) {
11823 const {
11824 e,
11825 target
11826 } = args;
11827 const elTrigger = target.closest(EditQuiz.selectors.elQuestionTitleNewInput) || target.closest(EditQuiz.selectors.elQuestionTypeNew);
11828 if (!elTrigger) {
11829 return;
11830 }
11831 const elAddNewQuestion = elTrigger.closest(`.${EditQuiz.selectors.elAddNewQuestion}`);
11832 if (!elAddNewQuestion) {
11833 return;
11834 }
11835 const elBtnAddQuestion = elAddNewQuestion.querySelector(`${EditQuiz.selectors.elBtnAddQuestion}`);
11836 if (!elBtnAddQuestion) {
11837 return;
11838 }
11839 const elQuestionTitleInput = elAddNewQuestion.querySelector(`${EditQuiz.selectors.elQuestionTitleNewInput}`);
11840 const elQuestionTypeNew = elAddNewQuestion.querySelector(`${EditQuiz.selectors.elQuestionTypeNew}`);
11841 const questionTitle = elQuestionTitleInput.value.trim();
11842 const questionType = elQuestionTypeNew.value;
11843 if (questionTitle && questionType) {
11844 elBtnAddQuestion.classList.add('active');
11845 } else {
11846 elBtnAddQuestion.classList.remove('active');
11847 }
11848 }
11849 removeQuestion(args) {
11850 const {
11851 e,
11852 target
11853 } = args;
11854 const elBtnRemoveQuestion = target.closest(`${EditQuiz.selectors.elBtnRemoveQuestion}`);
11855 if (!elBtnRemoveQuestion) {
11856 return;
11857 }
11858 const elQuestionItem = elBtnRemoveQuestion.closest(`${EditQuiz.selectors.elQuestionItem}`);
11859 if (!elQuestionItem) {
11860 return;
11861 }
11862 const questionId = elQuestionItem.dataset.questionId;
11863 sweetalert2__WEBPACK_IMPORTED_MODULE_1___default().fire({
11864 title: elBtnRemoveQuestion.dataset.title,
11865 text: elBtnRemoveQuestion.dataset.content,
11866 icon: 'warning',
11867 showCloseButton: true,
11868 showCancelButton: true,
11869 cancelButtonText: lpDataAdmin.i18n.cancel,
11870 confirmButtonText: lpDataAdmin.i18n.yes,
11871 reverseButtons: true
11872 }).then(result => {
11873 if (result.isConfirmed) {
11874 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItem, 1);
11875 const callBack = {
11876 success: response => {
11877 const {
11878 message,
11879 status
11880 } = response;
11881 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(message, status);
11882 if (status === 'success') {
11883 elQuestionItem.remove();
11884 this.updateCountItems();
11885 }
11886 },
11887 error: error => {
11888 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(error, 'error');
11889 },
11890 completed: () => {
11891 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItem, 0);
11892 }
11893 };
11894 const dataSend = {
11895 quiz_id: this.quizID,
11896 action: 'remove_question_from_quiz',
11897 question_id: questionId,
11898 args: {
11899 id_url: this.idUrlHandle
11900 }
11901 };
11902 window.lpAJAXG.fetchAJAX(dataSend, callBack);
11903 }
11904 });
11905 }
11906 updateQuestionTitle(args) {
11907 const {
11908 e,
11909 target
11910 } = args;
11911 let canHandle = false;
11912 if (target.closest(`${EditQuiz.selectors.elBtnUpdateQuestionTitle}`)) {
11913 canHandle = true;
11914 } else if (target.closest(`${EditQuiz.selectors.elQuestionTitleInput}`) && e.key === 'Enter') {
11915 canHandle = true;
11916 }
11917 if (!canHandle) {
11918 return;
11919 }
11920 e.preventDefault();
11921 const elQuestionItem = target.closest(`${EditQuiz.selectors.elQuestionItem}`);
11922 if (!elQuestionItem) {
11923 return;
11924 }
11925 const elQuestionTitleInput = elQuestionItem.querySelector(`${EditQuiz.selectors.elQuestionTitleInput}`);
11926 if (!elQuestionTitleInput) {
11927 return;
11928 }
11929 const questionId = elQuestionItem.dataset.questionId;
11930 const questionTitleValue = elQuestionTitleInput.value.trim();
11931 const titleOld = elQuestionTitleInput.dataset.old;
11932 const message = elQuestionTitleInput.dataset.messEmptyTitle;
11933 if (questionTitleValue.length === 0) {
11934 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(message, 'error');
11935 return;
11936 }
11937 if (questionTitleValue === titleOld) {
11938 return;
11939 }
11940 elQuestionTitleInput.blur();
11941 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItem, 1);
11942 const callBack = {
11943 success: response => {
11944 const {
11945 message,
11946 status
11947 } = response;
11948 if (status === 'success') {
11949 elQuestionTitleInput.dataset.old = questionTitleValue;
11950 } else {
11951 elQuestionTitleInput.value = titleOld;
11952 }
11953 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(message, status);
11954 },
11955 error: error => {
11956 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(error, 'error');
11957 },
11958 completed: () => {
11959 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItem, 0);
11960 elQuestionItem.classList.remove('editing');
11961 }
11962 };
11963 const dataSend = {
11964 quiz_id: this.quizID,
11965 action: 'update_question',
11966 question_id: questionId,
11967 question_title: questionTitleValue,
11968 args: {
11969 id_url: this.idUrlHandle
11970 }
11971 };
11972 window.lpAJAXG.fetchAJAX(dataSend, callBack);
11973 }
11974 changeTitleQuestion(args) {
11975 const {
11976 e,
11977 target
11978 } = args;
11979 const elQuestionTitleInput = target.closest(`${EditQuiz.selectors.elQuestionTitleInput}`);
11980 if (!elQuestionTitleInput) {
11981 return;
11982 }
11983 const elQuestionItem = elQuestionTitleInput.closest(`${EditQuiz.selectors.elQuestionItem}`);
11984 const titleValue = elQuestionTitleInput.value.trim();
11985 const titleValueOld = elQuestionTitleInput.dataset.old || '';
11986 if (titleValue === titleValueOld) {
11987 elQuestionItem.classList.remove('editing');
11988 } else {
11989 elQuestionItem.classList.add('editing');
11990 }
11991 }
11992 cancelChangeTitleQuestion(args) {
11993 const {
11994 e,
11995 target
11996 } = args;
11997 const elBtnCancelUpdateQuestionTitle = target.closest(`${EditQuiz.selectors.elBtnCancelUpdateQuestionTitle}`);
11998 if (!elBtnCancelUpdateQuestionTitle) {
11999 return;
12000 }
12001 const elQuestionItem = elBtnCancelUpdateQuestionTitle.closest(`${EditQuiz.selectors.elQuestionItem}`);
12002 const elQuestionTitleInput = elQuestionItem.querySelector(`${EditQuiz.selectors.elQuestionTitleInput}`);
12003 elQuestionTitleInput.value = elQuestionTitleInput.dataset.old || '';
12004 elQuestionItem.classList.remove('editing');
12005 }
12006 sortAbleQuestion() {
12007 let isUpdateSectionPosition = 0;
12008 let timeout;
12009 new sortablejs__WEBPACK_IMPORTED_MODULE_2__["default"](this.elEditListQuestions, {
12010 handle: '.drag',
12011 animation: 150,
12012 onEnd: evt => {
12013 const elQuestionItem = evt.item;
12014 if (!isUpdateSectionPosition) {
12015 return;
12016 }
12017 clearTimeout(timeout);
12018 timeout = setTimeout(() => {
12019 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItem, 1);
12020 const questionIds = [];
12021 const elQuestionItems = this.elEditListQuestions.querySelectorAll(`${EditQuiz.selectors.elQuestionItem}:not(.clone)`);
12022 elQuestionItems.forEach(elItem => {
12023 const questionId = elItem.dataset.questionId;
12024 if (questionId) {
12025 questionIds.push(questionId);
12026 }
12027 });
12028 const callBack = {
12029 success: response => {
12030 const {
12031 message,
12032 status
12033 } = response;
12034 if (status === 'success') {
12035 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(message, status);
12036 editQuestion.initTinyMCE();
12037 } else {
12038 throw `Error: ${message}`;
12039 }
12040 },
12041 error: error => {
12042 lpAssetsJsPath_lpToastify_js__WEBPACK_IMPORTED_MODULE_3__.show(error, 'error');
12043 },
12044 completed: () => {
12045 _utils_js__WEBPACK_IMPORTED_MODULE_0__.lpSetLoadingEl(elQuestionItem, 0);
12046 isUpdateSectionPosition = 0;
12047 }
12048 };
12049 const dataSend = {
12050 quiz_id: this.quizID,
12051 action: 'update_questions_position',
12052 question_ids: questionIds,
12053 args: {
12054 id_url: this.idUrlHandle
12055 }
12056 };
12057 window.lpAJAXG.fetchAJAX(dataSend, callBack);
12058 }, 1000);
12059 },
12060 onMove: () => {
12061 clearTimeout(timeout);
12062 },
12063 onUpdate: () => {
12064 isUpdateSectionPosition = 1;
12065 }
12066 });
12067 }
12068 }
12069 const editQuiz = new EditQuiz();
12070 editQuiz.init();
12071 })();
12072
12073 /******/ })()
12074 ;
12075 //# sourceMappingURL=edit-quiz.js.map