ChatGPT 阅读模式

🍞 显示一个用于阅读的模态框

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

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

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

QingJ © 2025

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