UserUtils

Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and more

当前为 2024-10-24 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/472956/1470784/UserUtils.js

  1. // ==UserScript==
  2. // @namespace https://github.com/Sv443-Network/UserUtils
  3. // @exclude *
  4. // @author Sv443
  5. // @supportURL https://github.com/Sv443-Network/UserUtils/issues
  6. // @homepageURL https://github.com/Sv443-Network/UserUtils
  7.  
  8. // ==UserLibrary==
  9. // @name UserUtils
  10. // @description Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and more
  11. // @version 8.1.0
  12. // @license MIT
  13. // @copyright Sv443 (https://github.com/Sv443)
  14.  
  15. // ==/UserScript==
  16. // ==/UserLibrary==
  17.  
  18. // ==OpenUserJS==
  19. // @author Sv443
  20. // ==/OpenUserJS==
  21.  
  22. var UserUtils = (function (exports) {
  23. var __defProp = Object.defineProperty;
  24. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  25. var __hasOwnProp = Object.prototype.hasOwnProperty;
  26. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  27. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  28. var __spreadValues = (a, b) => {
  29. for (var prop in b || (b = {}))
  30. if (__hasOwnProp.call(b, prop))
  31. __defNormalProp(a, prop, b[prop]);
  32. if (__getOwnPropSymbols)
  33. for (var prop of __getOwnPropSymbols(b)) {
  34. if (__propIsEnum.call(b, prop))
  35. __defNormalProp(a, prop, b[prop]);
  36. }
  37. return a;
  38. };
  39. var __objRest = (source, exclude) => {
  40. var target = {};
  41. for (var prop in source)
  42. if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
  43. target[prop] = source[prop];
  44. if (source != null && __getOwnPropSymbols)
  45. for (var prop of __getOwnPropSymbols(source)) {
  46. if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
  47. target[prop] = source[prop];
  48. }
  49. return target;
  50. };
  51. var __publicField = (obj, key, value) => {
  52. __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  53. return value;
  54. };
  55. var __async = (__this, __arguments, generator) => {
  56. return new Promise((resolve, reject) => {
  57. var fulfilled = (value) => {
  58. try {
  59. step(generator.next(value));
  60. } catch (e) {
  61. reject(e);
  62. }
  63. };
  64. var rejected = (value) => {
  65. try {
  66. step(generator.throw(value));
  67. } catch (e) {
  68. reject(e);
  69. }
  70. };
  71. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  72. step((generator = generator.apply(__this, __arguments)).next());
  73. });
  74. };
  75.  
  76. // lib/math.ts
  77. function clamp(value, min, max) {
  78. return Math.max(Math.min(value, max), min);
  79. }
  80. function mapRange(value, range1min, range1max, range2min, range2max) {
  81. if (Number(range1min) === 0 && Number(range2min) === 0)
  82. return value * (range2max / range1max);
  83. return (value - range1min) * ((range2max - range2min) / (range1max - range1min)) + range2min;
  84. }
  85. function randRange(...args) {
  86. let min, max;
  87. if (typeof args[0] === "number" && typeof args[1] === "number")
  88. [min, max] = args;
  89. else if (typeof args[0] === "number" && typeof args[1] !== "number") {
  90. min = 0;
  91. [max] = args;
  92. } else
  93. throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
  94. min = Number(min);
  95. max = Number(max);
  96. if (isNaN(min) || isNaN(max))
  97. return NaN;
  98. if (min > max)
  99. throw new TypeError(`Parameter "min" can't be bigger than "max"`);
  100. return Math.floor(Math.random() * (max - min + 1)) + min;
  101. }
  102.  
  103. // lib/array.ts
  104. function randomItem(array) {
  105. return randomItemIndex(array)[0];
  106. }
  107. function randomItemIndex(array) {
  108. if (array.length === 0)
  109. return [void 0, void 0];
  110. const idx = randRange(array.length - 1);
  111. return [array[idx], idx];
  112. }
  113. function takeRandomItem(arr) {
  114. const [itm, idx] = randomItemIndex(arr);
  115. if (idx === void 0)
  116. return void 0;
  117. arr.splice(idx, 1);
  118. return itm;
  119. }
  120. function randomizeArray(array) {
  121. const retArray = [...array];
  122. if (array.length === 0)
  123. return retArray;
  124. for (let i = retArray.length - 1; i > 0; i--) {
  125. const j = Math.floor(randRange(0, 1e4) / 1e4 * (i + 1));
  126. [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
  127. }
  128. return retArray;
  129. }
  130.  
  131. // lib/colors.ts
  132. function hexToRgb(hex) {
  133. hex = (hex.startsWith("#") ? hex.slice(1) : hex).trim();
  134. const a = hex.length === 8 || hex.length === 4 ? parseInt(hex.slice(-(hex.length / 4)), 16) / (hex.length === 8 ? 255 : 15) : void 0;
  135. if (!isNaN(Number(a)))
  136. hex = hex.slice(0, -(hex.length / 4));
  137. if (hex.length === 3 || hex.length === 4)
  138. hex = hex.split("").map((c) => c + c).join("");
  139. const bigint = parseInt(hex, 16);
  140. const r = bigint >> 16 & 255;
  141. const g = bigint >> 8 & 255;
  142. const b = bigint & 255;
  143. return [clamp(r, 0, 255), clamp(g, 0, 255), clamp(b, 0, 255), typeof a === "number" ? clamp(a, 0, 1) : void 0];
  144. }
  145. function rgbToHex(red, green, blue, alpha, withHash = true, upperCase = false) {
  146. const toHexVal = (n) => clamp(Math.round(n), 0, 255).toString(16).padStart(2, "0")[upperCase ? "toUpperCase" : "toLowerCase"]();
  147. return `${withHash ? "#" : ""}${toHexVal(red)}${toHexVal(green)}${toHexVal(blue)}${alpha ? toHexVal(alpha * 255) : ""}`;
  148. }
  149. function lightenColor(color, percent, upperCase = false) {
  150. return darkenColor(color, percent * -1, upperCase);
  151. }
  152. function darkenColor(color, percent, upperCase = false) {
  153. var _a;
  154. color = color.trim();
  155. const darkenRgb = (r2, g2, b2, percent2) => {
  156. r2 = Math.max(0, Math.min(255, r2 - r2 * percent2 / 100));
  157. g2 = Math.max(0, Math.min(255, g2 - g2 * percent2 / 100));
  158. b2 = Math.max(0, Math.min(255, b2 - b2 * percent2 / 100));
  159. return [r2, g2, b2];
  160. };
  161. let r, g, b, a;
  162. const isHexCol = color.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);
  163. if (isHexCol)
  164. [r, g, b, a] = hexToRgb(color);
  165. else if (color.startsWith("rgb")) {
  166. const rgbValues = (_a = color.match(/\d+(\.\d+)?/g)) == null ? void 0 : _a.map(Number);
  167. if (!rgbValues)
  168. throw new Error("Invalid RGB/RGBA color format");
  169. [r, g, b, a] = rgbValues;
  170. } else
  171. throw new Error("Unsupported color format");
  172. [r, g, b] = darkenRgb(r, g, b, percent);
  173. if (isHexCol)
  174. return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
  175. else if (color.startsWith("rgba"))
  176. return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
  177. else if (color.startsWith("rgb"))
  178. return `rgb(${r}, ${g}, ${b})`;
  179. else
  180. throw new Error("Unsupported color format");
  181. }
  182.  
  183. // lib/dom.ts
  184. function getUnsafeWindow() {
  185. try {
  186. return unsafeWindow;
  187. } catch (e) {
  188. return window;
  189. }
  190. }
  191. function addParent(element, newParent) {
  192. const oldParent = element.parentNode;
  193. if (!oldParent)
  194. throw new Error("Element doesn't have a parent node");
  195. oldParent.replaceChild(newParent, element);
  196. newParent.appendChild(element);
  197. return newParent;
  198. }
  199. function addGlobalStyle(style) {
  200. const styleElem = document.createElement("style");
  201. setInnerHtmlUnsafe(styleElem, style);
  202. document.head.appendChild(styleElem);
  203. return styleElem;
  204. }
  205. function preloadImages(srcUrls, rejects = false) {
  206. const promises = srcUrls.map((src) => new Promise((res, rej) => {
  207. const image = new Image();
  208. image.src = src;
  209. image.addEventListener("load", () => res(image));
  210. image.addEventListener("error", (evt) => rejects && rej(evt));
  211. }));
  212. return Promise.allSettled(promises);
  213. }
  214. function openInNewTab(href, background) {
  215. try {
  216. GM.openInTab(href, background);
  217. } catch (e) {
  218. const openElem = document.createElement("a");
  219. Object.assign(openElem, {
  220. className: "userutils-open-in-new-tab",
  221. target: "_blank",
  222. rel: "noopener noreferrer",
  223. href
  224. });
  225. openElem.style.display = "none";
  226. document.body.appendChild(openElem);
  227. openElem.click();
  228. setTimeout(openElem.remove, 50);
  229. }
  230. }
  231. function interceptEvent(eventObject, eventName, predicate = () => true) {
  232. Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
  233. if (isNaN(Error.stackTraceLimit))
  234. Error.stackTraceLimit = 100;
  235. (function(original) {
  236. eventObject.__proto__.addEventListener = function(...args) {
  237. var _a, _b;
  238. const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
  239. args[1] = function(...a) {
  240. if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
  241. return;
  242. else
  243. return origListener.apply(this, a);
  244. };
  245. original.apply(this, args);
  246. };
  247. })(eventObject.__proto__.addEventListener);
  248. }
  249. function interceptWindowEvent(eventName, predicate = () => true) {
  250. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  251. }
  252. function isScrollable(element) {
  253. const { overflowX, overflowY } = getComputedStyle(element);
  254. return {
  255. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  256. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
  257. };
  258. }
  259. function observeElementProp(element, property, callback) {
  260. const elementPrototype = Object.getPrototypeOf(element);
  261. if (elementPrototype.hasOwnProperty(property)) {
  262. const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
  263. Object.defineProperty(element, property, {
  264. get: function() {
  265. var _a;
  266. return (_a = descriptor == null ? void 0 : descriptor.get) == null ? void 0 : _a.apply(this, arguments);
  267. },
  268. set: function() {
  269. var _a;
  270. const oldValue = this[property];
  271. (_a = descriptor == null ? void 0 : descriptor.set) == null ? void 0 : _a.apply(this, arguments);
  272. const newValue = this[property];
  273. if (typeof callback === "function") {
  274. callback.bind(this, oldValue, newValue);
  275. }
  276. return newValue;
  277. }
  278. });
  279. }
  280. }
  281. function getSiblingsFrame(refElement, siblingAmount, refElementAlignment = "center-top", includeRef = true) {
  282. var _a, _b;
  283. const siblings = [...(_b = (_a = refElement.parentNode) == null ? void 0 : _a.childNodes) != null ? _b : []];
  284. const elemSiblIdx = siblings.indexOf(refElement);
  285. if (elemSiblIdx === -1)
  286. throw new Error("Element doesn't have a parent node");
  287. if (refElementAlignment === "top")
  288. return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
  289. else if (refElementAlignment.startsWith("center-")) {
  290. const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
  291. const startIdx = Math.max(0, elemSiblIdx - halfAmount);
  292. const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
  293. const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
  294. const startIdxWithOffset = startIdx + topOffset + btmOffset;
  295. return [
  296. ...siblings.filter((_, idx) => includeRef || idx !== elemSiblIdx).slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
  297. ];
  298. } else if (refElementAlignment === "bottom")
  299. return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
  300. return [];
  301. }
  302. var ttPolicy;
  303. function setInnerHtmlUnsafe(element, html) {
  304. var _a, _b, _c;
  305. if (!ttPolicy && typeof ((_a = window == null ? void 0 : window.trustedTypes) == null ? void 0 : _a.createPolicy) === "function") {
  306. ttPolicy = window.trustedTypes.createPolicy("_uu_set_innerhtml_unsafe", {
  307. createHTML: (unsafeHtml) => unsafeHtml
  308. });
  309. }
  310. element.innerHTML = (_c = (_b = ttPolicy == null ? void 0 : ttPolicy.createHTML) == null ? void 0 : _b.call(ttPolicy, html)) != null ? _c : html;
  311. return element;
  312. }
  313.  
  314. // lib/crypto.ts
  315. function compress(input, compressionFormat, outputType = "string") {
  316. return __async(this, null, function* () {
  317. const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
  318. const comp = new CompressionStream(compressionFormat);
  319. const writer = comp.writable.getWriter();
  320. writer.write(byteArray);
  321. writer.close();
  322. const buf = yield new Response(comp.readable).arrayBuffer();
  323. return outputType === "arrayBuffer" ? buf : ab2str(buf);
  324. });
  325. }
  326. function decompress(input, compressionFormat, outputType = "string") {
  327. return __async(this, null, function* () {
  328. const byteArray = typeof input === "string" ? str2ab(input) : input;
  329. const decomp = new DecompressionStream(compressionFormat);
  330. const writer = decomp.writable.getWriter();
  331. writer.write(byteArray);
  332. writer.close();
  333. const buf = yield new Response(decomp.readable).arrayBuffer();
  334. return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
  335. });
  336. }
  337. function ab2str(buf) {
  338. return getUnsafeWindow().btoa(
  339. new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
  340. );
  341. }
  342. function str2ab(str) {
  343. return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
  344. }
  345. function computeHash(input, algorithm = "SHA-256") {
  346. return __async(this, null, function* () {
  347. let data;
  348. if (typeof input === "string") {
  349. const encoder = new TextEncoder();
  350. data = encoder.encode(input);
  351. } else
  352. data = input;
  353. const hashBuffer = yield crypto.subtle.digest(algorithm, data);
  354. const hashArray = Array.from(new Uint8Array(hashBuffer));
  355. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
  356. return hashHex;
  357. });
  358. }
  359. function randomId(length = 16, radix = 16, enhancedEntropy = false) {
  360. if (enhancedEntropy) {
  361. const arr = new Uint8Array(length);
  362. crypto.getRandomValues(arr);
  363. return Array.from(
  364. arr,
  365. (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
  366. ).join("");
  367. }
  368. return Array.from(
  369. { length },
  370. () => Math.floor(Math.random() * radix).toString(radix)
  371. ).join("");
  372. }
  373.  
  374. // lib/DataStore.ts
  375. var DataStore = class {
  376. /**
  377. * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
  378. * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
  379. *
  380. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue` if the storageMethod is left as the default of `"GM"`
  381. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultData`
  382. *
  383. * @template TData The type of the data that is saved in persistent storage for the currently set format version (will be automatically inferred from `defaultData` if not provided) - **This has to be a JSON-compatible object!** (no undefined, circular references, etc.)
  384. * @param options The options for this DataStore instance
  385. */
  386. constructor(options) {
  387. __publicField(this, "id");
  388. __publicField(this, "formatVersion");
  389. __publicField(this, "defaultData");
  390. __publicField(this, "encodeData");
  391. __publicField(this, "decodeData");
  392. __publicField(this, "storageMethod");
  393. __publicField(this, "cachedData");
  394. __publicField(this, "migrations");
  395. var _a;
  396. this.id = options.id;
  397. this.formatVersion = options.formatVersion;
  398. this.defaultData = options.defaultData;
  399. this.cachedData = options.defaultData;
  400. this.migrations = options.migrations;
  401. this.storageMethod = (_a = options.storageMethod) != null ? _a : "GM";
  402. this.encodeData = options.encodeData;
  403. this.decodeData = options.decodeData;
  404. }
  405. //#region public
  406. /**
  407. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  408. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  409. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  410. */
  411. loadData() {
  412. return __async(this, null, function* () {
  413. try {
  414. const gmData = yield this.getValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultData));
  415. let gmFmtVer = Number(yield this.getValue(`_uucfgver-${this.id}`, NaN));
  416. if (typeof gmData !== "string") {
  417. yield this.saveDefaultData();
  418. return __spreadValues({}, this.defaultData);
  419. }
  420. const isEncoded = Boolean(yield this.getValue(`_uucfgenc-${this.id}`, false));
  421. let saveData = false;
  422. if (isNaN(gmFmtVer)) {
  423. yield this.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  424. saveData = true;
  425. }
  426. let parsed = yield this.deserializeData(gmData, isEncoded);
  427. if (gmFmtVer < this.formatVersion && this.migrations)
  428. parsed = yield this.runMigrations(parsed, gmFmtVer);
  429. if (saveData)
  430. yield this.setData(parsed);
  431. this.cachedData = __spreadValues({}, parsed);
  432. return this.cachedData;
  433. } catch (err) {
  434. console.warn("Error while parsing JSON data, resetting it to the default value.", err);
  435. yield this.saveDefaultData();
  436. return this.defaultData;
  437. }
  438. });
  439. }
  440. /**
  441. * Returns a copy of the data from the in-memory cache.
  442. * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
  443. * @param deepCopy Whether to return a deep copy of the data (default: `false`) - only necessary if your data object is nested and may have a bigger performance impact if enabled
  444. */
  445. getData(deepCopy = false) {
  446. return deepCopy ? this.deepCopy(this.cachedData) : __spreadValues({}, this.cachedData);
  447. }
  448. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  449. setData(data) {
  450. this.cachedData = data;
  451. const useEncoding = this.encodingEnabled();
  452. return new Promise((resolve) => __async(this, null, function* () {
  453. yield Promise.all([
  454. this.setValue(`_uucfg-${this.id}`, yield this.serializeData(data, useEncoding)),
  455. this.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  456. this.setValue(`_uucfgenc-${this.id}`, useEncoding)
  457. ]);
  458. resolve();
  459. }));
  460. }
  461. /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  462. saveDefaultData() {
  463. return __async(this, null, function* () {
  464. this.cachedData = this.defaultData;
  465. const useEncoding = this.encodingEnabled();
  466. return new Promise((resolve) => __async(this, null, function* () {
  467. yield Promise.all([
  468. this.setValue(`_uucfg-${this.id}`, yield this.serializeData(this.defaultData, useEncoding)),
  469. this.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  470. this.setValue(`_uucfgenc-${this.id}`, useEncoding)
  471. ]);
  472. resolve();
  473. }));
  474. });
  475. }
  476. /**
  477. * Call this method to clear all persistently stored data associated with this DataStore instance.
  478. * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
  479. * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
  480. *
  481. * ⚠️ This requires the additional directive `@grant GM.deleteValue` if the storageMethod is left as the default of `"GM"`
  482. */
  483. deleteData() {
  484. return __async(this, null, function* () {
  485. yield Promise.all([
  486. this.deleteValue(`_uucfg-${this.id}`),
  487. this.deleteValue(`_uucfgver-${this.id}`),
  488. this.deleteValue(`_uucfgenc-${this.id}`)
  489. ]);
  490. });
  491. }
  492. /** Returns whether encoding and decoding are enabled for this DataStore instance */
  493. encodingEnabled() {
  494. return Boolean(this.encodeData && this.decodeData);
  495. }
  496. //#region migrations
  497. /**
  498. * Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
  499. * This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
  500. * Though calling this method manually is not necessary, it can be useful if you want to run migrations for special occasions like a user importing potentially outdated data that has been previously exported.
  501. *
  502. * If one of the migrations fails, the data will be reset to the default value if `resetOnError` is set to `true` (default). Otherwise, an error will be thrown and no data will be saved.
  503. */
  504. runMigrations(oldData, oldFmtVer, resetOnError = true) {
  505. return __async(this, null, function* () {
  506. if (!this.migrations)
  507. return oldData;
  508. let newData = oldData;
  509. const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
  510. let lastFmtVer = oldFmtVer;
  511. for (const [fmtVer, migrationFunc] of sortedMigrations) {
  512. const ver = Number(fmtVer);
  513. if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  514. try {
  515. const migRes = migrationFunc(newData);
  516. newData = migRes instanceof Promise ? yield migRes : migRes;
  517. lastFmtVer = oldFmtVer = ver;
  518. } catch (err) {
  519. if (!resetOnError)
  520. throw new Error(`Error while running migration function for format version '${fmtVer}'`);
  521. console.error(`Error while running migration function for format version '${fmtVer}' - resetting to the default value.`, err);
  522. yield this.saveDefaultData();
  523. return this.getData();
  524. }
  525. }
  526. }
  527. yield Promise.all([
  528. this.setValue(`_uucfg-${this.id}`, yield this.serializeData(newData)),
  529. this.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  530. this.setValue(`_uucfgenc-${this.id}`, this.encodingEnabled())
  531. ]);
  532. return this.cachedData = __spreadValues({}, newData);
  533. });
  534. }
  535. /**
  536. * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
  537. * If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
  538. */
  539. migrateId(oldIds) {
  540. return __async(this, null, function* () {
  541. const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
  542. yield Promise.all(ids.map((id) => __async(this, null, function* () {
  543. const data = yield this.getValue(`_uucfg-${id}`, JSON.stringify(this.defaultData));
  544. const fmtVer = Number(yield this.getValue(`_uucfgver-${id}`, NaN));
  545. const isEncoded = Boolean(yield this.getValue(`_uucfgenc-${id}`, false));
  546. if (data === void 0 || isNaN(fmtVer))
  547. return;
  548. const parsed = yield this.deserializeData(data, isEncoded);
  549. yield Promise.allSettled([
  550. this.setValue(`_uucfg-${this.id}`, yield this.serializeData(parsed)),
  551. this.setValue(`_uucfgver-${this.id}`, fmtVer),
  552. this.setValue(`_uucfgenc-${this.id}`, isEncoded),
  553. this.deleteValue(`_uucfg-${id}`),
  554. this.deleteValue(`_uucfgver-${id}`),
  555. this.deleteValue(`_uucfgenc-${id}`)
  556. ]);
  557. })));
  558. });
  559. }
  560. //#region serialization
  561. /** Serializes the data using the optional this.encodeData() and returns it as a string */
  562. serializeData(data, useEncoding = true) {
  563. return __async(this, null, function* () {
  564. const stringData = JSON.stringify(data);
  565. if (!this.encodingEnabled() || !useEncoding)
  566. return stringData;
  567. const encRes = this.encodeData(stringData);
  568. if (encRes instanceof Promise)
  569. return yield encRes;
  570. return encRes;
  571. });
  572. }
  573. /** Deserializes the data using the optional this.decodeData() and returns it as a JSON object */
  574. deserializeData(data, useEncoding = true) {
  575. return __async(this, null, function* () {
  576. let decRes = this.encodingEnabled() && useEncoding ? this.decodeData(data) : void 0;
  577. if (decRes instanceof Promise)
  578. decRes = yield decRes;
  579. return JSON.parse(decRes != null ? decRes : data);
  580. });
  581. }
  582. //#region misc
  583. /** Copies a JSON-compatible object and loses all its internal references in the process */
  584. deepCopy(obj) {
  585. return JSON.parse(JSON.stringify(obj));
  586. }
  587. //#region storage
  588. /** Gets a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  589. getValue(name, defaultValue) {
  590. return __async(this, null, function* () {
  591. var _a, _b;
  592. switch (this.storageMethod) {
  593. case "localStorage":
  594. return (_a = localStorage.getItem(name)) != null ? _a : defaultValue;
  595. case "sessionStorage":
  596. return (_b = sessionStorage.getItem(name)) != null ? _b : defaultValue;
  597. default:
  598. return GM.getValue(name, defaultValue);
  599. }
  600. });
  601. }
  602. /**
  603. * Sets a value in persistent storage - can be overwritten in a subclass if you want to use something other than GM storage.
  604. * The default storage engines will stringify all passed values like numbers or booleans, so be aware of that.
  605. */
  606. setValue(name, value) {
  607. return __async(this, null, function* () {
  608. switch (this.storageMethod) {
  609. case "localStorage":
  610. return localStorage.setItem(name, String(value));
  611. case "sessionStorage":
  612. return sessionStorage.setItem(name, String(value));
  613. default:
  614. return GM.setValue(name, String(value));
  615. }
  616. });
  617. }
  618. /** Deletes a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  619. deleteValue(name) {
  620. return __async(this, null, function* () {
  621. switch (this.storageMethod) {
  622. case "localStorage":
  623. return localStorage.removeItem(name);
  624. case "sessionStorage":
  625. return sessionStorage.removeItem(name);
  626. default:
  627. return GM.deleteValue(name);
  628. }
  629. });
  630. }
  631. };
  632.  
  633. // lib/DataStoreSerializer.ts
  634. var DataStoreSerializer = class {
  635. constructor(stores, options = {}) {
  636. __publicField(this, "stores");
  637. __publicField(this, "options");
  638. if (!getUnsafeWindow().crypto || !getUnsafeWindow().crypto.subtle)
  639. throw new Error("DataStoreSerializer has to run in a secure context (HTTPS)!");
  640. this.stores = stores;
  641. this.options = __spreadValues({
  642. addChecksum: true,
  643. ensureIntegrity: true
  644. }, options);
  645. }
  646. /** Calculates the checksum of a string */
  647. calcChecksum(input) {
  648. return __async(this, null, function* () {
  649. return computeHash(input, "SHA-256");
  650. });
  651. }
  652. /** Serializes a DataStore instance */
  653. serializeStore(storeInst) {
  654. return __async(this, null, function* () {
  655. const data = storeInst.encodingEnabled() ? yield storeInst.encodeData(JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
  656. const checksum = this.options.addChecksum ? yield this.calcChecksum(data) : void 0;
  657. return {
  658. id: storeInst.id,
  659. data,
  660. formatVersion: storeInst.formatVersion,
  661. encoded: storeInst.encodingEnabled(),
  662. checksum
  663. };
  664. });
  665. }
  666. /** Serializes the data stores into a string */
  667. serialize() {
  668. return __async(this, null, function* () {
  669. const serData = [];
  670. for (const store of this.stores)
  671. serData.push(yield this.serializeStore(store));
  672. return JSON.stringify(serData);
  673. });
  674. }
  675. /**
  676. * Deserializes the data exported via {@linkcode serialize()} and imports it into the DataStore instances.
  677. * Also triggers the migration process if the data format has changed.
  678. */
  679. deserialize(serializedData) {
  680. return __async(this, null, function* () {
  681. const deserStores = JSON.parse(serializedData);
  682. for (const storeData of deserStores) {
  683. const storeInst = this.stores.find((s) => s.id === storeData.id);
  684. if (!storeInst)
  685. throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
  686. if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
  687. const checksum = yield this.calcChecksum(storeData.data);
  688. if (checksum !== storeData.checksum)
  689. throw new Error(`Checksum mismatch for DataStore with ID "${storeData.id}"!
  690. Expected: ${storeData.checksum}
  691. Has: ${checksum}`);
  692. }
  693. const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData(storeData.data) : storeData.data;
  694. if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
  695. yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
  696. else
  697. yield storeInst.setData(JSON.parse(decodedData));
  698. }
  699. });
  700. }
  701. /**
  702. * Loads the persistent data of the DataStore instances into the in-memory cache.
  703. * Also triggers the migration process if the data format has changed.
  704. * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
  705. */
  706. loadStoresData() {
  707. return __async(this, null, function* () {
  708. return Promise.allSettled(this.stores.map(
  709. (store) => __async(this, null, function* () {
  710. return {
  711. id: store.id,
  712. data: yield store.loadData()
  713. };
  714. })
  715. ));
  716. });
  717. }
  718. /** Resets the persistent data of the DataStore instances to their default values. */
  719. resetStoresData() {
  720. return __async(this, null, function* () {
  721. return Promise.allSettled(this.stores.map((store) => store.saveDefaultData()));
  722. });
  723. }
  724. /**
  725. * Deletes the persistent data of the DataStore instances.
  726. * Leaves the in-memory data untouched.
  727. */
  728. deleteStoresData() {
  729. return __async(this, null, function* () {
  730. return Promise.allSettled(this.stores.map((store) => store.deleteData()));
  731. });
  732. }
  733. };
  734.  
  735. // node_modules/nanoevents/index.js
  736. var createNanoEvents = () => ({
  737. emit(event, ...args) {
  738. for (let i = 0, callbacks = this.events[event] || [], length = callbacks.length; i < length; i++) {
  739. callbacks[i](...args);
  740. }
  741. },
  742. events: {},
  743. on(event, cb) {
  744. var _a;
  745. ((_a = this.events)[event] || (_a[event] = [])).push(cb);
  746. return () => {
  747. var _a2;
  748. this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
  749. };
  750. }
  751. });
  752.  
  753. // lib/NanoEmitter.ts
  754. var NanoEmitter = class {
  755. constructor(options = {}) {
  756. __publicField(this, "events", createNanoEvents());
  757. __publicField(this, "eventUnsubscribes", []);
  758. __publicField(this, "emitterOptions");
  759. this.emitterOptions = __spreadValues({
  760. publicEmit: false
  761. }, options);
  762. }
  763. /** Subscribes to an event - returns a function that unsubscribes the event listener */
  764. on(event, cb) {
  765. let unsub;
  766. const unsubProxy = () => {
  767. if (!unsub)
  768. return;
  769. unsub();
  770. this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
  771. };
  772. unsub = this.events.on(event, cb);
  773. this.eventUnsubscribes.push(unsub);
  774. return unsubProxy;
  775. }
  776. /** Subscribes to an event and calls the callback or resolves the Promise only once */
  777. once(event, cb) {
  778. return new Promise((resolve) => {
  779. let unsub;
  780. const onceProxy = (...args) => {
  781. unsub();
  782. cb == null ? void 0 : cb(...args);
  783. resolve(args);
  784. };
  785. unsub = this.on(event, onceProxy);
  786. });
  787. }
  788. /** Emits an event on this instance - Needs `publicEmit` to be set to true in the constructor! */
  789. emit(event, ...args) {
  790. if (this.emitterOptions.publicEmit) {
  791. this.events.emit(event, ...args);
  792. return true;
  793. }
  794. return false;
  795. }
  796. /** Unsubscribes all event listeners */
  797. unsubscribeAll() {
  798. for (const unsub of this.eventUnsubscribes)
  799. unsub();
  800. this.eventUnsubscribes = [];
  801. }
  802. };
  803.  
  804. // lib/Dialog.ts
  805. var defaultDialogCss = `.uu-no-select {
  806. user-select: none;
  807. }
  808.  
  809. .uu-dialog-bg {
  810. --uu-dialog-bg: #333333;
  811. --uu-dialog-bg-highlight: #252525;
  812. --uu-scroll-indicator-bg: rgba(10, 10, 10, 0.7);
  813. --uu-dialog-separator-color: #797979;
  814. --uu-dialog-border-radius: 10px;
  815. }
  816.  
  817. .uu-dialog-bg {
  818. display: block;
  819. position: fixed;
  820. width: 100%;
  821. height: 100%;
  822. top: 0;
  823. left: 0;
  824. z-index: 5;
  825. background-color: rgba(0, 0, 0, 0.6);
  826. }
  827.  
  828. .uu-dialog {
  829. --uu-calc-dialog-height: calc(min(100vh - 40px, var(--uu-dialog-height-max)));
  830. position: absolute;
  831. display: flex;
  832. flex-direction: column;
  833. width: calc(min(100% - 60px, var(--uu-dialog-width-max)));
  834. border-radius: var(--uu-dialog-border-radius);
  835. height: auto;
  836. max-height: var(--uu-calc-dialog-height);
  837. left: 50%;
  838. top: 50%;
  839. transform: translate(-50%, -50%);
  840. z-index: 6;
  841. color: #fff;
  842. background-color: var(--uu-dialog-bg);
  843. }
  844.  
  845. .uu-dialog.align-top {
  846. top: 0;
  847. transform: translate(-50%, 40px);
  848. }
  849.  
  850. .uu-dialog.align-bottom {
  851. top: 100%;
  852. transform: translate(-50%, -100%);
  853. }
  854.  
  855. .uu-dialog-body {
  856. font-size: 1.5rem;
  857. padding: 20px;
  858. }
  859.  
  860. .uu-dialog-body.small {
  861. padding: 15px;
  862. }
  863.  
  864. #uu-dialog-opts {
  865. display: flex;
  866. flex-direction: column;
  867. position: relative;
  868. padding: 30px 0px;
  869. overflow-y: auto;
  870. }
  871.  
  872. .uu-dialog-header {
  873. display: flex;
  874. justify-content: space-between;
  875. align-items: center;
  876. margin-bottom: 6px;
  877. padding: 15px 20px 15px 20px;
  878. background-color: var(--uu-dialog-bg);
  879. border: 2px solid var(--uu-dialog-separator-color);
  880. border-style: none none solid none !important;
  881. border-radius: var(--uu-dialog-border-radius) var(--uu-dialog-border-radius) 0px 0px;
  882. }
  883.  
  884. .uu-dialog-header.small {
  885. padding: 10px 15px;
  886. border-style: none none solid none !important;
  887. }
  888.  
  889. .uu-dialog-header-pad {
  890. content: " ";
  891. min-height: 32px;
  892. }
  893.  
  894. .uu-dialog-header-pad.small {
  895. min-height: 24px;
  896. }
  897.  
  898. .uu-dialog-titlecont {
  899. display: flex;
  900. align-items: center;
  901. }
  902.  
  903. .uu-dialog-titlecont-no-title {
  904. display: flex;
  905. justify-content: flex-end;
  906. align-items: center;
  907. }
  908.  
  909. .uu-dialog-title {
  910. position: relative;
  911. display: inline-block;
  912. font-size: 22px;
  913. }
  914.  
  915. .uu-dialog-close {
  916. cursor: pointer;
  917. }
  918.  
  919. .uu-dialog-header-img,
  920. .uu-dialog-close
  921. {
  922. width: 32px;
  923. height: 32px;
  924. }
  925.  
  926. .uu-dialog-header-img.small,
  927. .uu-dialog-close.small
  928. {
  929. width: 24px;
  930. height: 24px;
  931. }
  932.  
  933. .uu-dialog-footer {
  934. font-size: 17px;
  935. text-decoration: underline;
  936. }
  937.  
  938. .uu-dialog-footer.hidden {
  939. display: none;
  940. }
  941.  
  942. .uu-dialog-footer-cont {
  943. margin-top: 6px;
  944. padding: 15px 20px;
  945. background: var(--uu-dialog-bg);
  946. background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--uu-dialog-bg) 30%, var(--uu-dialog-bg) 100%);
  947. border: 2px solid var(--uu-dialog-separator-color);
  948. border-style: solid none none none !important;
  949. border-radius: 0px 0px var(--uu-dialog-border-radius) var(--uu-dialog-border-radius);
  950. }
  951.  
  952. .uu-dialog-footer-buttons-cont button:not(:last-of-type) {
  953. margin-right: 15px;
  954. }`;
  955. exports.currentDialogId = null;
  956. var openDialogs = [];
  957. var defaultStrings = {
  958. closeDialogTooltip: "Click to close the dialog"
  959. };
  960. var Dialog = class _Dialog extends NanoEmitter {
  961. constructor(options) {
  962. super();
  963. /** Options passed to the dialog in the constructor */
  964. __publicField(this, "options");
  965. /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
  966. __publicField(this, "id");
  967. /** Strings used in the dialog (used for translations) */
  968. __publicField(this, "strings");
  969. __publicField(this, "dialogOpen", false);
  970. __publicField(this, "dialogMounted", false);
  971. const _a = options, { strings } = _a, opts = __objRest(_a, ["strings"]);
  972. this.strings = __spreadValues(__spreadValues({}, defaultStrings), strings != null ? strings : {});
  973. this.options = __spreadValues({
  974. closeOnBgClick: true,
  975. closeOnEscPress: true,
  976. destroyOnClose: false,
  977. unmountOnClose: true,
  978. removeListenersOnDestroy: true,
  979. small: false,
  980. verticalAlign: "center"
  981. }, opts);
  982. this.id = opts.id;
  983. }
  984. //#region public
  985. /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
  986. mount() {
  987. return __async(this, null, function* () {
  988. var _a;
  989. if (this.dialogMounted)
  990. return;
  991. this.dialogMounted = true;
  992. if (!document.querySelector("style.uu-dialog-css"))
  993. addGlobalStyle((_a = this.options.dialogCss) != null ? _a : defaultDialogCss).classList.add("uu-dialog-css");
  994. const bgElem = document.createElement("div");
  995. bgElem.id = `uu-${this.id}-dialog-bg`;
  996. bgElem.classList.add("uu-dialog-bg");
  997. if (this.options.closeOnBgClick)
  998. bgElem.ariaLabel = bgElem.title = this.getString("closeDialogTooltip");
  999. bgElem.style.setProperty("--uu-dialog-width-max", `${this.options.width}px`);
  1000. bgElem.style.setProperty("--uu-dialog-height-max", `${this.options.height}px`);
  1001. bgElem.style.visibility = "hidden";
  1002. bgElem.style.display = "none";
  1003. bgElem.inert = true;
  1004. bgElem.appendChild(yield this.getDialogContent());
  1005. document.body.appendChild(bgElem);
  1006. this.attachListeners(bgElem);
  1007. this.events.emit("render");
  1008. return bgElem;
  1009. });
  1010. }
  1011. /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
  1012. unmount() {
  1013. var _a;
  1014. this.close();
  1015. this.dialogMounted = false;
  1016. const clearSelectors = [
  1017. `#uu-${this.id}-dialog-bg`,
  1018. `#uu-style-dialog-${this.id}`
  1019. ];
  1020. for (const sel of clearSelectors)
  1021. (_a = document.querySelector(sel)) == null ? void 0 : _a.remove();
  1022. this.events.emit("clear");
  1023. }
  1024. /** Clears the DOM of the dialog and then renders it again */
  1025. remount() {
  1026. return __async(this, null, function* () {
  1027. this.unmount();
  1028. yield this.mount();
  1029. });
  1030. }
  1031. /**
  1032. * Opens the dialog - also mounts it if it hasn't been mounted yet
  1033. * Prevents default action and immediate propagation of the passed event
  1034. */
  1035. open(e) {
  1036. return __async(this, null, function* () {
  1037. var _a;
  1038. e == null ? void 0 : e.preventDefault();
  1039. e == null ? void 0 : e.stopImmediatePropagation();
  1040. if (this.isOpen())
  1041. return;
  1042. this.dialogOpen = true;
  1043. if (openDialogs.includes(this.id))
  1044. throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
  1045. if (!this.isMounted())
  1046. yield this.mount();
  1047. const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
  1048. if (!dialogBg)
  1049. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  1050. dialogBg.style.visibility = "visible";
  1051. dialogBg.style.display = "block";
  1052. dialogBg.inert = false;
  1053. exports.currentDialogId = this.id;
  1054. openDialogs.unshift(this.id);
  1055. for (const dialogId of openDialogs)
  1056. if (dialogId !== this.id)
  1057. (_a = document.querySelector(`#uu-${dialogId}-dialog-bg`)) == null ? void 0 : _a.setAttribute("inert", "true");
  1058. document.body.classList.remove("uu-no-select");
  1059. document.body.setAttribute("inert", "true");
  1060. this.events.emit("open");
  1061. return dialogBg;
  1062. });
  1063. }
  1064. /** Closes the dialog - prevents default action and immediate propagation of the passed event */
  1065. close(e) {
  1066. var _a, _b;
  1067. e == null ? void 0 : e.preventDefault();
  1068. e == null ? void 0 : e.stopImmediatePropagation();
  1069. if (!this.isOpen())
  1070. return;
  1071. this.dialogOpen = false;
  1072. const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
  1073. if (!dialogBg)
  1074. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  1075. dialogBg.style.visibility = "hidden";
  1076. dialogBg.style.display = "none";
  1077. dialogBg.inert = true;
  1078. openDialogs.splice(openDialogs.indexOf(this.id), 1);
  1079. exports.currentDialogId = (_a = openDialogs[0]) != null ? _a : null;
  1080. if (exports.currentDialogId)
  1081. (_b = document.querySelector(`#uu-${exports.currentDialogId}-dialog-bg`)) == null ? void 0 : _b.removeAttribute("inert");
  1082. if (openDialogs.length === 0) {
  1083. document.body.classList.add("uu-no-select");
  1084. document.body.removeAttribute("inert");
  1085. }
  1086. this.events.emit("close");
  1087. if (this.options.destroyOnClose)
  1088. this.destroy();
  1089. else if (this.options.unmountOnClose)
  1090. this.unmount();
  1091. }
  1092. /** Returns true if the dialog is currently open */
  1093. isOpen() {
  1094. return this.dialogOpen;
  1095. }
  1096. /** Returns true if the dialog is currently mounted */
  1097. isMounted() {
  1098. return this.dialogMounted;
  1099. }
  1100. /** Clears the DOM of the dialog and removes all event listeners */
  1101. destroy() {
  1102. this.unmount();
  1103. this.events.emit("destroy");
  1104. this.options.removeListenersOnDestroy && this.unsubscribeAll();
  1105. }
  1106. //#region static
  1107. /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
  1108. static getCurrentDialogId() {
  1109. return exports.currentDialogId;
  1110. }
  1111. /** Returns the IDs of all currently open dialogs, top-most first */
  1112. static getOpenDialogs() {
  1113. return openDialogs;
  1114. }
  1115. //#region protected
  1116. getString(key) {
  1117. var _a;
  1118. return (_a = this.strings[key]) != null ? _a : defaultStrings[key];
  1119. }
  1120. /** Called once to attach all generic event listeners */
  1121. attachListeners(bgElem) {
  1122. if (this.options.closeOnBgClick) {
  1123. bgElem.addEventListener("click", (e) => {
  1124. var _a;
  1125. if (this.isOpen() && ((_a = e.target) == null ? void 0 : _a.id) === `uu-${this.id}-dialog-bg`)
  1126. this.close(e);
  1127. });
  1128. }
  1129. if (this.options.closeOnEscPress) {
  1130. document.body.addEventListener("keydown", (e) => {
  1131. if (e.key === "Escape" && this.isOpen() && _Dialog.getCurrentDialogId() === this.id)
  1132. this.close(e);
  1133. });
  1134. }
  1135. }
  1136. //#region protected
  1137. /**
  1138. * Adds generic, accessible interaction listeners to the passed element.
  1139. * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
  1140. * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
  1141. */
  1142. onInteraction(elem, listener, listenerOptions) {
  1143. const _a = listenerOptions != null ? listenerOptions : {}, { preventDefault = true, stopPropagation = true } = _a, listenerOpts = __objRest(_a, ["preventDefault", "stopPropagation"]);
  1144. const interactionKeys = ["Enter", " ", "Space"];
  1145. const proxListener = (e) => {
  1146. if (e instanceof KeyboardEvent) {
  1147. if (interactionKeys.includes(e.key)) {
  1148. preventDefault && e.preventDefault();
  1149. stopPropagation && e.stopPropagation();
  1150. } else
  1151. return;
  1152. } else if (e instanceof MouseEvent) {
  1153. preventDefault && e.preventDefault();
  1154. stopPropagation && e.stopPropagation();
  1155. }
  1156. (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
  1157. (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
  1158. listener(e);
  1159. };
  1160. elem.addEventListener("click", proxListener, listenerOpts);
  1161. elem.addEventListener("keydown", proxListener, listenerOpts);
  1162. }
  1163. /** Returns the dialog content element and all its children */
  1164. getDialogContent() {
  1165. return __async(this, null, function* () {
  1166. var _a, _b, _c, _d;
  1167. const header = (_b = (_a = this.options).renderHeader) == null ? void 0 : _b.call(_a);
  1168. const footer = (_d = (_c = this.options).renderFooter) == null ? void 0 : _d.call(_c);
  1169. const dialogWrapperEl = document.createElement("div");
  1170. dialogWrapperEl.id = `uu-${this.id}-dialog`;
  1171. dialogWrapperEl.classList.add("uu-dialog");
  1172. dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
  1173. dialogWrapperEl.role = "dialog";
  1174. dialogWrapperEl.setAttribute("aria-labelledby", `uu-${this.id}-dialog-title`);
  1175. dialogWrapperEl.setAttribute("aria-describedby", `uu-${this.id}-dialog-body`);
  1176. if (this.options.verticalAlign !== "center")
  1177. dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
  1178. const headerWrapperEl = document.createElement("div");
  1179. headerWrapperEl.classList.add("uu-dialog-header");
  1180. this.options.small && headerWrapperEl.classList.add("small");
  1181. if (header) {
  1182. const headerTitleWrapperEl = document.createElement("div");
  1183. headerTitleWrapperEl.id = `uu-${this.id}-dialog-title`;
  1184. headerTitleWrapperEl.classList.add("uu-dialog-title-wrapper");
  1185. headerTitleWrapperEl.role = "heading";
  1186. headerTitleWrapperEl.ariaLevel = "1";
  1187. headerTitleWrapperEl.appendChild(header instanceof Promise ? yield header : header);
  1188. headerWrapperEl.appendChild(headerTitleWrapperEl);
  1189. } else {
  1190. const padEl = document.createElement("div");
  1191. padEl.classList.add("uu-dialog-header-pad", this.options.small ? "small" : "");
  1192. headerWrapperEl.appendChild(padEl);
  1193. }
  1194. if (this.options.renderCloseBtn) {
  1195. const closeBtnEl = yield this.options.renderCloseBtn();
  1196. closeBtnEl.classList.add("uu-dialog-close");
  1197. this.options.small && closeBtnEl.classList.add("small");
  1198. closeBtnEl.tabIndex = 0;
  1199. if (closeBtnEl.hasAttribute("alt"))
  1200. closeBtnEl.setAttribute("alt", this.getString("closeDialogTooltip"));
  1201. closeBtnEl.title = closeBtnEl.ariaLabel = this.getString("closeDialogTooltip");
  1202. this.onInteraction(closeBtnEl, () => this.close());
  1203. headerWrapperEl.appendChild(closeBtnEl);
  1204. }
  1205. dialogWrapperEl.appendChild(headerWrapperEl);
  1206. const dialogBodyElem = document.createElement("div");
  1207. dialogBodyElem.id = `uu-${this.id}-dialog-body`;
  1208. dialogBodyElem.classList.add("uu-dialog-body");
  1209. this.options.small && dialogBodyElem.classList.add("small");
  1210. const body = this.options.renderBody();
  1211. dialogBodyElem.appendChild(body instanceof Promise ? yield body : body);
  1212. dialogWrapperEl.appendChild(dialogBodyElem);
  1213. if (footer) {
  1214. const footerWrapper = document.createElement("div");
  1215. footerWrapper.classList.add("uu-dialog-footer-cont");
  1216. dialogWrapperEl.appendChild(footerWrapper);
  1217. footerWrapper.appendChild(footer instanceof Promise ? yield footer : footer);
  1218. }
  1219. return dialogWrapperEl;
  1220. });
  1221. }
  1222. };
  1223.  
  1224. // lib/misc.ts
  1225. function autoPlural(word, num) {
  1226. if (Array.isArray(num) || num instanceof NodeList)
  1227. num = num.length;
  1228. return `${word}${num === 1 ? "" : "s"}`;
  1229. }
  1230. function insertValues(input, ...values) {
  1231. return input.replace(/%\d/gm, (match) => {
  1232. var _a, _b;
  1233. const argIndex = Number(match.substring(1)) - 1;
  1234. return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
  1235. });
  1236. }
  1237. function pauseFor(time) {
  1238. return new Promise((res) => {
  1239. setTimeout(() => res(), time);
  1240. });
  1241. }
  1242. function debounce(func, timeout = 300, edge = "falling") {
  1243. let timer;
  1244. return function(...args) {
  1245. if (edge === "rising") {
  1246. if (!timer) {
  1247. func.apply(this, args);
  1248. timer = setTimeout(() => timer = void 0, timeout);
  1249. }
  1250. } else {
  1251. clearTimeout(timer);
  1252. timer = setTimeout(() => func.apply(this, args), timeout);
  1253. }
  1254. };
  1255. }
  1256. function fetchAdvanced(_0) {
  1257. return __async(this, arguments, function* (input, options = {}) {
  1258. const { timeout = 1e4 } = options;
  1259. let signalOpts = {}, id = void 0;
  1260. if (timeout >= 0) {
  1261. const controller = new AbortController();
  1262. id = setTimeout(() => controller.abort(), timeout);
  1263. signalOpts = { signal: controller.signal };
  1264. }
  1265. try {
  1266. const res = yield fetch(input, __spreadValues(__spreadValues({}, options), signalOpts));
  1267. id && clearTimeout(id);
  1268. return res;
  1269. } catch (err) {
  1270. id && clearTimeout(id);
  1271. throw err;
  1272. }
  1273. });
  1274. }
  1275.  
  1276. // lib/SelectorObserver.ts
  1277. var domLoaded = false;
  1278. document.addEventListener("DOMContentLoaded", () => domLoaded = true);
  1279. var SelectorObserver = class {
  1280. constructor(baseElement, options = {}) {
  1281. __publicField(this, "enabled", false);
  1282. __publicField(this, "baseElement");
  1283. __publicField(this, "observer");
  1284. __publicField(this, "observerOptions");
  1285. __publicField(this, "customOptions");
  1286. __publicField(this, "listenerMap");
  1287. this.baseElement = baseElement;
  1288. this.listenerMap = /* @__PURE__ */ new Map();
  1289. const _a = options, {
  1290. defaultDebounce,
  1291. defaultDebounceEdge,
  1292. disableOnNoListeners,
  1293. enableOnAddListener
  1294. } = _a, observerOptions = __objRest(_a, [
  1295. "defaultDebounce",
  1296. "defaultDebounceEdge",
  1297. "disableOnNoListeners",
  1298. "enableOnAddListener"
  1299. ]);
  1300. this.observerOptions = __spreadValues({
  1301. childList: true,
  1302. subtree: true
  1303. }, observerOptions);
  1304. this.customOptions = {
  1305. defaultDebounce: defaultDebounce != null ? defaultDebounce : 0,
  1306. defaultDebounceEdge: defaultDebounceEdge != null ? defaultDebounceEdge : "rising",
  1307. disableOnNoListeners: disableOnNoListeners != null ? disableOnNoListeners : false,
  1308. enableOnAddListener: enableOnAddListener != null ? enableOnAddListener : true
  1309. };
  1310. if (typeof this.customOptions.checkInterval !== "number") {
  1311. this.observer = new MutationObserver(() => this.checkAllSelectors());
  1312. } else {
  1313. this.checkAllSelectors();
  1314. setInterval(() => this.checkAllSelectors(), this.customOptions.checkInterval);
  1315. }
  1316. }
  1317. /** Call to check all selectors in the {@linkcode listenerMap} using {@linkcode checkSelector()} */
  1318. checkAllSelectors() {
  1319. if (!this.enabled || !domLoaded)
  1320. return;
  1321. for (const [selector, listeners] of this.listenerMap.entries())
  1322. this.checkSelector(selector, listeners);
  1323. }
  1324. /** Checks if the element(s) with the given {@linkcode selector} exist in the DOM and calls the respective {@linkcode listeners} accordingly */
  1325. checkSelector(selector, listeners) {
  1326. var _a;
  1327. if (!this.enabled)
  1328. return;
  1329. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  1330. if (!baseElement)
  1331. return;
  1332. const all = listeners.some((listener) => listener.all);
  1333. const one = listeners.some((listener) => !listener.all);
  1334. const allElements = all ? baseElement.querySelectorAll(selector) : null;
  1335. const oneElement = one ? baseElement.querySelector(selector) : null;
  1336. for (const options of listeners) {
  1337. if (options.all) {
  1338. if (allElements && allElements.length > 0) {
  1339. options.listener(allElements);
  1340. if (!options.continuous)
  1341. this.removeListener(selector, options);
  1342. }
  1343. } else {
  1344. if (oneElement) {
  1345. options.listener(oneElement);
  1346. if (!options.continuous)
  1347. this.removeListener(selector, options);
  1348. }
  1349. }
  1350. if (((_a = this.listenerMap.get(selector)) == null ? void 0 : _a.length) === 0)
  1351. this.listenerMap.delete(selector);
  1352. if (this.listenerMap.size === 0 && this.customOptions.disableOnNoListeners)
  1353. this.disable();
  1354. }
  1355. }
  1356. /**
  1357. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  1358. * @param selector The selector to observe
  1359. * @param options Options for the selector observation
  1360. * @param options.listener Gets called whenever the selector was found in the DOM
  1361. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  1362. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  1363. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  1364. * @returns Returns a function that can be called to remove this listener more easily
  1365. */
  1366. addListener(selector, options) {
  1367. options = __spreadValues({
  1368. all: false,
  1369. continuous: false,
  1370. debounce: 0
  1371. }, options);
  1372. if (options.debounce && options.debounce > 0 || this.customOptions.defaultDebounce && this.customOptions.defaultDebounce > 0) {
  1373. options.listener = debounce(
  1374. options.listener,
  1375. options.debounce || this.customOptions.defaultDebounce,
  1376. options.debounceEdge || this.customOptions.defaultDebounceEdge
  1377. );
  1378. }
  1379. if (this.listenerMap.has(selector))
  1380. this.listenerMap.get(selector).push(options);
  1381. else
  1382. this.listenerMap.set(selector, [options]);
  1383. if (this.enabled === false && this.customOptions.enableOnAddListener)
  1384. this.enable();
  1385. this.checkSelector(selector, [options]);
  1386. return () => this.removeListener(selector, options);
  1387. }
  1388. /** Disables the observation of the child elements */
  1389. disable() {
  1390. var _a;
  1391. if (!this.enabled)
  1392. return;
  1393. this.enabled = false;
  1394. (_a = this.observer) == null ? void 0 : _a.disconnect();
  1395. }
  1396. /**
  1397. * Enables or reenables the observation of the child elements.
  1398. * @param immediatelyCheckSelectors Whether to immediately check if all previously registered selectors exist (default is true)
  1399. * @returns Returns true when the observation was enabled, false otherwise (e.g. when the base element wasn't found)
  1400. */
  1401. enable(immediatelyCheckSelectors = true) {
  1402. var _a;
  1403. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  1404. if (this.enabled || !baseElement)
  1405. return false;
  1406. this.enabled = true;
  1407. (_a = this.observer) == null ? void 0 : _a.observe(baseElement, this.observerOptions);
  1408. if (immediatelyCheckSelectors)
  1409. this.checkAllSelectors();
  1410. return true;
  1411. }
  1412. /** Returns whether the observation of the child elements is currently enabled */
  1413. isEnabled() {
  1414. return this.enabled;
  1415. }
  1416. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  1417. clearListeners() {
  1418. this.listenerMap.clear();
  1419. }
  1420. /**
  1421. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  1422. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  1423. */
  1424. removeAllListeners(selector) {
  1425. return this.listenerMap.delete(selector);
  1426. }
  1427. /**
  1428. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  1429. * @returns Returns true when the listener was found and removed, false otherwise
  1430. */
  1431. removeListener(selector, options) {
  1432. const listeners = this.listenerMap.get(selector);
  1433. if (!listeners)
  1434. return false;
  1435. const index = listeners.indexOf(options);
  1436. if (index > -1) {
  1437. listeners.splice(index, 1);
  1438. return true;
  1439. }
  1440. return false;
  1441. }
  1442. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  1443. getAllListeners() {
  1444. return this.listenerMap;
  1445. }
  1446. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  1447. getListeners(selector) {
  1448. return this.listenerMap.get(selector);
  1449. }
  1450. };
  1451.  
  1452. // lib/translation.ts
  1453. var trans = {};
  1454. var curLang;
  1455. var trLang = (language, key, ...args) => {
  1456. var _a;
  1457. if (!language)
  1458. return key;
  1459. const trText = (_a = trans[language]) == null ? void 0 : _a[key];
  1460. if (!trText)
  1461. return key;
  1462. if (args.length > 0 && trText.match(/%\d/)) {
  1463. return insertValues(trText, ...args);
  1464. }
  1465. return trText;
  1466. };
  1467. function tr(key, ...args) {
  1468. return trLang(curLang, key, ...args);
  1469. }
  1470. tr.forLang = trLang;
  1471. tr.addLanguage = (language, translations) => {
  1472. trans[language] = translations;
  1473. };
  1474. tr.setLanguage = (language) => {
  1475. curLang = language;
  1476. };
  1477. tr.getLanguage = () => {
  1478. return curLang;
  1479. };
  1480. tr.getTranslations = (language) => {
  1481. return trans[language != null ? language : curLang];
  1482. };
  1483.  
  1484. exports.DataStore = DataStore;
  1485. exports.DataStoreSerializer = DataStoreSerializer;
  1486. exports.Dialog = Dialog;
  1487. exports.NanoEmitter = NanoEmitter;
  1488. exports.SelectorObserver = SelectorObserver;
  1489. exports.addGlobalStyle = addGlobalStyle;
  1490. exports.addParent = addParent;
  1491. exports.autoPlural = autoPlural;
  1492. exports.clamp = clamp;
  1493. exports.compress = compress;
  1494. exports.computeHash = computeHash;
  1495. exports.darkenColor = darkenColor;
  1496. exports.debounce = debounce;
  1497. exports.decompress = decompress;
  1498. exports.defaultDialogCss = defaultDialogCss;
  1499. exports.defaultStrings = defaultStrings;
  1500. exports.fetchAdvanced = fetchAdvanced;
  1501. exports.getSiblingsFrame = getSiblingsFrame;
  1502. exports.getUnsafeWindow = getUnsafeWindow;
  1503. exports.hexToRgb = hexToRgb;
  1504. exports.insertValues = insertValues;
  1505. exports.interceptEvent = interceptEvent;
  1506. exports.interceptWindowEvent = interceptWindowEvent;
  1507. exports.isScrollable = isScrollable;
  1508. exports.lightenColor = lightenColor;
  1509. exports.mapRange = mapRange;
  1510. exports.observeElementProp = observeElementProp;
  1511. exports.openDialogs = openDialogs;
  1512. exports.openInNewTab = openInNewTab;
  1513. exports.pauseFor = pauseFor;
  1514. exports.preloadImages = preloadImages;
  1515. exports.randRange = randRange;
  1516. exports.randomId = randomId;
  1517. exports.randomItem = randomItem;
  1518. exports.randomItemIndex = randomItemIndex;
  1519. exports.randomizeArray = randomizeArray;
  1520. exports.rgbToHex = rgbToHex;
  1521. exports.setInnerHtmlUnsafe = setInnerHtmlUnsafe;
  1522. exports.takeRandomItem = takeRandomItem;
  1523. exports.tr = tr;
  1524.  
  1525. return exports;
  1526.  
  1527. })({});