ChatGPT 页面摘要按钮

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

当前为 2024-03-10 提交的版本,查看 最新版本

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