ChatGPT 页面摘要按钮

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

当前为 2023-11-17 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址