ChatGPT 阅读模式

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

目前为 2024-01-13 提交的版本。查看 最新版本

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