ChatGPT 页面翻译按钮

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

当前为 2023-10-29 提交的版本,查看 最新版本

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