chatgpt-page-summary-button

🍓 let ChatGPT summary the web page you are reading in one click

目前為 2023-10-31 提交的版本,檢視 最新版本

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