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-09-03 提交的版本,查看 最新版本

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

QingJ © 2025

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