ChatGPT 页面摘要按钮

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

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

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