UserUtils

Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, manage persistent user configurations, modify the DOM more easily and more

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/472956/1348514/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, manage persistent user configurations, modify the DOM more easily and more
  11. // @version 6.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. function randomId(length = 16, radix = 16) {
  103. const arr = new Uint8Array(length);
  104. crypto.getRandomValues(arr);
  105. return Array.from(
  106. arr,
  107. (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
  108. ).join("");
  109. }
  110.  
  111. // lib/array.ts
  112. function randomItem(array) {
  113. return randomItemIndex(array)[0];
  114. }
  115. function randomItemIndex(array) {
  116. if (array.length === 0)
  117. return [void 0, void 0];
  118. const idx = randRange(array.length - 1);
  119. return [array[idx], idx];
  120. }
  121. function takeRandomItem(arr) {
  122. const [itm, idx] = randomItemIndex(arr);
  123. if (idx === void 0)
  124. return void 0;
  125. arr.splice(idx, 1);
  126. return itm;
  127. }
  128. function randomizeArray(array) {
  129. const retArray = [...array];
  130. if (array.length === 0)
  131. return retArray;
  132. for (let i = retArray.length - 1; i > 0; i--) {
  133. const j = Math.floor(randRange(0, 1e4) / 1e4 * (i + 1));
  134. [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
  135. }
  136. return retArray;
  137. }
  138.  
  139. // lib/DataStore.ts
  140. var DataStore = class {
  141. /**
  142. * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
  143. * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
  144. *
  145. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  146. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultData`
  147. *
  148. * @template TData The type of the data that is saved in persistent storage (will be automatically inferred from `options.defaultData`) - this should also be the type of the data format associated with the current `options.formatVersion`
  149. * @param options The options for this DataStore instance
  150. */
  151. constructor(options) {
  152. __publicField(this, "id");
  153. __publicField(this, "formatVersion");
  154. __publicField(this, "defaultData");
  155. __publicField(this, "cachedData");
  156. __publicField(this, "migrations");
  157. __publicField(this, "encodeData");
  158. __publicField(this, "decodeData");
  159. this.id = options.id;
  160. this.formatVersion = options.formatVersion;
  161. this.defaultData = options.defaultData;
  162. this.cachedData = options.defaultData;
  163. this.migrations = options.migrations;
  164. this.encodeData = options.encodeData;
  165. this.decodeData = options.decodeData;
  166. }
  167. /**
  168. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  169. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  170. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  171. */
  172. loadData() {
  173. return __async(this, null, function* () {
  174. try {
  175. const gmData = yield GM.getValue(`_uucfg-${this.id}`, this.defaultData);
  176. let gmFmtVer = Number(yield GM.getValue(`_uucfgver-${this.id}`));
  177. if (typeof gmData !== "string") {
  178. yield this.saveDefaultData();
  179. return __spreadValues({}, this.defaultData);
  180. }
  181. const isEncoded = yield GM.getValue(`_uucfgenc-${this.id}`, false);
  182. if (isNaN(gmFmtVer))
  183. yield GM.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  184. let parsed = yield this.deserializeData(gmData, isEncoded);
  185. if (gmFmtVer < this.formatVersion && this.migrations)
  186. parsed = yield this.runMigrations(parsed, gmFmtVer);
  187. return __spreadValues({}, this.cachedData = parsed);
  188. } catch (err) {
  189. console.warn("Error while parsing JSON data, resetting it to the default value.", err);
  190. yield this.saveDefaultData();
  191. return this.defaultData;
  192. }
  193. });
  194. }
  195. /**
  196. * Returns a copy of the data from the in-memory cache.
  197. * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
  198. */
  199. getData() {
  200. return this.deepCopy(this.cachedData);
  201. }
  202. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  203. setData(data) {
  204. this.cachedData = data;
  205. const useEncoding = Boolean(this.encodeData && this.decodeData);
  206. return new Promise((resolve) => __async(this, null, function* () {
  207. yield Promise.all([
  208. GM.setValue(`_uucfg-${this.id}`, yield this.serializeData(data, useEncoding)),
  209. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  210. GM.setValue(`_uucfgenc-${this.id}`, useEncoding)
  211. ]);
  212. resolve();
  213. }));
  214. }
  215. /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  216. saveDefaultData() {
  217. return __async(this, null, function* () {
  218. this.cachedData = this.defaultData;
  219. const useEncoding = Boolean(this.encodeData && this.decodeData);
  220. return new Promise((resolve) => __async(this, null, function* () {
  221. yield Promise.all([
  222. GM.setValue(`_uucfg-${this.id}`, yield this.serializeData(this.defaultData, useEncoding)),
  223. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  224. GM.setValue(`_uucfgenc-${this.id}`, useEncoding)
  225. ]);
  226. resolve();
  227. }));
  228. });
  229. }
  230. /**
  231. * Call this method to clear all persistently stored data associated with this DataStore instance.
  232. * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
  233. * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
  234. *
  235. * ⚠️ This requires the additional directive `@grant GM.deleteValue`
  236. */
  237. deleteData() {
  238. return __async(this, null, function* () {
  239. yield Promise.all([
  240. GM.deleteValue(`_uucfg-${this.id}`),
  241. GM.deleteValue(`_uucfgver-${this.id}`),
  242. GM.deleteValue(`_uucfgenc-${this.id}`)
  243. ]);
  244. });
  245. }
  246. /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
  247. runMigrations(oldData, oldFmtVer) {
  248. return __async(this, null, function* () {
  249. if (!this.migrations)
  250. return oldData;
  251. let newData = oldData;
  252. const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
  253. let lastFmtVer = oldFmtVer;
  254. for (const [fmtVer, migrationFunc] of sortedMigrations) {
  255. const ver = Number(fmtVer);
  256. if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  257. try {
  258. const migRes = migrationFunc(newData);
  259. newData = migRes instanceof Promise ? yield migRes : migRes;
  260. lastFmtVer = oldFmtVer = ver;
  261. } catch (err) {
  262. console.error(`Error while running migration function for format version '${fmtVer}' - resetting to the default value.`, err);
  263. yield this.saveDefaultData();
  264. return this.getData();
  265. }
  266. }
  267. }
  268. yield Promise.all([
  269. GM.setValue(`_uucfg-${this.id}`, yield this.serializeData(newData)),
  270. GM.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  271. GM.setValue(`_uucfgenc-${this.id}`, Boolean(this.encodeData && this.decodeData))
  272. ]);
  273. return newData;
  274. });
  275. }
  276. /** Serializes the data using the optional this.encodeData() and returns it as a string */
  277. serializeData(data, useEncoding = true) {
  278. return __async(this, null, function* () {
  279. const stringData = JSON.stringify(data);
  280. if (!this.encodeData || !this.decodeData || !useEncoding)
  281. return stringData;
  282. const encRes = this.encodeData(stringData);
  283. if (encRes instanceof Promise)
  284. return yield encRes;
  285. return encRes;
  286. });
  287. }
  288. /** Deserializes the data using the optional this.decodeData() and returns it as a JSON object */
  289. deserializeData(data, useEncoding = true) {
  290. return __async(this, null, function* () {
  291. let decRes = this.decodeData && this.encodeData && useEncoding ? this.decodeData(data) : void 0;
  292. if (decRes instanceof Promise)
  293. decRes = yield decRes;
  294. return JSON.parse(decRes != null ? decRes : data);
  295. });
  296. }
  297. /** Copies a JSON-compatible object and loses its internal references */
  298. deepCopy(obj) {
  299. return JSON.parse(JSON.stringify(obj));
  300. }
  301. };
  302.  
  303. // lib/dom.ts
  304. function getUnsafeWindow() {
  305. try {
  306. return unsafeWindow;
  307. } catch (e) {
  308. return window;
  309. }
  310. }
  311. function insertAfter(beforeElement, afterElement) {
  312. var _a;
  313. (_a = beforeElement.parentNode) == null ? void 0 : _a.insertBefore(afterElement, beforeElement.nextSibling);
  314. return afterElement;
  315. }
  316. function addParent(element, newParent) {
  317. const oldParent = element.parentNode;
  318. if (!oldParent)
  319. throw new Error("Element doesn't have a parent node");
  320. oldParent.replaceChild(newParent, element);
  321. newParent.appendChild(element);
  322. return newParent;
  323. }
  324. function addGlobalStyle(style) {
  325. const styleElem = document.createElement("style");
  326. styleElem.innerHTML = style;
  327. document.head.appendChild(styleElem);
  328. return styleElem;
  329. }
  330. function preloadImages(srcUrls, rejects = false) {
  331. const promises = srcUrls.map((src) => new Promise((res, rej) => {
  332. const image = new Image();
  333. image.src = src;
  334. image.addEventListener("load", () => res(image));
  335. image.addEventListener("error", (evt) => rejects && rej(evt));
  336. }));
  337. return Promise.allSettled(promises);
  338. }
  339. function openInNewTab(href) {
  340. const openElem = document.createElement("a");
  341. Object.assign(openElem, {
  342. className: "userutils-open-in-new-tab",
  343. target: "_blank",
  344. rel: "noopener noreferrer",
  345. href
  346. });
  347. openElem.style.display = "none";
  348. document.body.appendChild(openElem);
  349. openElem.click();
  350. setTimeout(openElem.remove, 50);
  351. }
  352. function interceptEvent(eventObject, eventName, predicate = () => true) {
  353. Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
  354. if (isNaN(Error.stackTraceLimit))
  355. Error.stackTraceLimit = 100;
  356. (function(original) {
  357. eventObject.__proto__.addEventListener = function(...args) {
  358. var _a, _b;
  359. const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
  360. args[1] = function(...a) {
  361. if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
  362. return;
  363. else
  364. return origListener.apply(this, a);
  365. };
  366. original.apply(this, args);
  367. };
  368. })(eventObject.__proto__.addEventListener);
  369. }
  370. function interceptWindowEvent(eventName, predicate = () => true) {
  371. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  372. }
  373. function isScrollable(element) {
  374. const { overflowX, overflowY } = getComputedStyle(element);
  375. return {
  376. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  377. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
  378. };
  379. }
  380. function observeElementProp(element, property, callback) {
  381. const elementPrototype = Object.getPrototypeOf(element);
  382. if (elementPrototype.hasOwnProperty(property)) {
  383. const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
  384. Object.defineProperty(element, property, {
  385. get: function() {
  386. var _a;
  387. return (_a = descriptor == null ? void 0 : descriptor.get) == null ? void 0 : _a.apply(this, arguments);
  388. },
  389. set: function() {
  390. var _a;
  391. const oldValue = this[property];
  392. (_a = descriptor == null ? void 0 : descriptor.set) == null ? void 0 : _a.apply(this, arguments);
  393. const newValue = this[property];
  394. if (typeof callback === "function") {
  395. callback.bind(this, oldValue, newValue);
  396. }
  397. return newValue;
  398. }
  399. });
  400. }
  401. }
  402. function getSiblingsFrame(refElement, siblingAmount, refElementAlignment = "center-top", includeRef = true) {
  403. var _a, _b;
  404. const siblings = [...(_b = (_a = refElement.parentNode) == null ? void 0 : _a.childNodes) != null ? _b : []];
  405. const elemSiblIdx = siblings.indexOf(refElement);
  406. if (elemSiblIdx === -1)
  407. throw new Error("Element doesn't have a parent node");
  408. if (refElementAlignment === "top")
  409. return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
  410. else if (refElementAlignment.startsWith("center-")) {
  411. const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
  412. const startIdx = Math.max(0, elemSiblIdx - halfAmount);
  413. const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
  414. const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
  415. const startIdxWithOffset = startIdx + topOffset + btmOffset;
  416. return [
  417. ...siblings.filter((_, idx) => includeRef || idx !== elemSiblIdx).slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
  418. ];
  419. } else if (refElementAlignment === "bottom")
  420. return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
  421. return [];
  422. }
  423.  
  424. // lib/misc.ts
  425. function autoPlural(word, num) {
  426. if (Array.isArray(num) || num instanceof NodeList)
  427. num = num.length;
  428. return `${word}${num === 1 ? "" : "s"}`;
  429. }
  430. function pauseFor(time) {
  431. return new Promise((res) => {
  432. setTimeout(() => res(), time);
  433. });
  434. }
  435. function debounce(func, timeout = 300) {
  436. let timer;
  437. return function(...args) {
  438. clearTimeout(timer);
  439. timer = setTimeout(() => func.apply(this, args), timeout);
  440. };
  441. }
  442. function fetchAdvanced(_0) {
  443. return __async(this, arguments, function* (input, options = {}) {
  444. const { timeout = 1e4 } = options;
  445. let signalOpts = {}, id = void 0;
  446. if (timeout >= 0) {
  447. const controller = new AbortController();
  448. id = setTimeout(() => controller.abort(), timeout);
  449. signalOpts = { signal: controller.signal };
  450. }
  451. const res = yield fetch(input, __spreadValues(__spreadValues({}, options), signalOpts));
  452. clearTimeout(id);
  453. return res;
  454. });
  455. }
  456. function insertValues(input, ...values) {
  457. return input.replace(/%\d/gm, (match) => {
  458. var _a, _b;
  459. const argIndex = Number(match.substring(1)) - 1;
  460. return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
  461. });
  462. }
  463. function compress(input, compressionFormat, outputType = "string") {
  464. return __async(this, null, function* () {
  465. const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
  466. const comp = new CompressionStream(compressionFormat);
  467. const writer = comp.writable.getWriter();
  468. writer.write(byteArray);
  469. writer.close();
  470. const buf = yield new Response(comp.readable).arrayBuffer();
  471. return outputType === "arrayBuffer" ? buf : ab2str(buf);
  472. });
  473. }
  474. function decompress(input, compressionFormat, outputType = "string") {
  475. return __async(this, null, function* () {
  476. const byteArray = typeof input === "string" ? str2ab(input) : input;
  477. const decomp = new DecompressionStream(compressionFormat);
  478. const writer = decomp.writable.getWriter();
  479. writer.write(byteArray);
  480. writer.close();
  481. const buf = yield new Response(decomp.readable).arrayBuffer();
  482. return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
  483. });
  484. }
  485. function ab2str(buf) {
  486. return getUnsafeWindow().btoa(
  487. new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
  488. );
  489. }
  490. function str2ab(str) {
  491. return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
  492. }
  493.  
  494. // lib/SelectorObserver.ts
  495. var SelectorObserver = class {
  496. constructor(baseElement, options = {}) {
  497. __publicField(this, "enabled", false);
  498. __publicField(this, "baseElement");
  499. __publicField(this, "observer");
  500. __publicField(this, "observerOptions");
  501. __publicField(this, "customOptions");
  502. __publicField(this, "listenerMap");
  503. this.baseElement = baseElement;
  504. this.listenerMap = /* @__PURE__ */ new Map();
  505. this.observer = new MutationObserver(() => this.checkAllSelectors());
  506. const _a = options, {
  507. defaultDebounce,
  508. disableOnNoListeners,
  509. enableOnAddListener
  510. } = _a, observerOptions = __objRest(_a, [
  511. "defaultDebounce",
  512. "disableOnNoListeners",
  513. "enableOnAddListener"
  514. ]);
  515. this.observerOptions = __spreadValues({
  516. childList: true,
  517. subtree: true
  518. }, observerOptions);
  519. this.customOptions = {
  520. defaultDebounce: defaultDebounce != null ? defaultDebounce : 0,
  521. disableOnNoListeners: disableOnNoListeners != null ? disableOnNoListeners : false,
  522. enableOnAddListener: enableOnAddListener != null ? enableOnAddListener : true
  523. };
  524. }
  525. checkAllSelectors() {
  526. for (const [selector, listeners] of this.listenerMap.entries())
  527. this.checkSelector(selector, listeners);
  528. }
  529. checkSelector(selector, listeners) {
  530. var _a;
  531. if (!this.enabled)
  532. return;
  533. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  534. if (!baseElement)
  535. return;
  536. const all = listeners.some((listener) => listener.all);
  537. const one = listeners.some((listener) => !listener.all);
  538. const allElements = all ? baseElement.querySelectorAll(selector) : null;
  539. const oneElement = one ? baseElement.querySelector(selector) : null;
  540. for (const options of listeners) {
  541. if (options.all) {
  542. if (allElements && allElements.length > 0) {
  543. options.listener(allElements);
  544. if (!options.continuous)
  545. this.removeListener(selector, options);
  546. }
  547. } else {
  548. if (oneElement) {
  549. options.listener(oneElement);
  550. if (!options.continuous)
  551. this.removeListener(selector, options);
  552. }
  553. }
  554. if (((_a = this.listenerMap.get(selector)) == null ? void 0 : _a.length) === 0)
  555. this.listenerMap.delete(selector);
  556. if (this.listenerMap.size === 0 && this.customOptions.disableOnNoListeners)
  557. this.disable();
  558. }
  559. }
  560. debounce(func, time) {
  561. let timeout;
  562. return function(...args) {
  563. clearTimeout(timeout);
  564. timeout = setTimeout(() => func.apply(this, args), time);
  565. };
  566. }
  567. /**
  568. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  569. * @param selector The selector to observe
  570. * @param options Options for the selector observation
  571. * @param options.listener Gets called whenever the selector was found in the DOM
  572. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  573. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  574. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  575. */
  576. addListener(selector, options) {
  577. options = __spreadValues({ all: false, continuous: false, debounce: 0 }, options);
  578. if (options.debounce && options.debounce > 0 || this.customOptions.defaultDebounce && this.customOptions.defaultDebounce > 0) {
  579. options.listener = this.debounce(
  580. options.listener,
  581. options.debounce || this.customOptions.defaultDebounce
  582. );
  583. }
  584. if (this.listenerMap.has(selector))
  585. this.listenerMap.get(selector).push(options);
  586. else
  587. this.listenerMap.set(selector, [options]);
  588. if (this.enabled === false && this.customOptions.enableOnAddListener)
  589. this.enable();
  590. this.checkSelector(selector, [options]);
  591. }
  592. /** Disables the observation of the child elements */
  593. disable() {
  594. if (!this.enabled)
  595. return;
  596. this.enabled = false;
  597. this.observer.disconnect();
  598. }
  599. /**
  600. * Enables or reenables the observation of the child elements.
  601. * @param immediatelyCheckSelectors Whether to immediately check if all previously registered selectors exist (default is true)
  602. * @returns Returns true when the observation was enabled, false otherwise (e.g. when the base element wasn't found)
  603. */
  604. enable(immediatelyCheckSelectors = true) {
  605. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  606. if (this.enabled || !baseElement)
  607. return false;
  608. this.enabled = true;
  609. this.observer.observe(baseElement, this.observerOptions);
  610. if (immediatelyCheckSelectors)
  611. this.checkAllSelectors();
  612. return true;
  613. }
  614. /** Returns whether the observation of the child elements is currently enabled */
  615. isEnabled() {
  616. return this.enabled;
  617. }
  618. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  619. clearListeners() {
  620. this.listenerMap.clear();
  621. }
  622. /**
  623. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  624. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  625. */
  626. removeAllListeners(selector) {
  627. return this.listenerMap.delete(selector);
  628. }
  629. /**
  630. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  631. * @returns Returns true when the listener was found and removed, false otherwise
  632. */
  633. removeListener(selector, options) {
  634. const listeners = this.listenerMap.get(selector);
  635. if (!listeners)
  636. return false;
  637. const index = listeners.indexOf(options);
  638. if (index > -1) {
  639. listeners.splice(index, 1);
  640. return true;
  641. }
  642. return false;
  643. }
  644. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  645. getAllListeners() {
  646. return this.listenerMap;
  647. }
  648. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  649. getListeners(selector) {
  650. return this.listenerMap.get(selector);
  651. }
  652. };
  653.  
  654. // lib/translation.ts
  655. var trans = {};
  656. var curLang;
  657. function tr(key, ...args) {
  658. var _a;
  659. if (!curLang)
  660. return key;
  661. const trText = (_a = trans[curLang]) == null ? void 0 : _a[key];
  662. if (!trText)
  663. return key;
  664. if (args.length > 0 && trText.match(/%\d/)) {
  665. return insertValues(trText, ...args);
  666. }
  667. return trText;
  668. }
  669. tr.addLanguage = (language, translations) => {
  670. trans[language] = translations;
  671. };
  672. tr.setLanguage = (language) => {
  673. curLang = language;
  674. };
  675. tr.getLanguage = () => {
  676. return curLang;
  677. };
  678.  
  679. exports.DataStore = DataStore;
  680. exports.SelectorObserver = SelectorObserver;
  681. exports.addGlobalStyle = addGlobalStyle;
  682. exports.addParent = addParent;
  683. exports.autoPlural = autoPlural;
  684. exports.clamp = clamp;
  685. exports.compress = compress;
  686. exports.debounce = debounce;
  687. exports.decompress = decompress;
  688. exports.fetchAdvanced = fetchAdvanced;
  689. exports.getSiblingsFrame = getSiblingsFrame;
  690. exports.getUnsafeWindow = getUnsafeWindow;
  691. exports.insertAfter = insertAfter;
  692. exports.insertValues = insertValues;
  693. exports.interceptEvent = interceptEvent;
  694. exports.interceptWindowEvent = interceptWindowEvent;
  695. exports.isScrollable = isScrollable;
  696. exports.mapRange = mapRange;
  697. exports.observeElementProp = observeElementProp;
  698. exports.openInNewTab = openInNewTab;
  699. exports.pauseFor = pauseFor;
  700. exports.preloadImages = preloadImages;
  701. exports.randRange = randRange;
  702. exports.randomId = randomId;
  703. exports.randomItem = randomItem;
  704. exports.randomItemIndex = randomItemIndex;
  705. exports.randomizeArray = randomizeArray;
  706. exports.takeRandomItem = takeRandomItem;
  707. exports.tr = tr;
  708.  
  709. return exports;
  710.  
  711. })({});

QingJ © 2025

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