Greasy Fork 支持简体中文。

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-16 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/472956/1448924/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.0.1
  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`
  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. //#region serialization
  536. /** Serializes the data using the optional this.encodeData() and returns it as a string */
  537. serializeData(data, useEncoding = true) {
  538. return __async(this, null, function* () {
  539. const stringData = JSON.stringify(data);
  540. if (!this.encodingEnabled() || !useEncoding)
  541. return stringData;
  542. const encRes = this.encodeData(stringData);
  543. if (encRes instanceof Promise)
  544. return yield encRes;
  545. return encRes;
  546. });
  547. }
  548. /** Deserializes the data using the optional this.decodeData() and returns it as a JSON object */
  549. deserializeData(data, useEncoding = true) {
  550. return __async(this, null, function* () {
  551. let decRes = this.encodingEnabled() && useEncoding ? this.decodeData(data) : void 0;
  552. if (decRes instanceof Promise)
  553. decRes = yield decRes;
  554. return JSON.parse(decRes != null ? decRes : data);
  555. });
  556. }
  557. //#region misc
  558. /** Copies a JSON-compatible object and loses all its internal references in the process */
  559. deepCopy(obj) {
  560. return JSON.parse(JSON.stringify(obj));
  561. }
  562. //#region storage
  563. /** Gets a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  564. getValue(name, defaultValue) {
  565. return __async(this, null, function* () {
  566. var _a, _b;
  567. switch (this.storageMethod) {
  568. case "localStorage":
  569. return (_a = localStorage.getItem(name)) != null ? _a : defaultValue;
  570. case "sessionStorage":
  571. return (_b = sessionStorage.getItem(name)) != null ? _b : defaultValue;
  572. default:
  573. return GM.getValue(name, defaultValue);
  574. }
  575. });
  576. }
  577. /**
  578. * Sets a value in persistent storage - can be overwritten in a subclass if you want to use something other than GM storage.
  579. * The default storage engines will stringify all passed values like numbers or booleans, so be aware of that.
  580. */
  581. setValue(name, value) {
  582. return __async(this, null, function* () {
  583. switch (this.storageMethod) {
  584. case "localStorage":
  585. return localStorage.setItem(name, String(value));
  586. case "sessionStorage":
  587. return sessionStorage.setItem(name, String(value));
  588. default:
  589. return GM.setValue(name, String(value));
  590. }
  591. });
  592. }
  593. /** Deletes a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  594. deleteValue(name) {
  595. return __async(this, null, function* () {
  596. switch (this.storageMethod) {
  597. case "localStorage":
  598. return localStorage.removeItem(name);
  599. case "sessionStorage":
  600. return sessionStorage.removeItem(name);
  601. default:
  602. return GM.deleteValue(name);
  603. }
  604. });
  605. }
  606. };
  607.  
  608. // lib/DataStoreSerializer.ts
  609. var DataStoreSerializer = class {
  610. constructor(stores, options = {}) {
  611. __publicField(this, "stores");
  612. __publicField(this, "options");
  613. if (!getUnsafeWindow().crypto || !getUnsafeWindow().crypto.subtle)
  614. throw new Error("DataStoreSerializer has to run in a secure context (HTTPS)!");
  615. this.stores = stores;
  616. this.options = __spreadValues({
  617. addChecksum: true,
  618. ensureIntegrity: true
  619. }, options);
  620. }
  621. /** Calculates the checksum of a string */
  622. calcChecksum(input) {
  623. return __async(this, null, function* () {
  624. return computeHash(input, "SHA-256");
  625. });
  626. }
  627. /** Serializes a DataStore instance */
  628. serializeStore(storeInst) {
  629. return __async(this, null, function* () {
  630. const data = storeInst.encodingEnabled() ? yield storeInst.encodeData(JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
  631. const checksum = this.options.addChecksum ? yield this.calcChecksum(data) : void 0;
  632. return {
  633. id: storeInst.id,
  634. data,
  635. formatVersion: storeInst.formatVersion,
  636. encoded: storeInst.encodingEnabled(),
  637. checksum
  638. };
  639. });
  640. }
  641. /** Serializes the data stores into a string */
  642. serialize() {
  643. return __async(this, null, function* () {
  644. const serData = [];
  645. for (const store of this.stores)
  646. serData.push(yield this.serializeStore(store));
  647. return JSON.stringify(serData);
  648. });
  649. }
  650. /**
  651. * Deserializes the data exported via {@linkcode serialize()} and imports it into the DataStore instances.
  652. * Also triggers the migration process if the data format has changed.
  653. */
  654. deserialize(serializedData) {
  655. return __async(this, null, function* () {
  656. const deserStores = JSON.parse(serializedData);
  657. for (const storeData of deserStores) {
  658. const storeInst = this.stores.find((s) => s.id === storeData.id);
  659. if (!storeInst)
  660. throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
  661. if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
  662. const checksum = yield this.calcChecksum(storeData.data);
  663. if (checksum !== storeData.checksum)
  664. throw new Error(`Checksum mismatch for DataStore with ID "${storeData.id}"!
  665. Expected: ${storeData.checksum}
  666. Has: ${checksum}`);
  667. }
  668. const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData(storeData.data) : storeData.data;
  669. if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
  670. yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
  671. else
  672. yield storeInst.setData(JSON.parse(decodedData));
  673. }
  674. });
  675. }
  676. };
  677.  
  678. // node_modules/nanoevents/index.js
  679. var createNanoEvents = () => ({
  680. emit(event, ...args) {
  681. for (let i = 0, callbacks = this.events[event] || [], length = callbacks.length; i < length; i++) {
  682. callbacks[i](...args);
  683. }
  684. },
  685. events: {},
  686. on(event, cb) {
  687. var _a;
  688. ((_a = this.events)[event] || (_a[event] = [])).push(cb);
  689. return () => {
  690. var _a2;
  691. this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
  692. };
  693. }
  694. });
  695.  
  696. // lib/NanoEmitter.ts
  697. var NanoEmitter = class {
  698. constructor(options = {}) {
  699. __publicField(this, "events", createNanoEvents());
  700. __publicField(this, "eventUnsubscribes", []);
  701. __publicField(this, "emitterOptions");
  702. this.emitterOptions = __spreadValues({
  703. publicEmit: false
  704. }, options);
  705. }
  706. /** Subscribes to an event - returns a function that unsubscribes the event listener */
  707. on(event, cb) {
  708. let unsub;
  709. const unsubProxy = () => {
  710. if (!unsub)
  711. return;
  712. unsub();
  713. this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
  714. };
  715. unsub = this.events.on(event, cb);
  716. this.eventUnsubscribes.push(unsub);
  717. return unsubProxy;
  718. }
  719. /** Subscribes to an event and calls the callback or resolves the Promise only once */
  720. once(event, cb) {
  721. return new Promise((resolve) => {
  722. let unsub;
  723. const onceProxy = (...args) => {
  724. unsub();
  725. cb == null ? void 0 : cb(...args);
  726. resolve(args);
  727. };
  728. unsub = this.on(event, onceProxy);
  729. });
  730. }
  731. /** Emits an event on this instance - Needs `publicEmit` to be set to true in the constructor! */
  732. emit(event, ...args) {
  733. if (this.emitterOptions.publicEmit) {
  734. this.events.emit(event, ...args);
  735. return true;
  736. }
  737. return false;
  738. }
  739. /** Unsubscribes all event listeners */
  740. unsubscribeAll() {
  741. for (const unsub of this.eventUnsubscribes)
  742. unsub();
  743. this.eventUnsubscribes = [];
  744. }
  745. };
  746.  
  747. // lib/Dialog.ts
  748. var defaultDialogCss = `.uu-no-select {
  749. user-select: none;
  750. }
  751.  
  752. .uu-dialog-bg {
  753. --uu-dialog-bg: #333333;
  754. --uu-dialog-bg-highlight: #252525;
  755. --uu-scroll-indicator-bg: rgba(10, 10, 10, 0.7);
  756. --uu-dialog-separator-color: #797979;
  757. --uu-dialog-border-radius: 10px;
  758. }
  759.  
  760. .uu-dialog-bg {
  761. display: block;
  762. position: fixed;
  763. width: 100%;
  764. height: 100%;
  765. top: 0;
  766. left: 0;
  767. z-index: 5;
  768. background-color: rgba(0, 0, 0, 0.6);
  769. }
  770.  
  771. .uu-dialog {
  772. --uu-calc-dialog-height: calc(min(100vh - 40px, var(--uu-dialog-height-max)));
  773. position: absolute;
  774. display: flex;
  775. flex-direction: column;
  776. width: calc(min(100% - 60px, var(--uu-dialog-width-max)));
  777. border-radius: var(--uu-dialog-border-radius);
  778. height: auto;
  779. max-height: var(--uu-calc-dialog-height);
  780. left: 50%;
  781. top: 50%;
  782. transform: translate(-50%, -50%);
  783. z-index: 6;
  784. color: #fff;
  785. background-color: var(--uu-dialog-bg);
  786. }
  787.  
  788. .uu-dialog.align-top {
  789. top: 0;
  790. transform: translate(-50%, 40px);
  791. }
  792.  
  793. .uu-dialog.align-bottom {
  794. top: 100%;
  795. transform: translate(-50%, -100%);
  796. }
  797.  
  798. .uu-dialog-body {
  799. font-size: 1.5rem;
  800. padding: 20px;
  801. }
  802.  
  803. .uu-dialog-body.small {
  804. padding: 15px;
  805. }
  806.  
  807. #uu-dialog-opts {
  808. display: flex;
  809. flex-direction: column;
  810. position: relative;
  811. padding: 30px 0px;
  812. overflow-y: auto;
  813. }
  814.  
  815. .uu-dialog-header {
  816. display: flex;
  817. justify-content: space-between;
  818. align-items: center;
  819. margin-bottom: 6px;
  820. padding: 15px 20px 15px 20px;
  821. background-color: var(--uu-dialog-bg);
  822. border: 2px solid var(--uu-dialog-separator-color);
  823. border-style: none none solid none !important;
  824. border-radius: var(--uu-dialog-border-radius) var(--uu-dialog-border-radius) 0px 0px;
  825. }
  826.  
  827. .uu-dialog-header.small {
  828. padding: 10px 15px;
  829. border-style: none none solid none !important;
  830. }
  831.  
  832. .uu-dialog-header-pad {
  833. content: " ";
  834. min-height: 32px;
  835. }
  836.  
  837. .uu-dialog-header-pad.small {
  838. min-height: 24px;
  839. }
  840.  
  841. .uu-dialog-titlecont {
  842. display: flex;
  843. align-items: center;
  844. }
  845.  
  846. .uu-dialog-titlecont-no-title {
  847. display: flex;
  848. justify-content: flex-end;
  849. align-items: center;
  850. }
  851.  
  852. .uu-dialog-title {
  853. position: relative;
  854. display: inline-block;
  855. font-size: 22px;
  856. }
  857.  
  858. .uu-dialog-close {
  859. cursor: pointer;
  860. }
  861.  
  862. .uu-dialog-header-img,
  863. .uu-dialog-close
  864. {
  865. width: 32px;
  866. height: 32px;
  867. }
  868.  
  869. .uu-dialog-header-img.small,
  870. .uu-dialog-close.small
  871. {
  872. width: 24px;
  873. height: 24px;
  874. }
  875.  
  876. .uu-dialog-footer {
  877. font-size: 17px;
  878. text-decoration: underline;
  879. }
  880.  
  881. .uu-dialog-footer.hidden {
  882. display: none;
  883. }
  884.  
  885. .uu-dialog-footer-cont {
  886. margin-top: 6px;
  887. padding: 15px 20px;
  888. background: var(--uu-dialog-bg);
  889. background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--uu-dialog-bg) 30%, var(--uu-dialog-bg) 100%);
  890. border: 2px solid var(--uu-dialog-separator-color);
  891. border-style: solid none none none !important;
  892. border-radius: 0px 0px var(--uu-dialog-border-radius) var(--uu-dialog-border-radius);
  893. }
  894.  
  895. .uu-dialog-footer-buttons-cont button:not(:last-of-type) {
  896. margin-right: 15px;
  897. }`;
  898. exports.currentDialogId = null;
  899. var openDialogs = [];
  900. var defaultStrings = {
  901. closeDialogTooltip: "Click to close the dialog"
  902. };
  903. var Dialog = class _Dialog extends NanoEmitter {
  904. constructor(options) {
  905. super();
  906. /** Options passed to the dialog in the constructor */
  907. __publicField(this, "options");
  908. /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
  909. __publicField(this, "id");
  910. /** Strings used in the dialog (used for translations) */
  911. __publicField(this, "strings");
  912. __publicField(this, "dialogOpen", false);
  913. __publicField(this, "dialogMounted", false);
  914. const _a = options, { strings } = _a, opts = __objRest(_a, ["strings"]);
  915. this.strings = __spreadValues(__spreadValues({}, defaultStrings), strings != null ? strings : {});
  916. this.options = __spreadValues({
  917. closeOnBgClick: true,
  918. closeOnEscPress: true,
  919. destroyOnClose: false,
  920. unmountOnClose: true,
  921. removeListenersOnDestroy: true,
  922. small: false,
  923. verticalAlign: "center"
  924. }, opts);
  925. this.id = opts.id;
  926. }
  927. //#region public
  928. /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
  929. mount() {
  930. return __async(this, null, function* () {
  931. var _a;
  932. if (this.dialogMounted)
  933. return;
  934. this.dialogMounted = true;
  935. if (!document.querySelector("style.uu-dialog-css"))
  936. addGlobalStyle((_a = this.options.dialogCss) != null ? _a : defaultDialogCss).classList.add("uu-dialog-css");
  937. const bgElem = document.createElement("div");
  938. bgElem.id = `uu-${this.id}-dialog-bg`;
  939. bgElem.classList.add("uu-dialog-bg");
  940. if (this.options.closeOnBgClick)
  941. bgElem.ariaLabel = bgElem.title = this.getString("closeDialogTooltip");
  942. bgElem.style.setProperty("--uu-dialog-width-max", `${this.options.width}px`);
  943. bgElem.style.setProperty("--uu-dialog-height-max", `${this.options.height}px`);
  944. bgElem.style.visibility = "hidden";
  945. bgElem.style.display = "none";
  946. bgElem.inert = true;
  947. bgElem.appendChild(yield this.getDialogContent());
  948. document.body.appendChild(bgElem);
  949. this.attachListeners(bgElem);
  950. this.events.emit("render");
  951. return bgElem;
  952. });
  953. }
  954. /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
  955. unmount() {
  956. var _a;
  957. this.close();
  958. this.dialogMounted = false;
  959. const clearSelectors = [
  960. `#uu-${this.id}-dialog-bg`,
  961. `#uu-style-dialog-${this.id}`
  962. ];
  963. for (const sel of clearSelectors)
  964. (_a = document.querySelector(sel)) == null ? void 0 : _a.remove();
  965. this.events.emit("clear");
  966. }
  967. /** Clears the DOM of the dialog and then renders it again */
  968. remount() {
  969. return __async(this, null, function* () {
  970. this.unmount();
  971. yield this.mount();
  972. });
  973. }
  974. /**
  975. * Opens the dialog - also mounts it if it hasn't been mounted yet
  976. * Prevents default action and immediate propagation of the passed event
  977. */
  978. open(e) {
  979. return __async(this, null, function* () {
  980. var _a;
  981. e == null ? void 0 : e.preventDefault();
  982. e == null ? void 0 : e.stopImmediatePropagation();
  983. if (this.isOpen())
  984. return;
  985. this.dialogOpen = true;
  986. if (openDialogs.includes(this.id))
  987. throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
  988. if (!this.isMounted())
  989. yield this.mount();
  990. const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
  991. if (!dialogBg)
  992. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  993. dialogBg.style.visibility = "visible";
  994. dialogBg.style.display = "block";
  995. dialogBg.inert = false;
  996. exports.currentDialogId = this.id;
  997. openDialogs.unshift(this.id);
  998. for (const dialogId of openDialogs)
  999. if (dialogId !== this.id)
  1000. (_a = document.querySelector(`#uu-${dialogId}-dialog-bg`)) == null ? void 0 : _a.setAttribute("inert", "true");
  1001. document.body.classList.remove("uu-no-select");
  1002. document.body.setAttribute("inert", "true");
  1003. this.events.emit("open");
  1004. return dialogBg;
  1005. });
  1006. }
  1007. /** Closes the dialog - prevents default action and immediate propagation of the passed event */
  1008. close(e) {
  1009. var _a, _b;
  1010. e == null ? void 0 : e.preventDefault();
  1011. e == null ? void 0 : e.stopImmediatePropagation();
  1012. if (!this.isOpen())
  1013. return;
  1014. this.dialogOpen = false;
  1015. const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
  1016. if (!dialogBg)
  1017. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  1018. dialogBg.style.visibility = "hidden";
  1019. dialogBg.style.display = "none";
  1020. dialogBg.inert = true;
  1021. openDialogs.splice(openDialogs.indexOf(this.id), 1);
  1022. exports.currentDialogId = (_a = openDialogs[0]) != null ? _a : null;
  1023. if (exports.currentDialogId)
  1024. (_b = document.querySelector(`#uu-${exports.currentDialogId}-dialog-bg`)) == null ? void 0 : _b.removeAttribute("inert");
  1025. if (openDialogs.length === 0) {
  1026. document.body.classList.add("uu-no-select");
  1027. document.body.removeAttribute("inert");
  1028. }
  1029. this.events.emit("close");
  1030. if (this.options.destroyOnClose)
  1031. this.destroy();
  1032. else if (this.options.unmountOnClose)
  1033. this.unmount();
  1034. }
  1035. /** Returns true if the dialog is currently open */
  1036. isOpen() {
  1037. return this.dialogOpen;
  1038. }
  1039. /** Returns true if the dialog is currently mounted */
  1040. isMounted() {
  1041. return this.dialogMounted;
  1042. }
  1043. /** Clears the DOM of the dialog and removes all event listeners */
  1044. destroy() {
  1045. this.unmount();
  1046. this.events.emit("destroy");
  1047. this.options.removeListenersOnDestroy && this.unsubscribeAll();
  1048. }
  1049. //#region static
  1050. /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
  1051. static getCurrentDialogId() {
  1052. return exports.currentDialogId;
  1053. }
  1054. /** Returns the IDs of all currently open dialogs, top-most first */
  1055. static getOpenDialogs() {
  1056. return openDialogs;
  1057. }
  1058. //#region protected
  1059. getString(key) {
  1060. var _a;
  1061. return (_a = this.strings[key]) != null ? _a : defaultStrings[key];
  1062. }
  1063. /** Called once to attach all generic event listeners */
  1064. attachListeners(bgElem) {
  1065. if (this.options.closeOnBgClick) {
  1066. bgElem.addEventListener("click", (e) => {
  1067. var _a;
  1068. if (this.isOpen() && ((_a = e.target) == null ? void 0 : _a.id) === `uu-${this.id}-dialog-bg`)
  1069. this.close(e);
  1070. });
  1071. }
  1072. if (this.options.closeOnEscPress) {
  1073. document.body.addEventListener("keydown", (e) => {
  1074. if (e.key === "Escape" && this.isOpen() && _Dialog.getCurrentDialogId() === this.id)
  1075. this.close(e);
  1076. });
  1077. }
  1078. }
  1079. //#region protected
  1080. /**
  1081. * Adds generic, accessible interaction listeners to the passed element.
  1082. * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
  1083. * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
  1084. */
  1085. onInteraction(elem, listener, listenerOptions) {
  1086. const _a = listenerOptions != null ? listenerOptions : {}, { preventDefault = true, stopPropagation = true } = _a, listenerOpts = __objRest(_a, ["preventDefault", "stopPropagation"]);
  1087. const interactionKeys = ["Enter", " ", "Space"];
  1088. const proxListener = (e) => {
  1089. if (e instanceof KeyboardEvent) {
  1090. if (interactionKeys.includes(e.key)) {
  1091. preventDefault && e.preventDefault();
  1092. stopPropagation && e.stopPropagation();
  1093. } else
  1094. return;
  1095. } else if (e instanceof MouseEvent) {
  1096. preventDefault && e.preventDefault();
  1097. stopPropagation && e.stopPropagation();
  1098. }
  1099. (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
  1100. (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
  1101. listener(e);
  1102. };
  1103. elem.addEventListener("click", proxListener, listenerOpts);
  1104. elem.addEventListener("keydown", proxListener, listenerOpts);
  1105. }
  1106. /** Returns the dialog content element and all its children */
  1107. getDialogContent() {
  1108. return __async(this, null, function* () {
  1109. var _a, _b, _c, _d;
  1110. const header = (_b = (_a = this.options).renderHeader) == null ? void 0 : _b.call(_a);
  1111. const footer = (_d = (_c = this.options).renderFooter) == null ? void 0 : _d.call(_c);
  1112. const dialogWrapperEl = document.createElement("div");
  1113. dialogWrapperEl.id = `uu-${this.id}-dialog`;
  1114. dialogWrapperEl.classList.add("uu-dialog");
  1115. dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
  1116. dialogWrapperEl.role = "dialog";
  1117. dialogWrapperEl.setAttribute("aria-labelledby", `uu-${this.id}-dialog-title`);
  1118. dialogWrapperEl.setAttribute("aria-describedby", `uu-${this.id}-dialog-body`);
  1119. if (this.options.verticalAlign !== "center")
  1120. dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
  1121. const headerWrapperEl = document.createElement("div");
  1122. headerWrapperEl.classList.add("uu-dialog-header");
  1123. this.options.small && headerWrapperEl.classList.add("small");
  1124. if (header) {
  1125. const headerTitleWrapperEl = document.createElement("div");
  1126. headerTitleWrapperEl.id = `uu-${this.id}-dialog-title`;
  1127. headerTitleWrapperEl.classList.add("uu-dialog-title-wrapper");
  1128. headerTitleWrapperEl.role = "heading";
  1129. headerTitleWrapperEl.ariaLevel = "1";
  1130. headerTitleWrapperEl.appendChild(header instanceof Promise ? yield header : header);
  1131. headerWrapperEl.appendChild(headerTitleWrapperEl);
  1132. } else {
  1133. const padEl = document.createElement("div");
  1134. padEl.classList.add("uu-dialog-header-pad", this.options.small ? "small" : "");
  1135. headerWrapperEl.appendChild(padEl);
  1136. }
  1137. if (this.options.renderCloseBtn) {
  1138. const closeBtnEl = yield this.options.renderCloseBtn();
  1139. closeBtnEl.classList.add("uu-dialog-close");
  1140. this.options.small && closeBtnEl.classList.add("small");
  1141. closeBtnEl.tabIndex = 0;
  1142. if (closeBtnEl.hasAttribute("alt"))
  1143. closeBtnEl.setAttribute("alt", this.getString("closeDialogTooltip"));
  1144. closeBtnEl.title = closeBtnEl.ariaLabel = this.getString("closeDialogTooltip");
  1145. this.onInteraction(closeBtnEl, () => this.close());
  1146. headerWrapperEl.appendChild(closeBtnEl);
  1147. }
  1148. dialogWrapperEl.appendChild(headerWrapperEl);
  1149. const dialogBodyElem = document.createElement("div");
  1150. dialogBodyElem.id = `uu-${this.id}-dialog-body`;
  1151. dialogBodyElem.classList.add("uu-dialog-body");
  1152. this.options.small && dialogBodyElem.classList.add("small");
  1153. const body = this.options.renderBody();
  1154. dialogBodyElem.appendChild(body instanceof Promise ? yield body : body);
  1155. dialogWrapperEl.appendChild(dialogBodyElem);
  1156. if (footer) {
  1157. const footerWrapper = document.createElement("div");
  1158. footerWrapper.classList.add("uu-dialog-footer-cont");
  1159. dialogWrapperEl.appendChild(footerWrapper);
  1160. footerWrapper.appendChild(footer instanceof Promise ? yield footer : footer);
  1161. }
  1162. return dialogWrapperEl;
  1163. });
  1164. }
  1165. };
  1166.  
  1167. // lib/misc.ts
  1168. function autoPlural(word, num) {
  1169. if (Array.isArray(num) || num instanceof NodeList)
  1170. num = num.length;
  1171. return `${word}${num === 1 ? "" : "s"}`;
  1172. }
  1173. function insertValues(input, ...values) {
  1174. return input.replace(/%\d/gm, (match) => {
  1175. var _a, _b;
  1176. const argIndex = Number(match.substring(1)) - 1;
  1177. return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
  1178. });
  1179. }
  1180. function pauseFor(time) {
  1181. return new Promise((res) => {
  1182. setTimeout(() => res(), time);
  1183. });
  1184. }
  1185. function debounce(func, timeout = 300, edge = "falling") {
  1186. let timer;
  1187. return function(...args) {
  1188. if (edge === "rising") {
  1189. if (!timer) {
  1190. func.apply(this, args);
  1191. timer = setTimeout(() => timer = void 0, timeout);
  1192. }
  1193. } else {
  1194. clearTimeout(timer);
  1195. timer = setTimeout(() => func.apply(this, args), timeout);
  1196. }
  1197. };
  1198. }
  1199. function fetchAdvanced(_0) {
  1200. return __async(this, arguments, function* (input, options = {}) {
  1201. const { timeout = 1e4 } = options;
  1202. let signalOpts = {}, id = void 0;
  1203. if (timeout >= 0) {
  1204. const controller = new AbortController();
  1205. id = setTimeout(() => controller.abort(), timeout);
  1206. signalOpts = { signal: controller.signal };
  1207. }
  1208. try {
  1209. const res = yield fetch(input, __spreadValues(__spreadValues({}, options), signalOpts));
  1210. id && clearTimeout(id);
  1211. return res;
  1212. } catch (err) {
  1213. id && clearTimeout(id);
  1214. throw err;
  1215. }
  1216. });
  1217. }
  1218.  
  1219. // lib/SelectorObserver.ts
  1220. var domLoaded = false;
  1221. document.addEventListener("DOMContentLoaded", () => domLoaded = true);
  1222. var SelectorObserver = class {
  1223. constructor(baseElement, options = {}) {
  1224. __publicField(this, "enabled", false);
  1225. __publicField(this, "baseElement");
  1226. __publicField(this, "observer");
  1227. __publicField(this, "observerOptions");
  1228. __publicField(this, "customOptions");
  1229. __publicField(this, "listenerMap");
  1230. this.baseElement = baseElement;
  1231. this.listenerMap = /* @__PURE__ */ new Map();
  1232. const _a = options, {
  1233. defaultDebounce,
  1234. defaultDebounceEdge,
  1235. disableOnNoListeners,
  1236. enableOnAddListener
  1237. } = _a, observerOptions = __objRest(_a, [
  1238. "defaultDebounce",
  1239. "defaultDebounceEdge",
  1240. "disableOnNoListeners",
  1241. "enableOnAddListener"
  1242. ]);
  1243. this.observerOptions = __spreadValues({
  1244. childList: true,
  1245. subtree: true
  1246. }, observerOptions);
  1247. this.customOptions = {
  1248. defaultDebounce: defaultDebounce != null ? defaultDebounce : 0,
  1249. defaultDebounceEdge: defaultDebounceEdge != null ? defaultDebounceEdge : "rising",
  1250. disableOnNoListeners: disableOnNoListeners != null ? disableOnNoListeners : false,
  1251. enableOnAddListener: enableOnAddListener != null ? enableOnAddListener : true
  1252. };
  1253. if (typeof this.customOptions.checkInterval !== "number") {
  1254. this.observer = new MutationObserver(() => this.checkAllSelectors());
  1255. } else {
  1256. this.checkAllSelectors();
  1257. setInterval(() => this.checkAllSelectors(), this.customOptions.checkInterval);
  1258. }
  1259. }
  1260. /** Call to check all selectors in the {@linkcode listenerMap} using {@linkcode checkSelector()} */
  1261. checkAllSelectors() {
  1262. if (!this.enabled || !domLoaded)
  1263. return;
  1264. for (const [selector, listeners] of this.listenerMap.entries())
  1265. this.checkSelector(selector, listeners);
  1266. }
  1267. /** Checks if the element(s) with the given {@linkcode selector} exist in the DOM and calls the respective {@linkcode listeners} accordingly */
  1268. checkSelector(selector, listeners) {
  1269. var _a;
  1270. if (!this.enabled)
  1271. return;
  1272. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  1273. if (!baseElement)
  1274. return;
  1275. const all = listeners.some((listener) => listener.all);
  1276. const one = listeners.some((listener) => !listener.all);
  1277. const allElements = all ? baseElement.querySelectorAll(selector) : null;
  1278. const oneElement = one ? baseElement.querySelector(selector) : null;
  1279. for (const options of listeners) {
  1280. if (options.all) {
  1281. if (allElements && allElements.length > 0) {
  1282. options.listener(allElements);
  1283. if (!options.continuous)
  1284. this.removeListener(selector, options);
  1285. }
  1286. } else {
  1287. if (oneElement) {
  1288. options.listener(oneElement);
  1289. if (!options.continuous)
  1290. this.removeListener(selector, options);
  1291. }
  1292. }
  1293. if (((_a = this.listenerMap.get(selector)) == null ? void 0 : _a.length) === 0)
  1294. this.listenerMap.delete(selector);
  1295. if (this.listenerMap.size === 0 && this.customOptions.disableOnNoListeners)
  1296. this.disable();
  1297. }
  1298. }
  1299. /**
  1300. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  1301. * @param selector The selector to observe
  1302. * @param options Options for the selector observation
  1303. * @param options.listener Gets called whenever the selector was found in the DOM
  1304. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  1305. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  1306. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  1307. * @returns Returns a function that can be called to remove this listener more easily
  1308. */
  1309. addListener(selector, options) {
  1310. options = __spreadValues({
  1311. all: false,
  1312. continuous: false,
  1313. debounce: 0
  1314. }, options);
  1315. if (options.debounce && options.debounce > 0 || this.customOptions.defaultDebounce && this.customOptions.defaultDebounce > 0) {
  1316. options.listener = debounce(
  1317. options.listener,
  1318. options.debounce || this.customOptions.defaultDebounce,
  1319. options.debounceEdge || this.customOptions.defaultDebounceEdge
  1320. );
  1321. }
  1322. if (this.listenerMap.has(selector))
  1323. this.listenerMap.get(selector).push(options);
  1324. else
  1325. this.listenerMap.set(selector, [options]);
  1326. if (this.enabled === false && this.customOptions.enableOnAddListener)
  1327. this.enable();
  1328. this.checkSelector(selector, [options]);
  1329. return () => this.removeListener(selector, options);
  1330. }
  1331. /** Disables the observation of the child elements */
  1332. disable() {
  1333. var _a;
  1334. if (!this.enabled)
  1335. return;
  1336. this.enabled = false;
  1337. (_a = this.observer) == null ? void 0 : _a.disconnect();
  1338. }
  1339. /**
  1340. * Enables or reenables the observation of the child elements.
  1341. * @param immediatelyCheckSelectors Whether to immediately check if all previously registered selectors exist (default is true)
  1342. * @returns Returns true when the observation was enabled, false otherwise (e.g. when the base element wasn't found)
  1343. */
  1344. enable(immediatelyCheckSelectors = true) {
  1345. var _a;
  1346. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  1347. if (this.enabled || !baseElement)
  1348. return false;
  1349. this.enabled = true;
  1350. (_a = this.observer) == null ? void 0 : _a.observe(baseElement, this.observerOptions);
  1351. if (immediatelyCheckSelectors)
  1352. this.checkAllSelectors();
  1353. return true;
  1354. }
  1355. /** Returns whether the observation of the child elements is currently enabled */
  1356. isEnabled() {
  1357. return this.enabled;
  1358. }
  1359. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  1360. clearListeners() {
  1361. this.listenerMap.clear();
  1362. }
  1363. /**
  1364. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  1365. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  1366. */
  1367. removeAllListeners(selector) {
  1368. return this.listenerMap.delete(selector);
  1369. }
  1370. /**
  1371. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  1372. * @returns Returns true when the listener was found and removed, false otherwise
  1373. */
  1374. removeListener(selector, options) {
  1375. const listeners = this.listenerMap.get(selector);
  1376. if (!listeners)
  1377. return false;
  1378. const index = listeners.indexOf(options);
  1379. if (index > -1) {
  1380. listeners.splice(index, 1);
  1381. return true;
  1382. }
  1383. return false;
  1384. }
  1385. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  1386. getAllListeners() {
  1387. return this.listenerMap;
  1388. }
  1389. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  1390. getListeners(selector) {
  1391. return this.listenerMap.get(selector);
  1392. }
  1393. };
  1394.  
  1395. // lib/translation.ts
  1396. var trans = {};
  1397. var curLang;
  1398. var trLang = (language, key, ...args) => {
  1399. var _a;
  1400. if (!language)
  1401. return key;
  1402. const trText = (_a = trans[language]) == null ? void 0 : _a[key];
  1403. if (!trText)
  1404. return key;
  1405. if (args.length > 0 && trText.match(/%\d/)) {
  1406. return insertValues(trText, ...args);
  1407. }
  1408. return trText;
  1409. };
  1410. function tr(key, ...args) {
  1411. return trLang(curLang, key, ...args);
  1412. }
  1413. tr.forLang = trLang;
  1414. tr.addLanguage = (language, translations) => {
  1415. trans[language] = translations;
  1416. };
  1417. tr.setLanguage = (language) => {
  1418. curLang = language;
  1419. };
  1420. tr.getLanguage = () => {
  1421. return curLang;
  1422. };
  1423. tr.getTranslations = (language) => {
  1424. return trans[language != null ? language : curLang];
  1425. };
  1426.  
  1427. exports.DataStore = DataStore;
  1428. exports.DataStoreSerializer = DataStoreSerializer;
  1429. exports.Dialog = Dialog;
  1430. exports.NanoEmitter = NanoEmitter;
  1431. exports.SelectorObserver = SelectorObserver;
  1432. exports.addGlobalStyle = addGlobalStyle;
  1433. exports.addParent = addParent;
  1434. exports.autoPlural = autoPlural;
  1435. exports.clamp = clamp;
  1436. exports.compress = compress;
  1437. exports.computeHash = computeHash;
  1438. exports.darkenColor = darkenColor;
  1439. exports.debounce = debounce;
  1440. exports.decompress = decompress;
  1441. exports.defaultDialogCss = defaultDialogCss;
  1442. exports.defaultStrings = defaultStrings;
  1443. exports.fetchAdvanced = fetchAdvanced;
  1444. exports.getSiblingsFrame = getSiblingsFrame;
  1445. exports.getUnsafeWindow = getUnsafeWindow;
  1446. exports.hexToRgb = hexToRgb;
  1447. exports.insertValues = insertValues;
  1448. exports.interceptEvent = interceptEvent;
  1449. exports.interceptWindowEvent = interceptWindowEvent;
  1450. exports.isScrollable = isScrollable;
  1451. exports.lightenColor = lightenColor;
  1452. exports.mapRange = mapRange;
  1453. exports.observeElementProp = observeElementProp;
  1454. exports.openDialogs = openDialogs;
  1455. exports.openInNewTab = openInNewTab;
  1456. exports.pauseFor = pauseFor;
  1457. exports.preloadImages = preloadImages;
  1458. exports.randRange = randRange;
  1459. exports.randomId = randomId;
  1460. exports.randomItem = randomItem;
  1461. exports.randomItemIndex = randomItemIndex;
  1462. exports.randomizeArray = randomizeArray;
  1463. exports.rgbToHex = rgbToHex;
  1464. exports.setInnerHtmlUnsafe = setInnerHtmlUnsafe;
  1465. exports.takeRandomItem = takeRandomItem;
  1466. exports.tr = tr;
  1467.  
  1468. return exports;
  1469.  
  1470. })({});