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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/472956/1353203/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.1.0
  12. // @license MIT
  13. // @copyright Sv443 (https://github.com/Sv443)
  14.  
  15. // ==/UserScript==
  16. // ==/UserLibrary==
  17.  
  18. // ==OpenUserJS==
  19. // @author Sv443
  20. // ==/OpenUserJS==
  21.  
  22. var UserUtils = (function (exports) {
  23. var __defProp = Object.defineProperty;
  24. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  25. var __hasOwnProp = Object.prototype.hasOwnProperty;
  26. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  27. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  28. var __spreadValues = (a, b) => {
  29. for (var prop in b || (b = {}))
  30. if (__hasOwnProp.call(b, prop))
  31. __defNormalProp(a, prop, b[prop]);
  32. if (__getOwnPropSymbols)
  33. for (var prop of __getOwnPropSymbols(b)) {
  34. if (__propIsEnum.call(b, prop))
  35. __defNormalProp(a, prop, b[prop]);
  36. }
  37. return a;
  38. };
  39. var __objRest = (source, exclude) => {
  40. var target = {};
  41. for (var prop in source)
  42. if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
  43. target[prop] = source[prop];
  44. if (source != null && __getOwnPropSymbols)
  45. for (var prop of __getOwnPropSymbols(source)) {
  46. if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
  47. target[prop] = source[prop];
  48. }
  49. return target;
  50. };
  51. var __publicField = (obj, key, value) => {
  52. __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  53. return value;
  54. };
  55. var __async = (__this, __arguments, generator) => {
  56. return new Promise((resolve, reject) => {
  57. var fulfilled = (value) => {
  58. try {
  59. step(generator.next(value));
  60. } catch (e) {
  61. reject(e);
  62. }
  63. };
  64. var rejected = (value) => {
  65. try {
  66. step(generator.throw(value));
  67. } catch (e) {
  68. reject(e);
  69. }
  70. };
  71. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  72. step((generator = generator.apply(__this, __arguments)).next());
  73. });
  74. };
  75.  
  76. // lib/math.ts
  77. function clamp(value, min, max) {
  78. return Math.max(Math.min(value, max), min);
  79. }
  80. function mapRange(value, range1min, range1max, range2min, range2max) {
  81. if (Number(range1min) === 0 && Number(range2min) === 0)
  82. return value * (range2max / range1max);
  83. return (value - range1min) * ((range2max - range2min) / (range1max - range1min)) + range2min;
  84. }
  85. function randRange(...args) {
  86. let min, max;
  87. if (typeof args[0] === "number" && typeof args[1] === "number")
  88. [min, max] = args;
  89. else if (typeof args[0] === "number" && typeof args[1] !== "number") {
  90. min = 0;
  91. [max] = args;
  92. } else
  93. throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
  94. min = Number(min);
  95. max = Number(max);
  96. if (isNaN(min) || isNaN(max))
  97. return NaN;
  98. if (min > max)
  99. throw new TypeError(`Parameter "min" can't be bigger than "max"`);
  100. return Math.floor(Math.random() * (max - min + 1)) + min;
  101. }
  102. 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, edge = "falling") {
  436. let timer;
  437. return function(...args) {
  438. if (edge === "rising") {
  439. if (!timer) {
  440. func.apply(this, args);
  441. timer = setTimeout(() => timer = void 0, timeout);
  442. }
  443. } else {
  444. clearTimeout(timer);
  445. timer = setTimeout(() => func.apply(this, args), timeout);
  446. }
  447. };
  448. }
  449. function fetchAdvanced(_0) {
  450. return __async(this, arguments, function* (input, options = {}) {
  451. const { timeout = 1e4 } = options;
  452. let signalOpts = {}, id = void 0;
  453. if (timeout >= 0) {
  454. const controller = new AbortController();
  455. id = setTimeout(() => controller.abort(), timeout);
  456. signalOpts = { signal: controller.signal };
  457. }
  458. const res = yield fetch(input, __spreadValues(__spreadValues({}, options), signalOpts));
  459. clearTimeout(id);
  460. return res;
  461. });
  462. }
  463. function insertValues(input, ...values) {
  464. return input.replace(/%\d/gm, (match) => {
  465. var _a, _b;
  466. const argIndex = Number(match.substring(1)) - 1;
  467. return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
  468. });
  469. }
  470. function compress(input, compressionFormat, outputType = "string") {
  471. return __async(this, null, function* () {
  472. const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
  473. const comp = new CompressionStream(compressionFormat);
  474. const writer = comp.writable.getWriter();
  475. writer.write(byteArray);
  476. writer.close();
  477. const buf = yield new Response(comp.readable).arrayBuffer();
  478. return outputType === "arrayBuffer" ? buf : ab2str(buf);
  479. });
  480. }
  481. function decompress(input, compressionFormat, outputType = "string") {
  482. return __async(this, null, function* () {
  483. const byteArray = typeof input === "string" ? str2ab(input) : input;
  484. const decomp = new DecompressionStream(compressionFormat);
  485. const writer = decomp.writable.getWriter();
  486. writer.write(byteArray);
  487. writer.close();
  488. const buf = yield new Response(decomp.readable).arrayBuffer();
  489. return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
  490. });
  491. }
  492. function ab2str(buf) {
  493. return getUnsafeWindow().btoa(
  494. new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
  495. );
  496. }
  497. function str2ab(str) {
  498. return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
  499. }
  500.  
  501. // lib/SelectorObserver.ts
  502. var SelectorObserver = class {
  503. constructor(baseElement, options = {}) {
  504. __publicField(this, "enabled", false);
  505. __publicField(this, "baseElement");
  506. __publicField(this, "observer");
  507. __publicField(this, "observerOptions");
  508. __publicField(this, "customOptions");
  509. __publicField(this, "listenerMap");
  510. this.baseElement = baseElement;
  511. this.listenerMap = /* @__PURE__ */ new Map();
  512. this.observer = new MutationObserver(() => this.checkAllSelectors());
  513. const _a = options, {
  514. defaultDebounce,
  515. disableOnNoListeners,
  516. enableOnAddListener
  517. } = _a, observerOptions = __objRest(_a, [
  518. "defaultDebounce",
  519. "disableOnNoListeners",
  520. "enableOnAddListener"
  521. ]);
  522. this.observerOptions = __spreadValues({
  523. childList: true,
  524. subtree: true
  525. }, observerOptions);
  526. this.customOptions = {
  527. defaultDebounce: defaultDebounce != null ? defaultDebounce : 0,
  528. disableOnNoListeners: disableOnNoListeners != null ? disableOnNoListeners : false,
  529. enableOnAddListener: enableOnAddListener != null ? enableOnAddListener : true
  530. };
  531. }
  532. checkAllSelectors() {
  533. for (const [selector, listeners] of this.listenerMap.entries())
  534. this.checkSelector(selector, listeners);
  535. }
  536. checkSelector(selector, listeners) {
  537. var _a;
  538. if (!this.enabled)
  539. return;
  540. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  541. if (!baseElement)
  542. return;
  543. const all = listeners.some((listener) => listener.all);
  544. const one = listeners.some((listener) => !listener.all);
  545. const allElements = all ? baseElement.querySelectorAll(selector) : null;
  546. const oneElement = one ? baseElement.querySelector(selector) : null;
  547. for (const options of listeners) {
  548. if (options.all) {
  549. if (allElements && allElements.length > 0) {
  550. options.listener(allElements);
  551. if (!options.continuous)
  552. this.removeListener(selector, options);
  553. }
  554. } else {
  555. if (oneElement) {
  556. options.listener(oneElement);
  557. if (!options.continuous)
  558. this.removeListener(selector, options);
  559. }
  560. }
  561. if (((_a = this.listenerMap.get(selector)) == null ? void 0 : _a.length) === 0)
  562. this.listenerMap.delete(selector);
  563. if (this.listenerMap.size === 0 && this.customOptions.disableOnNoListeners)
  564. this.disable();
  565. }
  566. }
  567. debounce(func, time) {
  568. let timeout;
  569. return function(...args) {
  570. clearTimeout(timeout);
  571. timeout = setTimeout(() => func.apply(this, args), time);
  572. };
  573. }
  574. /**
  575. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  576. * @param selector The selector to observe
  577. * @param options Options for the selector observation
  578. * @param options.listener Gets called whenever the selector was found in the DOM
  579. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  580. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  581. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  582. */
  583. addListener(selector, options) {
  584. options = __spreadValues({ all: false, continuous: false, debounce: 0 }, options);
  585. if (options.debounce && options.debounce > 0 || this.customOptions.defaultDebounce && this.customOptions.defaultDebounce > 0) {
  586. options.listener = this.debounce(
  587. options.listener,
  588. options.debounce || this.customOptions.defaultDebounce
  589. );
  590. }
  591. if (this.listenerMap.has(selector))
  592. this.listenerMap.get(selector).push(options);
  593. else
  594. this.listenerMap.set(selector, [options]);
  595. if (this.enabled === false && this.customOptions.enableOnAddListener)
  596. this.enable();
  597. this.checkSelector(selector, [options]);
  598. }
  599. /** Disables the observation of the child elements */
  600. disable() {
  601. if (!this.enabled)
  602. return;
  603. this.enabled = false;
  604. this.observer.disconnect();
  605. }
  606. /**
  607. * Enables or reenables the observation of the child elements.
  608. * @param immediatelyCheckSelectors Whether to immediately check if all previously registered selectors exist (default is true)
  609. * @returns Returns true when the observation was enabled, false otherwise (e.g. when the base element wasn't found)
  610. */
  611. enable(immediatelyCheckSelectors = true) {
  612. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  613. if (this.enabled || !baseElement)
  614. return false;
  615. this.enabled = true;
  616. this.observer.observe(baseElement, this.observerOptions);
  617. if (immediatelyCheckSelectors)
  618. this.checkAllSelectors();
  619. return true;
  620. }
  621. /** Returns whether the observation of the child elements is currently enabled */
  622. isEnabled() {
  623. return this.enabled;
  624. }
  625. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  626. clearListeners() {
  627. this.listenerMap.clear();
  628. }
  629. /**
  630. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  631. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  632. */
  633. removeAllListeners(selector) {
  634. return this.listenerMap.delete(selector);
  635. }
  636. /**
  637. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  638. * @returns Returns true when the listener was found and removed, false otherwise
  639. */
  640. removeListener(selector, options) {
  641. const listeners = this.listenerMap.get(selector);
  642. if (!listeners)
  643. return false;
  644. const index = listeners.indexOf(options);
  645. if (index > -1) {
  646. listeners.splice(index, 1);
  647. return true;
  648. }
  649. return false;
  650. }
  651. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  652. getAllListeners() {
  653. return this.listenerMap;
  654. }
  655. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  656. getListeners(selector) {
  657. return this.listenerMap.get(selector);
  658. }
  659. };
  660.  
  661. // lib/translation.ts
  662. var trans = {};
  663. var curLang;
  664. function tr(key, ...args) {
  665. var _a;
  666. if (!curLang)
  667. return key;
  668. const trText = (_a = trans[curLang]) == null ? void 0 : _a[key];
  669. if (!trText)
  670. return key;
  671. if (args.length > 0 && trText.match(/%\d/)) {
  672. return insertValues(trText, ...args);
  673. }
  674. return trText;
  675. }
  676. tr.addLanguage = (language, translations) => {
  677. trans[language] = translations;
  678. };
  679. tr.setLanguage = (language) => {
  680. curLang = language;
  681. };
  682. tr.getLanguage = () => {
  683. return curLang;
  684. };
  685.  
  686. exports.DataStore = DataStore;
  687. exports.SelectorObserver = SelectorObserver;
  688. exports.addGlobalStyle = addGlobalStyle;
  689. exports.addParent = addParent;
  690. exports.autoPlural = autoPlural;
  691. exports.clamp = clamp;
  692. exports.compress = compress;
  693. exports.debounce = debounce;
  694. exports.decompress = decompress;
  695. exports.fetchAdvanced = fetchAdvanced;
  696. exports.getSiblingsFrame = getSiblingsFrame;
  697. exports.getUnsafeWindow = getUnsafeWindow;
  698. exports.insertAfter = insertAfter;
  699. exports.insertValues = insertValues;
  700. exports.interceptEvent = interceptEvent;
  701. exports.interceptWindowEvent = interceptWindowEvent;
  702. exports.isScrollable = isScrollable;
  703. exports.mapRange = mapRange;
  704. exports.observeElementProp = observeElementProp;
  705. exports.openInNewTab = openInNewTab;
  706. exports.pauseFor = pauseFor;
  707. exports.preloadImages = preloadImages;
  708. exports.randRange = randRange;
  709. exports.randomId = randomId;
  710. exports.randomItem = randomItem;
  711. exports.randomItemIndex = randomItemIndex;
  712. exports.randomizeArray = randomizeArray;
  713. exports.takeRandomItem = takeRandomItem;
  714. exports.tr = tr;
  715.  
  716. return exports;
  717.  
  718. })({});

QingJ © 2025

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