Basic Functions (For userscripts)

Useful functions for myself

As of 2024-03-23. See the latest version.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/456034/1348004/Basic%20Functions%20%28For%20userscripts%29.js

  1. /* eslint-disable no-multi-spaces */
  2. /* eslint-disable no-return-assign */
  3.  
  4. // ==UserScript==
  5. // @name Basic Functions (For userscripts)
  6. // @name:zh-CN 常用函数(用户脚本)
  7. // @name:en Basic Functions (For userscripts)
  8. // @namespace PY-DNG Userscripts
  9. // @version 0.8.5.2
  10. // @description Useful functions for myself
  11. // @description:zh-CN 自用函数
  12. // @description:en Useful functions for myself
  13. // @author PY-DNG
  14. // @license GPL-3.0-or-later
  15. // ==/UserScript==
  16.  
  17. // Note: version 0.8.2.1 is modified just the license and it's not uploaded to GF yet 23-11-26 15:03
  18. // Note: version 0.8.3.1 is added just the description of parseArgs and has not uploaded to GF yet 24-02-03 18:55
  19.  
  20. let [
  21. // Console & Debug
  22. LogLevel, DoLog, Err, Assert,
  23.  
  24. // DOM
  25. $, $All, $CrE, $AEL, $$CrE, addStyle, detectDom, destroyEvent,
  26.  
  27. // Data
  28. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  29.  
  30. // Environment & Browser
  31. getUrlArgv, dl_browser, dl_GM,
  32.  
  33. // Logic & Task
  34. AsyncManager, testChecker, registerChecker, loadFuncs
  35. ] = (function() {
  36. // function DoLog() {}
  37. // Arguments: level=LogLevel.Info, logContent, logger='log'
  38. const [LogLevel, DoLog] = (function() {
  39. const LogLevel = {
  40. None: 0,
  41. Error: 1,
  42. Success: 2,
  43. Warning: 3,
  44. Info: 4,
  45. };
  46.  
  47. return [LogLevel, DoLog];
  48. function DoLog() {
  49. // Get window
  50. const win = (typeof(unsafeWindow) === 'object' && unsafeWindow !== null) ? unsafeWindow : window;
  51.  
  52. const LogLevelMap = {};
  53. LogLevelMap[LogLevel.None] = {
  54. prefix: '',
  55. color: 'color:#ffffff'
  56. }
  57. LogLevelMap[LogLevel.Error] = {
  58. prefix: '[Error]',
  59. color: 'color:#ff0000'
  60. }
  61. LogLevelMap[LogLevel.Success] = {
  62. prefix: '[Success]',
  63. color: 'color:#00aa00'
  64. }
  65. LogLevelMap[LogLevel.Warning] = {
  66. prefix: '[Warning]',
  67. color: 'color:#ffa500'
  68. }
  69. LogLevelMap[LogLevel.Info] = {
  70. prefix: '[Info]',
  71. color: 'color:#888888'
  72. }
  73. LogLevelMap[LogLevel.Elements] = {
  74. prefix: '[Elements]',
  75. color: 'color:#000000'
  76. }
  77.  
  78. // Current log level
  79. DoLog.logLevel = (win.isPY_DNG && win.userscriptDebugging) ? LogLevel.Info : LogLevel.Warning; // Info Warning Success Error
  80.  
  81. // Log counter
  82. DoLog.logCount === undefined && (DoLog.logCount = 0);
  83.  
  84. // Get args
  85. let [level, logContent, logger] = parseArgs([...arguments], [
  86. [2],
  87. [1,2],
  88. [1,2,3]
  89. ], [LogLevel.Info, 'DoLog initialized.', 'log']);
  90.  
  91. let msg = '%c' + LogLevelMap[level].prefix + (typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + (LogLevelMap[level].prefix ? ' ' : '');
  92. let subst = LogLevelMap[level].color;
  93.  
  94. switch (typeof(logContent)) {
  95. case 'string':
  96. msg += '%s';
  97. break;
  98. case 'number':
  99. msg += '%d';
  100. break;
  101. default:
  102. msg += '%o';
  103. break;
  104. }
  105.  
  106. // Log when log level permits
  107. if (level <= DoLog.logLevel) {
  108. // Log to console when log level permits
  109. if (level <= DoLog.logLevel) {
  110. if (++DoLog.logCount > 512) {
  111. console.clear();
  112. DoLog.logCount = 0;
  113. }
  114. console[logger](msg, subst, logContent);
  115. }
  116. }
  117. }
  118. }) ();
  119.  
  120. // type: [Error, TypeError]
  121. function Err(msg, type=0) {
  122. throw new [Error, TypeError][type]((typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + msg);
  123. }
  124.  
  125. function Assert(val, errmsg, errtype) {
  126. val || Err(errmsg, errtype);
  127. }
  128.  
  129. // Basic functions
  130. // querySelector
  131. function $() {
  132. switch(arguments.length) {
  133. case 2:
  134. return arguments[0].querySelector(arguments[1]);
  135. break;
  136. default:
  137. return document.querySelector(arguments[0]);
  138. }
  139. }
  140. // querySelectorAll
  141. function $All() {
  142. switch(arguments.length) {
  143. case 2:
  144. return arguments[0].querySelectorAll(arguments[1]);
  145. break;
  146. default:
  147. return document.querySelectorAll(arguments[0]);
  148. }
  149. }
  150. // createElement
  151. function $CrE() {
  152. switch(arguments.length) {
  153. case 2:
  154. return arguments[0].createElement(arguments[1]);
  155. break;
  156. default:
  157. return document.createElement(arguments[0]);
  158. }
  159. }
  160. // addEventListener
  161. function $AEL(...args) {
  162. const target = args.shift();
  163. return target.addEventListener.apply(target, args);
  164. }
  165. function $$CrE() {
  166. const [tagName, props, attrs, classes, styles, listeners] = parseArgs([...arguments], [
  167. function(args, defaultValues) {
  168. const arg = args[0];
  169. return {
  170. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  171. 'object': () => ['tagName', 'props', 'attrs', 'classes', 'styles', 'listeners'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  172. }[typeof arg]();
  173. },
  174. [1,2],
  175. [1,2,3],
  176. [1,2,3,4],
  177. [1,2,3,4,5]
  178. ], ['div', {}, {}, [], {}, []]);
  179. const elm = $CrE(tagName);
  180. for (const [name, val] of Object.entries(props)) {
  181. elm[name] = val;
  182. }
  183. for (const [name, val] of Object.entries(attrs)) {
  184. elm.setAttribute(name, val);
  185. }
  186. for (const cls of Array.isArray(classes) ? classes : [classes]) {
  187. elm.classList.add(cls);
  188. }
  189. for (const [name, val] of Object.entries(styles)) {
  190. elm.style[name] = val;
  191. }
  192. for (const listener of listeners) {
  193. $AEL(...[elm, ...listener]);
  194. }
  195. return elm;
  196. }
  197.  
  198. // Append a style text to document(<head>) with a <style> element
  199. // arguments: css | css, id | parentElement, css, id
  200. // remove old one when id duplicates with another element in document
  201. function addStyle() {
  202. // Get arguments
  203. const [parentElement, css, id] = parseArgs([...arguments], [
  204. [2],
  205. [2,3],
  206. [1,2,3]
  207. ], [document.head, '', null]);
  208.  
  209. // Make <style>
  210. const style = $CrE("style");
  211. style.textContent = css;
  212. id !== null && (style.id = id);
  213. id !== null && $(`#${id}`) && $(`#${id}`).remove();
  214.  
  215. // Append to parentElement
  216. parentElement.appendChild(style);
  217. return style;
  218. }
  219.  
  220. // Get callback when specific dom/element loaded
  221. // detectDom({[root], selector, callback[, once]}) | detectDom(selector, callback) | detectDom(root, selector, callback) | detectDom(root, selector, callback, attributes) | detectDom(root, selector, callback, attributes, once)
  222. // Supports both callback for multiple detection, and promise for one-time detection.
  223. // By default promise mode is preferred, meaning `callback` argument should be provided explicitly when using callback
  224. // mode (by adding `callback` property in details object, or provide all 4 arguments where callback should be the last)
  225. // This behavior is different from versions that equals to or older than 0.8.4.2, so be careful when using it.
  226. function detectDom() {
  227. let [selectors, root, attributes, callback] = parseArgs([...arguments], [
  228. function(args, defaultValues) {
  229. const arg = args[0];
  230. return {
  231. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  232. 'object': () => ['root', 'selector', 'attributes', 'callback'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  233. }[typeof arg]();
  234. },
  235. [2,1],
  236. [2,1,3],
  237. [2,1,3,4],
  238. ], [[''], document, false, null]);
  239. !Array.isArray(selectors) && (selectors = [selectors]);
  240.  
  241. if (select(root, selectors)) {
  242. for (const elm of selectAll(root, selectors)) {
  243. return callback ? (callback(elm), null) : Promise.resolve(elm);
  244. }
  245. }
  246.  
  247. const observer = new MutationObserver(mCallback);
  248. observer.observe(root, {
  249. childList: true,
  250. subtree: true,
  251. attributes,
  252. });
  253.  
  254. let isPromise = !callback;
  255. return callback ? observer : new Promise((resolve, reject) => callback = resolve);
  256.  
  257. function mCallback(mutationList, observer) {
  258. const addedNodes = mutationList.reduce((an, mutation) => {
  259. switch (mutation.type) {
  260. case 'childList':
  261. an.push(...mutation.addedNodes);
  262. break;
  263. case 'attributes':
  264. an.push(mutation.target);
  265. break;
  266. }
  267. return an;
  268. }, []);
  269. const addedSelectorNodes = addedNodes.reduce((nodes, anode) => {
  270. if (anode.matches && match(anode, selectors)) {
  271. nodes.add(anode);
  272. }
  273. const childMatches = anode.querySelectorAll ? selectAll(anode, selectors) : [];
  274. for (const cm of childMatches) {
  275. nodes.add(cm);
  276. }
  277. return nodes;
  278. }, new Set());
  279. for (const node of addedSelectorNodes) {
  280. callback(node);
  281. isPromise && observer.disconnect();
  282. }
  283. }
  284.  
  285. function selectAll(elm, selectors) {
  286. !Array.isArray(selectors) && (selectors = [selectors]);
  287. return selectors.map(selector => [...$All(elm, selector)]).reduce((all, arr) => {
  288. all.push(...arr);
  289. return all;
  290. }, []);
  291. }
  292.  
  293. function select(elm, selectors) {
  294. const all = selectAll(elm, selectors);
  295. return all.length ? all[0] : null;
  296. }
  297.  
  298. function match(elm, selectors) {
  299. return !!elm.matches && selectors.some(selector => elm.matches(selector));
  300. }
  301. }
  302.  
  303. // Just stopPropagation and preventDefault
  304. function destroyEvent(e) {
  305. if (!e) {return false;};
  306. if (!e instanceof Event) {return false;};
  307. e.stopPropagation();
  308. e.preventDefault();
  309. }
  310.  
  311. // Object1[prop] ==> Object2[prop]
  312. function copyProp(obj1, obj2, prop) {obj1[prop] !== undefined && (obj2[prop] = obj1[prop]);}
  313. function copyProps(obj1, obj2, props) {(props || Object.keys(obj1)).forEach((prop) => (copyProp(obj1, obj2, prop)));}
  314.  
  315. // Argument parser with sorting and defaultValue support
  316. function parseArgs(args, rules, defaultValues=[]) {
  317. // args and rules should be array, but not just iterable (string is also iterable)
  318. if (!Array.isArray(args) || !Array.isArray(rules)) {
  319. throw new TypeError('parseArgs: args and rules should be array')
  320. }
  321.  
  322. // fill rules[0]
  323. (!Array.isArray(rules[0]) || rules[0].length === 1) && rules.splice(0, 0, []);
  324.  
  325. // max arguments length
  326. const count = rules.length - 1;
  327.  
  328. // args.length must <= count
  329. if (args.length > count) {
  330. throw new TypeError(`parseArgs: args has more elements(${args.length}) longer than ruless'(${count})`);
  331. }
  332.  
  333. // rules[i].length should be === i if rules[i] is an array, otherwise it should be a function
  334. for (let i = 1; i <= count; i++) {
  335. const rule = rules[i];
  336. if (Array.isArray(rule)) {
  337. if (rule.length !== i) {
  338. throw new TypeError(`parseArgs: rules[${i}](${rule}) should have ${i} numbers, but given ${rules[i].length}`);
  339. }
  340. if (!rule.every((num) => (typeof num === 'number' && num <= count))) {
  341. throw new TypeError(`parseArgs: rules[${i}](${rule}) should contain numbers smaller than count(${count}) only`);
  342. }
  343. } else if (typeof rule !== 'function') {
  344. throw new TypeError(`parseArgs: rules[${i}](${rule}) should be an array or a function.`)
  345. }
  346. }
  347.  
  348. // Parse
  349. const rule = rules[args.length];
  350. let parsed;
  351. if (Array.isArray(rule)) {
  352. parsed = [...defaultValues];
  353. for (let i = 0; i < rule.length; i++) {
  354. parsed[rule[i]-1] = args[i];
  355. }
  356. } else {
  357. parsed = rule(args, defaultValues);
  358. }
  359. return parsed;
  360. }
  361.  
  362. // escape str into javascript written format
  363. function escJsStr(str, quote='"') {
  364. str = str.replaceAll('\\', '\\\\').replaceAll(quote, '\\' + quote).replaceAll('\t', '\\t');
  365. str = quote === '`' ? str.replaceAll(/(\$\{[^\}]*\})/g, '\\$1') : str.replaceAll('\r', '\\r').replaceAll('\n', '\\n');
  366. return quote + str + quote;
  367. }
  368.  
  369. // Replace model text with no mismatching of replacing replaced text
  370. // e.g. replaceText('aaaabbbbccccdddd', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'}) === 'bbbbccccddddeeee'
  371. // replaceText('abcdAABBAA', {'BB': 'AA', 'AAAAAA': 'This is a trap!'}) === 'abcdAAAAAA'
  372. // replaceText('abcd{AAAA}BB}', {'{AAAA}': '{BB', '{BBBB}': 'This is a trap!'}) === 'abcd{BBBB}'
  373. // replaceText('abcd', {}) === 'abcd'
  374. /* Note:
  375. replaceText will replace in sort of replacer's iterating sort
  376. e.g. currently replaceText('abcdAABBAA', {'BBAA': 'TEXT', 'AABB': 'TEXT'}) === 'abcdAATEXT'
  377. but remember: (As MDN Web Doc said,) Although the keys of an ordinary Object are ordered now, this was
  378. not always the case, and the order is complex. As a result, it's best not to rely on property order.
  379. So, don't expect replaceText will treat replacer key-values in any specific sort. Use replaceText to
  380. replace irrelevance replacer keys only.
  381. */
  382. function replaceText(text, replacer) {
  383. if (Object.entries(replacer).length === 0) {return text;}
  384. const [models, targets] = Object.entries(replacer);
  385. const len = models.length;
  386. let text_arr = [{text: text, replacable: true}];
  387. for (const [model, target] of Object.entries(replacer)) {
  388. text_arr = replace(text_arr, model, target);
  389. }
  390. return text_arr.map((text_obj) => (text_obj.text)).join('');
  391.  
  392. function replace(text_arr, model, target) {
  393. const result_arr = [];
  394. for (const text_obj of text_arr) {
  395. if (text_obj.replacable) {
  396. const splited = text_obj.text.split(model);
  397. for (const part of splited) {
  398. result_arr.push({text: part, replacable: true});
  399. result_arr.push({text: target, replacable: false});
  400. }
  401. result_arr.pop();
  402. } else {
  403. result_arr.push(text_obj);
  404. }
  405. }
  406. return result_arr;
  407. }
  408. }
  409.  
  410. // Get a url argument from location.href
  411. // also recieve a function to deal the matched string
  412. // returns defaultValue if name not found
  413. // Args: {name, url=location.href, defaultValue=null, dealFunc=((a)=>{return a;})} or (name) or (url, name) or (url, name, defaultValue) or (url, name, defaultValue, dealFunc)
  414. function getUrlArgv(details) {
  415. const [name, url, defaultValue, dealFunc] = parseArgs([...arguments], [
  416. function(args, defaultValues) {
  417. const arg = args[0];
  418. return {
  419. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  420. 'object': () => ['name', 'url', 'defaultValue', 'dealFunc'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  421. }[typeof arg]();
  422. },
  423. [2,1],
  424. [2,1,3],
  425. [2,1,3,4]
  426. ], [null, location.href, null, a => a]);
  427.  
  428. if (name === null) { return null; }
  429.  
  430. const search = new URL(url).search;
  431. const objSearch = new URLSearchParams(search);
  432. const raw = objSearch.has(name) ? objSearch.get(name) : defaultValue;
  433. const argv = dealFunc(raw);
  434.  
  435. return argv;
  436. }
  437.  
  438. // Save dataURL to file
  439. function dl_browser(dataURL, filename) {
  440. const a = document.createElement('a');
  441. a.href = dataURL;
  442. a.download = filename;
  443. a.click();
  444. }
  445.  
  446. // File download function
  447. // details looks like the detail of GM_xmlhttpRequest
  448. // onload function will be called after file saved to disk
  449. function dl_GM(details) {
  450. if (!details.url || !details.name) {return false;};
  451.  
  452. // Configure request object
  453. const requestObj = {
  454. url: details.url,
  455. responseType: 'blob',
  456. onload: function(e) {
  457. // Save file
  458. dl_browser(URL.createObjectURL(e.response), details.name);
  459.  
  460. // onload callback
  461. details.onload ? details.onload(e) : function() {};
  462. }
  463. }
  464. if (details.onloadstart ) {requestObj.onloadstart = details.onloadstart;};
  465. if (details.onprogress ) {requestObj.onprogress = details.onprogress;};
  466. if (details.onerror ) {requestObj.onerror = details.onerror;};
  467. if (details.onabort ) {requestObj.onabort = details.onabort;};
  468. if (details.onreadystatechange) {requestObj.onreadystatechange = details.onreadystatechange;};
  469. if (details.ontimeout ) {requestObj.ontimeout = details.ontimeout;};
  470.  
  471. // Send request
  472. GM_xmlhttpRequest(requestObj);
  473. }
  474.  
  475. function AsyncManager() {
  476. const AM = this;
  477.  
  478. // Ongoing xhr count
  479. this.taskCount = 0;
  480.  
  481. // Whether generate finish events
  482. let finishEvent = false;
  483. Object.defineProperty(this, 'finishEvent', {
  484. configurable: true,
  485. enumerable: true,
  486. get: () => (finishEvent),
  487. set: (b) => {
  488. finishEvent = b;
  489. b && AM.taskCount === 0 && AM.onfinish && AM.onfinish();
  490. }
  491. });
  492.  
  493. // Add one task
  494. this.add = () => (++AM.taskCount);
  495.  
  496. // Finish one task
  497. this.finish = () => ((--AM.taskCount === 0 && AM.finishEvent && AM.onfinish && AM.onfinish(), AM.taskCount));
  498. }
  499.  
  500. const [testChecker, registerChecker, loadFuncs] = (function() {
  501. const checkers = {
  502. switch: value => value,
  503. url: value => location.href === value,
  504. path: value => location.pathname === value,
  505. regurl: value => !!location.href.match(value),
  506. regpath: value => !!location.pathname.match(value),
  507. starturl: value => location.href.startsWith(value),
  508. startpath: value => location.pathname.startsWith(value),
  509. func: value => value()
  510. };
  511.  
  512. // Check whether current page url matches FuncInfo.checker rule
  513. // This code is copy and modified from FunctionLoader.check
  514. function testChecker(checker) {
  515. if (!checker) {return true;}
  516. const values = Array.isArray(checker.value) ? checker.value : [checker.value];
  517. return values[checker.all ? 'every' : 'some'](value => {
  518. const type = checker.type;
  519. if (checkers.hasOwnProperty(type)) {
  520. try {
  521. return checkers[type](value);
  522. } catch (err) {
  523. DoLog(LogLevel.Error, 'Checker function raised an error');
  524. DoLog(LogLevel.Error, err);
  525. return false;
  526. }
  527. } else {
  528. DoLog(LogLevel.Error, 'Invalid checker type');
  529. return false;
  530. }
  531. });
  532. }
  533.  
  534. function registerChecker(name, func) {
  535. Assert(['Symbol', 'string', 'number'].includes(typeof name), 'name should be symbol, string or number');
  536. Assert(typeof func === 'function', 'func should be a function');
  537. checkers[name] = func;
  538. }
  539.  
  540. // Load all function-objs provided in funcs asynchronously, and merge return values into one return obj
  541. // funcobj: {[checker], [detectDom], func}
  542. function loadFuncs(oFuncs) {
  543. const returnObj = {};
  544.  
  545. oFuncs.forEach(oFunc => {
  546. if (!oFunc.checker || testChecker(oFunc.checker)) {
  547. if (oFunc.detectDom) {
  548. const selectors = Array.isArray(oFunc.detectDom) ? oFunc.detectDom : [oFunc.detectDom];
  549. Promise.all(selectors.map(selector => detectDom(selector))).then(node => execute(oFunc));
  550. } else {
  551. setTimeout(e => execute(oFunc), 0);
  552. }
  553. }
  554. });
  555.  
  556. return returnObj;
  557.  
  558. function execute(oFunc) {
  559. setTimeout(e => {
  560. const rval = oFunc.func(returnObj) || {};
  561. copyProps(rval, returnObj);
  562. }, 0);
  563. }
  564. }
  565.  
  566. return [testChecker, registerChecker, loadFuncs];
  567. }) ();
  568.  
  569. return [
  570. // Console & Debug
  571. LogLevel, DoLog, Err, Assert,
  572.  
  573. // DOM
  574. $, $All, $CrE, $AEL, $$CrE, addStyle, detectDom, destroyEvent,
  575.  
  576. // Data
  577. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  578.  
  579. // Environment & Browser
  580. getUrlArgv, dl_browser, dl_GM,
  581.  
  582. // Logic & Task
  583. AsyncManager, testChecker, registerChecker, loadFuncs
  584. ];
  585. })();