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/1348001/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.1
  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 [root, selectors, attributes, callback] = parseArgs([...arguments], [
  228. function(args, defaultValues) {
  229. const arg = args[0];
  230. return ['root', 'selector', 'attributes', 'callback'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i]);
  231. },
  232. [1,2],
  233. [1,2,3],
  234. [1,2,3,4],
  235. ], [document, [''], false, null]);
  236. !Array.isArray(selectors) && (selectors = [selectors]);
  237.  
  238. if (select(root, selectors)) {
  239. for (const elm of selectAll(root, selectors)) {
  240. return callback ? (callback(elm), null) : Promise.resolve(elm);
  241. }
  242. }
  243.  
  244. const observer = new MutationObserver(mCallback);
  245. observer.observe(root, {
  246. childList: true,
  247. subtree: true,
  248. attributes,
  249. });
  250.  
  251. let isPromise = !callback;
  252. return callback ? observer : new Promise((resolve, reject) => callback = resolve);
  253.  
  254. function mCallback(mutationList, observer) {
  255. const addedNodes = mutationList.reduce((an, mutation) => {
  256. switch (mutation.type) {
  257. case 'childList':
  258. an.push(...mutation.addedNodes);
  259. break;
  260. case 'attributes':
  261. an.push(mutation.target);
  262. break;
  263. }
  264. return an;
  265. }, []);
  266. const addedSelectorNodes = addedNodes.reduce((nodes, anode) => {
  267. if (anode.matches && match(anode, selectors)) {
  268. nodes.add(anode);
  269. }
  270. const childMatches = anode.querySelectorAll ? selectAll(anode, selectors) : [];
  271. for (const cm of childMatches) {
  272. nodes.add(cm);
  273. }
  274. return nodes;
  275. }, new Set());
  276. for (const node of addedSelectorNodes) {
  277. callback(node);
  278. isPromise && observer.disconnect();
  279. }
  280. }
  281.  
  282. function selectAll(elm, selectors) {
  283. !Array.isArray(selectors) && (selectors = [selectors]);
  284. return selectors.map(selector => [...$All(elm, selector)]).reduce((all, arr) => {
  285. all.push(...arr);
  286. return all;
  287. }, []);
  288. }
  289.  
  290. function select(elm, selectors) {
  291. const all = selectAll(elm, selectors);
  292. return all.length ? all[0] : null;
  293. }
  294.  
  295. function match(elm, selectors) {
  296. return !!elm.matches && selectors.some(selector => elm.matches(selector));
  297. }
  298. }
  299.  
  300. // Just stopPropagation and preventDefault
  301. function destroyEvent(e) {
  302. if (!e) {return false;};
  303. if (!e instanceof Event) {return false;};
  304. e.stopPropagation();
  305. e.preventDefault();
  306. }
  307.  
  308. // Object1[prop] ==> Object2[prop]
  309. function copyProp(obj1, obj2, prop) {obj1[prop] !== undefined && (obj2[prop] = obj1[prop]);}
  310. function copyProps(obj1, obj2, props) {(props || Object.keys(obj1)).forEach((prop) => (copyProp(obj1, obj2, prop)));}
  311.  
  312. // Argument parser with sorting and defaultValue support
  313. function parseArgs(args, rules, defaultValues=[]) {
  314. // args and rules should be array, but not just iterable (string is also iterable)
  315. if (!Array.isArray(args) || !Array.isArray(rules)) {
  316. throw new TypeError('parseArgs: args and rules should be array')
  317. }
  318.  
  319. // fill rules[0]
  320. (!Array.isArray(rules[0]) || rules[0].length === 1) && rules.splice(0, 0, []);
  321.  
  322. // max arguments length
  323. const count = rules.length - 1;
  324.  
  325. // args.length must <= count
  326. if (args.length > count) {
  327. throw new TypeError(`parseArgs: args has more elements(${args.length}) longer than ruless'(${count})`);
  328. }
  329.  
  330. // rules[i].length should be === i if rules[i] is an array, otherwise it should be a function
  331. for (let i = 1; i <= count; i++) {
  332. const rule = rules[i];
  333. if (Array.isArray(rule)) {
  334. if (rule.length !== i) {
  335. throw new TypeError(`parseArgs: rules[${i}](${rule}) should have ${i} numbers, but given ${rules[i].length}`);
  336. }
  337. if (!rule.every((num) => (typeof num === 'number' && num <= count))) {
  338. throw new TypeError(`parseArgs: rules[${i}](${rule}) should contain numbers smaller than count(${count}) only`);
  339. }
  340. } else if (typeof rule !== 'function') {
  341. throw new TypeError(`parseArgs: rules[${i}](${rule}) should be an array or a function.`)
  342. }
  343. }
  344.  
  345. // Parse
  346. const rule = rules[args.length];
  347. let parsed;
  348. if (Array.isArray(rule)) {
  349. parsed = [...defaultValues];
  350. for (let i = 0; i < rule.length; i++) {
  351. parsed[rule[i]-1] = args[i];
  352. }
  353. } else {
  354. parsed = rule(args, defaultValues);
  355. }
  356. return parsed;
  357. }
  358.  
  359. // escape str into javascript written format
  360. function escJsStr(str, quote='"') {
  361. str = str.replaceAll('\\', '\\\\').replaceAll(quote, '\\' + quote).replaceAll('\t', '\\t');
  362. str = quote === '`' ? str.replaceAll(/(\$\{[^\}]*\})/g, '\\$1') : str.replaceAll('\r', '\\r').replaceAll('\n', '\\n');
  363. return quote + str + quote;
  364. }
  365.  
  366. // Replace model text with no mismatching of replacing replaced text
  367. // e.g. replaceText('aaaabbbbccccdddd', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'}) === 'bbbbccccddddeeee'
  368. // replaceText('abcdAABBAA', {'BB': 'AA', 'AAAAAA': 'This is a trap!'}) === 'abcdAAAAAA'
  369. // replaceText('abcd{AAAA}BB}', {'{AAAA}': '{BB', '{BBBB}': 'This is a trap!'}) === 'abcd{BBBB}'
  370. // replaceText('abcd', {}) === 'abcd'
  371. /* Note:
  372. replaceText will replace in sort of replacer's iterating sort
  373. e.g. currently replaceText('abcdAABBAA', {'BBAA': 'TEXT', 'AABB': 'TEXT'}) === 'abcdAATEXT'
  374. but remember: (As MDN Web Doc said,) Although the keys of an ordinary Object are ordered now, this was
  375. not always the case, and the order is complex. As a result, it's best not to rely on property order.
  376. So, don't expect replaceText will treat replacer key-values in any specific sort. Use replaceText to
  377. replace irrelevance replacer keys only.
  378. */
  379. function replaceText(text, replacer) {
  380. if (Object.entries(replacer).length === 0) {return text;}
  381. const [models, targets] = Object.entries(replacer);
  382. const len = models.length;
  383. let text_arr = [{text: text, replacable: true}];
  384. for (const [model, target] of Object.entries(replacer)) {
  385. text_arr = replace(text_arr, model, target);
  386. }
  387. return text_arr.map((text_obj) => (text_obj.text)).join('');
  388.  
  389. function replace(text_arr, model, target) {
  390. const result_arr = [];
  391. for (const text_obj of text_arr) {
  392. if (text_obj.replacable) {
  393. const splited = text_obj.text.split(model);
  394. for (const part of splited) {
  395. result_arr.push({text: part, replacable: true});
  396. result_arr.push({text: target, replacable: false});
  397. }
  398. result_arr.pop();
  399. } else {
  400. result_arr.push(text_obj);
  401. }
  402. }
  403. return result_arr;
  404. }
  405. }
  406.  
  407. // Get a url argument from location.href
  408. // also recieve a function to deal the matched string
  409. // returns defaultValue if name not found
  410. // 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)
  411. function getUrlArgv(details) {
  412. const [name, url, defaultValue, dealFunc] = parseArgs([...arguments], [
  413. function(args, defaultValues) {
  414. const arg = args[0];
  415. return {
  416. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  417. 'object': () => ['name', 'url', 'defaultValue', 'dealFunc'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  418. }[typeof arg]();
  419. },
  420. [2,1],
  421. [2,1,3],
  422. [2,1,3,4]
  423. ], [null, location.href, null, a => a]);
  424.  
  425. if (name === null) { return null; }
  426.  
  427. const search = new URL(url).search;
  428. const objSearch = new URLSearchParams(search);
  429. const raw = objSearch.has(name) ? objSearch.get(name) : defaultValue;
  430. const argv = dealFunc(raw);
  431.  
  432. return argv;
  433. }
  434.  
  435. // Save dataURL to file
  436. function dl_browser(dataURL, filename) {
  437. const a = document.createElement('a');
  438. a.href = dataURL;
  439. a.download = filename;
  440. a.click();
  441. }
  442.  
  443. // File download function
  444. // details looks like the detail of GM_xmlhttpRequest
  445. // onload function will be called after file saved to disk
  446. function dl_GM(details) {
  447. if (!details.url || !details.name) {return false;};
  448.  
  449. // Configure request object
  450. const requestObj = {
  451. url: details.url,
  452. responseType: 'blob',
  453. onload: function(e) {
  454. // Save file
  455. dl_browser(URL.createObjectURL(e.response), details.name);
  456.  
  457. // onload callback
  458. details.onload ? details.onload(e) : function() {};
  459. }
  460. }
  461. if (details.onloadstart ) {requestObj.onloadstart = details.onloadstart;};
  462. if (details.onprogress ) {requestObj.onprogress = details.onprogress;};
  463. if (details.onerror ) {requestObj.onerror = details.onerror;};
  464. if (details.onabort ) {requestObj.onabort = details.onabort;};
  465. if (details.onreadystatechange) {requestObj.onreadystatechange = details.onreadystatechange;};
  466. if (details.ontimeout ) {requestObj.ontimeout = details.ontimeout;};
  467.  
  468. // Send request
  469. GM_xmlhttpRequest(requestObj);
  470. }
  471.  
  472. function AsyncManager() {
  473. const AM = this;
  474.  
  475. // Ongoing xhr count
  476. this.taskCount = 0;
  477.  
  478. // Whether generate finish events
  479. let finishEvent = false;
  480. Object.defineProperty(this, 'finishEvent', {
  481. configurable: true,
  482. enumerable: true,
  483. get: () => (finishEvent),
  484. set: (b) => {
  485. finishEvent = b;
  486. b && AM.taskCount === 0 && AM.onfinish && AM.onfinish();
  487. }
  488. });
  489.  
  490. // Add one task
  491. this.add = () => (++AM.taskCount);
  492.  
  493. // Finish one task
  494. this.finish = () => ((--AM.taskCount === 0 && AM.finishEvent && AM.onfinish && AM.onfinish(), AM.taskCount));
  495. }
  496.  
  497. const [testChecker, registerChecker, loadFuncs] = (function() {
  498. const checkers = {
  499. switch: value => value,
  500. url: value => location.href === value,
  501. path: value => location.pathname === value,
  502. regurl: value => !!location.href.match(value),
  503. regpath: value => !!location.pathname.match(value),
  504. starturl: value => location.href.startsWith(value),
  505. startpath: value => location.pathname.startsWith(value),
  506. func: value => value()
  507. };
  508.  
  509. // Check whether current page url matches FuncInfo.checker rule
  510. // This code is copy and modified from FunctionLoader.check
  511. function testChecker(checker) {
  512. if (!checker) {return true;}
  513. const values = Array.isArray(checker.value) ? checker.value : [checker.value];
  514. return values[checker.all ? 'every' : 'some'](value => {
  515. const type = checker.type;
  516. if (checkers.hasOwnProperty(type)) {
  517. try {
  518. return checkers[type](value);
  519. } catch (err) {
  520. DoLog(LogLevel.Error, 'Checker function raised an error');
  521. DoLog(LogLevel.Error, err);
  522. return false;
  523. }
  524. } else {
  525. DoLog(LogLevel.Error, 'Invalid checker type');
  526. return false;
  527. }
  528. });
  529. }
  530.  
  531. function registerChecker(name, func) {
  532. Assert(['Symbol', 'string', 'number'].includes(typeof name), 'name should be symbol, string or number');
  533. Assert(typeof func === 'function', 'func should be a function');
  534. checkers[name] = func;
  535. }
  536.  
  537. // Load all function-objs provided in funcs asynchronously, and merge return values into one return obj
  538. // funcobj: {[checker], [detectDom], func}
  539. function loadFuncs(oFuncs) {
  540. const returnObj = {};
  541.  
  542. oFuncs.forEach(oFunc => {
  543. if (!oFunc.checker || testChecker(oFunc.checker)) {
  544. if (oFunc.detectDom) {
  545. const selectors = Array.isArray(oFunc.detectDom) ? oFunc.detectDom : [oFunc.detectDom];
  546. Promise.all(selectors.map(selector => detectDom(selector))).then(node => execute(oFunc));
  547. } else {
  548. setTimeout(e => execute(oFunc), 0);
  549. }
  550. }
  551. });
  552.  
  553. return returnObj;
  554.  
  555. function execute(oFunc) {
  556. setTimeout(e => {
  557. const rval = oFunc.func(returnObj) || {};
  558. copyProps(rval, returnObj);
  559. }, 0);
  560. }
  561. }
  562.  
  563. return [testChecker, registerChecker, loadFuncs];
  564. }) ();
  565.  
  566. return [
  567. // Console & Debug
  568. LogLevel, DoLog, Err, Assert,
  569.  
  570. // DOM
  571. $, $All, $CrE, $AEL, $$CrE, addStyle, detectDom, destroyEvent,
  572.  
  573. // Data
  574. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  575.  
  576. // Environment & Browser
  577. getUrlArgv, dl_browser, dl_GM,
  578.  
  579. // Logic & Task
  580. AsyncManager, testChecker, registerChecker, loadFuncs
  581. ];
  582. })();