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

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

QingJ © 2025

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