ChatGPT 页面摘要按钮

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

安装此脚本?
作者推荐脚本

您可能也喜欢ChatGPT 自动继续 🔄

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

QingJ © 2025

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