ChatGPT 页面摘要按钮

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

当前为 2024-01-13 提交的版本,查看 最新版本

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