Basic Functions (For userscripts)

Useful functions for myself

As of 2023-02-10. 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/1147868/Basic%20Functions%20%28For%20userscripts%29.js

  1. /* eslint-disable no-multi-spaces */
  2.  
  3. // ==UserScript==
  4. // @name Basic Functions (For userscripts)
  5. // @name:zh-CN 常用函数(用户脚本)
  6. // @name:en Basic Functions (For userscripts)
  7. // @namespace PY-DNG Userscripts
  8. // @version 0.4
  9. // @description Useful functions for myself
  10. // @description:zh-CN 自用函数
  11. // @description:en Useful functions for myself
  12. // @author PY-DNG
  13. // @license GPL-license
  14. // ==/UserScript==
  15.  
  16. let [
  17. // Console & Debug
  18. LogLevel, DoLog, Err,
  19.  
  20. // DOM
  21. $, $All, $CrE, $AEL, addStyle, destroyEvent,
  22.  
  23. // Data
  24. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  25.  
  26. // Environment & Browser
  27. getUrlArgv, dl_browser, dl_GM,
  28.  
  29. // Logic & Task
  30. AsyncManager,
  31. ] = (function() {
  32. // function DoLog() {}
  33. // Arguments: level=LogLevel.Info, logContent, logger='log'
  34. const [LogLevel, DoLog] = (function() {
  35. const LogLevel = {
  36. None: 0,
  37. Error: 1,
  38. Success: 2,
  39. Warning: 3,
  40. Info: 4,
  41. };
  42.  
  43. return [LogLevel, DoLog];
  44. function DoLog() {
  45. // Get window
  46. const win = (typeof(unsafeWindow) === 'object' && unsafeWindow !== null) ? unsafeWindow : window;
  47.  
  48. const LogLevelMap = {};
  49. LogLevelMap[LogLevel.None] = {
  50. prefix: '',
  51. color: 'color:#ffffff'
  52. }
  53. LogLevelMap[LogLevel.Error] = {
  54. prefix: '[Error]',
  55. color: 'color:#ff0000'
  56. }
  57. LogLevelMap[LogLevel.Success] = {
  58. prefix: '[Success]',
  59. color: 'color:#00aa00'
  60. }
  61. LogLevelMap[LogLevel.Warning] = {
  62. prefix: '[Warning]',
  63. color: 'color:#ffa500'
  64. }
  65. LogLevelMap[LogLevel.Info] = {
  66. prefix: '[Info]',
  67. color: 'color:#888888'
  68. }
  69. LogLevelMap[LogLevel.Elements] = {
  70. prefix: '[Elements]',
  71. color: 'color:#000000'
  72. }
  73.  
  74. // Current log level
  75. DoLog.logLevel = (win.isPY_DNG && win.userscriptDebugging) ? LogLevel.Info : LogLevel.Warning; // Info Warning Success Error
  76.  
  77. // Log counter
  78. DoLog.logCount === undefined && (DoLog.logCount = 0);
  79.  
  80. // Get args
  81. let [level, logContent, logger] = parseArgs([...arguments], [
  82. [2],
  83. [1,2],
  84. [1,2,3]
  85. ], [LogLevel.Info, 'DoLog initialized.', 'log']);
  86.  
  87. let msg = '%c' + LogLevelMap[level].prefix + (typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + (LogLevelMap[level].prefix ? ' ' : '');
  88. let subst = LogLevelMap[level].color;
  89.  
  90. switch (typeof(logContent)) {
  91. case 'string':
  92. msg += '%s';
  93. break;
  94. case 'number':
  95. msg += '%d';
  96. break;
  97. default:
  98. msg += '%o';
  99. break;
  100. }
  101.  
  102. // Log when log level permits
  103. if (level <= DoLog.logLevel) {
  104. // Log to console when log level permits
  105. if (level <= DoLog.logLevel) {
  106. if (++DoLog.logCount > 512) {
  107. console.clear();
  108. DoLog.logCount = 0;
  109. }
  110. console[logger](msg, subst, logContent);
  111. }
  112. }
  113. }
  114. }) ();
  115.  
  116. // type: [Error, TypeError]
  117. function Err(msg, type=0) {
  118. throw new [Error, TypeError][type]((typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + msg);
  119. }
  120.  
  121. // Basic functions
  122. // querySelector
  123. function $() {
  124. switch(arguments.length) {
  125. case 2:
  126. return arguments[0].querySelector(arguments[1]);
  127. break;
  128. default:
  129. return document.querySelector(arguments[0]);
  130. }
  131. }
  132. // querySelectorAll
  133. function $All() {
  134. switch(arguments.length) {
  135. case 2:
  136. return arguments[0].querySelectorAll(arguments[1]);
  137. break;
  138. default:
  139. return document.querySelectorAll(arguments[0]);
  140. }
  141. }
  142. // createElement
  143. function $CrE() {
  144. switch(arguments.length) {
  145. case 2:
  146. return arguments[0].createElement(arguments[1]);
  147. break;
  148. default:
  149. return document.createElement(arguments[0]);
  150. }
  151. }
  152. // addEventListener
  153. function $AEL(...args) {
  154. const target = args.shift();
  155. return target.addEventListener.apply(target, args);
  156. }
  157.  
  158. // Append a style text to document(<head>) with a <style> element
  159. // arguments: css | parentElement, css | parentElement, css, attributes
  160. function addStyle() {
  161. // Get arguments
  162. const [parentElement, css, attributes] = parseArgs([...arguments], [
  163. [2],
  164. [1,2],
  165. [1,2,3]
  166. ], [document.head, '', {}]);
  167.  
  168. // Make <style>
  169. const style = $CrE("style");
  170. style.textContent = css;
  171. for (const [name, val] of Object.entries(attributes)) {
  172. style.setAttribute(name, val);
  173. }
  174.  
  175. // Append to parentElement
  176. parentElement.appendChild(style);
  177. return style;
  178. }
  179.  
  180. // Just stopPropagation and preventDefault
  181. function destroyEvent(e) {
  182. if (!e) {return false;};
  183. if (!e instanceof Event) {return false;};
  184. e.stopPropagation();
  185. e.preventDefault();
  186. }
  187.  
  188. // Object1[prop] ==> Object2[prop]
  189. function copyProp(obj1, obj2, prop) {obj1[prop] !== undefined && (obj2[prop] = obj1[prop]);}
  190. function copyProps(obj1, obj2, props) {(props || Object.keys(obj1)).forEach((prop) => (copyProp(obj1, obj2, prop)));}
  191.  
  192. function parseArgs(args, rules, defaultValues=[]) {
  193. // args and rules should be array, but not just iterable (string is also iterable)
  194. if (!Array.isArray(args) || !Array.isArray(rules)) {
  195. throw new TypeError('parseArgs: args and rules should be array')
  196. }
  197.  
  198. // fill rules[0]
  199. (!Array.isArray(rules[0]) || rules[0].length === 1) && rules.splice(0, 0, []);
  200.  
  201. // max arguments length
  202. const count = rules.length - 1;
  203.  
  204. // args.length must <= count
  205. if (args.length > count) {
  206. throw new TypeError(`parseArgs: args has more elements(${args.length}) longer than ruless'(${count})`);
  207. }
  208.  
  209. // rules[i].length should be === i if rules[i] is an array, otherwise it should be a function
  210. for (let i = 1; i <= count; i++) {
  211. const rule = rules[i];
  212. if (Array.isArray(rule)) {
  213. if (rule.length !== i) {
  214. throw new TypeError(`parseArgs: rules[${i}](${rule}) should have ${i} numbers, but given ${rules[i].length}`);
  215. }
  216. if (!rule.every((num) => (typeof num === 'number' && num <= count))) {
  217. throw new TypeError(`parseArgs: rules[${i}](${rule}) should contain numbers smaller than count(${count}) only`);
  218. }
  219. } else if (typeof rule !== 'function') {
  220. throw new TypeError(`parseArgs: rules[${i}](${rule}) should be an array or a function.`)
  221. }
  222. }
  223.  
  224. // Parse
  225. const rule = rules[args.length];
  226. let parsed;
  227. if (Array.isArray(rule)) {
  228. parsed = [...defaultValues];
  229. for (let i = 0; i < rule.length; i++) {
  230. parsed[rule[i]-1] = args[i];
  231. }
  232. } else {
  233. parsed = rule(args, defaultValues);
  234. }
  235. return parsed;
  236. }
  237.  
  238. // escape str into javascript written format
  239. function escJsStr(str, quote='"') {
  240. str = str.replaceAll('\\', '\\\\').replaceAll(quote, '\\' + quote).replaceAll('\t', '\\t');
  241. str = quote === '`' ? str.replaceAll(/(\$\{[^\}]*\})/g, '\\$1') : str.replaceAll('\r', '\\r').replaceAll('\n', '\\n');
  242. return quote + str + quote;
  243. }
  244.  
  245. // Replace model text with no mismatching of replacing replaced text
  246. // e.g. replaceText('aaaabbbbccccdddd', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'}) === 'bbbbccccddddeeee'
  247. // replaceText('abcdAABBAA', {'BB': 'AA', 'AAAAAA': 'This is a trap!'}) === 'abcdAAAAAA'
  248. // replaceText('abcd{AAAA}BB}', {'{AAAA}': '{BB', '{BBBB}': 'This is a trap!'}) === 'abcd{BBBB}'
  249. // replaceText('abcd', {}) === 'abcd'
  250. /* Note:
  251. replaceText will replace in sort of replacer's iterating sort
  252. e.g. currently replaceText('abcdAABBAA', {'BBAA': 'TEXT', 'AABB': 'TEXT'}) === 'abcdAATEXT'
  253. but remember: (As MDN Web Doc said,) Although the keys of an ordinary Object are ordered now, this was
  254. not always the case, and the order is complex. As a result, it's best not to rely on property order.
  255. So, don't expect replaceText will treat replacer key-values in any specific sort. Use replaceText to
  256. replace irrelevance replacer keys only.
  257. */
  258. function replaceText(text, replacer) {
  259. if (Object.entries(replacer).length === 0) {return text;}
  260. const [models, targets] = Object.entries(replacer);
  261. const len = models.length;
  262. let text_arr = [{text: text, replacable: true}];
  263. for (const [model, target] of Object.entries(replacer)) {
  264. text_arr = replace(text_arr, model, target);
  265. }
  266. return text_arr.map((text_obj) => (text_obj.text)).join('');
  267.  
  268. function replace(text_arr, model, target) {
  269. const result_arr = [];
  270. for (const text_obj of text_arr) {
  271. if (text_obj.replacable) {
  272. const splited = text_obj.text.split(model);
  273. for (const part of splited) {
  274. result_arr.push({text: part, replacable: true});
  275. result_arr.push({text: target, replacable: false});
  276. }
  277. result_arr.pop();
  278. } else {
  279. result_arr.push(text_obj);
  280. }
  281. }
  282. return result_arr;
  283. }
  284. }
  285.  
  286. // Get a url argument from lacation.href
  287. // also recieve a function to deal the matched string
  288. // returns defaultValue if name not found
  289. // Args: {url=location.href, name, dealFunc=((a)=>{return a;}), defaultValue=null} or 'name'
  290. function getUrlArgv(details) {
  291. typeof(details) === 'string' && (details = {name: details});
  292. typeof(details) === 'undefined' && (details = {});
  293. if (!details.name) {return null;};
  294.  
  295. const url = details.url ? details.url : location.href;
  296. const name = details.name ? details.name : '';
  297. const dealFunc = details.dealFunc ? details.dealFunc : ((a)=>{return a;});
  298. const defaultValue = details.defaultValue ? details.defaultValue : null;
  299. const matcher = new RegExp('[\\?&]' + name + '=([^&#]+)');
  300. const result = url.match(matcher);
  301. const argv = result ? dealFunc(result[1]) : defaultValue;
  302.  
  303. return argv;
  304. }
  305.  
  306. // Save dataURL to file
  307. function dl_browser(dataURL, filename) {
  308. const a = document.createElement('a');
  309. a.href = dataURL;
  310. a.download = filename;
  311. a.click();
  312. }
  313.  
  314. // File download function
  315. // details looks like the detail of GM_xmlhttpRequest
  316. // onload function will be called after file saved to disk
  317. function dl_GM(details) {
  318. if (!details.url || !details.name) {return false;};
  319.  
  320. // Configure request object
  321. const requestObj = {
  322. url: details.url,
  323. responseType: 'blob',
  324. onload: function(e) {
  325. // Save file
  326. dl_browser(URL.createObjectURL(e.response), details.name);
  327.  
  328. // onload callback
  329. details.onload ? details.onload(e) : function() {};
  330. }
  331. }
  332. if (details.onloadstart ) {requestObj.onloadstart = details.onloadstart;};
  333. if (details.onprogress ) {requestObj.onprogress = details.onprogress;};
  334. if (details.onerror ) {requestObj.onerror = details.onerror;};
  335. if (details.onabort ) {requestObj.onabort = details.onabort;};
  336. if (details.onreadystatechange) {requestObj.onreadystatechange = details.onreadystatechange;};
  337. if (details.ontimeout ) {requestObj.ontimeout = details.ontimeout;};
  338.  
  339. // Send request
  340. GM_xmlhttpRequest(requestObj);
  341. }
  342.  
  343. function AsyncManager() {
  344. const AM = this;
  345.  
  346. // Ongoing xhr count
  347. this.taskCount = 0;
  348.  
  349. // Whether generate finish events
  350. let finishEvent = false;
  351. Object.defineProperty(this, 'finishEvent', {
  352. configurable: true,
  353. enumerable: true,
  354. get: () => (finishEvent),
  355. set: (b) => {
  356. finishEvent = b;
  357. b && AM.taskCount === 0 && AM.onfinish && AM.onfinish();
  358. }
  359. });
  360.  
  361. // Add one task
  362. this.add = () => (++AM.taskCount);
  363.  
  364. // Finish one task
  365. this.finish = () => ((--AM.taskCount === 0 && AM.finishEvent && AM.onfinish && AM.onfinish(), AM.taskCount));
  366. }
  367.  
  368. return [
  369. // Console & Debug
  370. LogLevel, DoLog, Err,
  371.  
  372. // DOM
  373. $, $All, $CrE, $AEL, addStyle, destroyEvent,
  374.  
  375. // Data
  376. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  377.  
  378. // Environment & Browser
  379. getUrlArgv, dl_browser, dl_GM,
  380.  
  381. // Logic & Task
  382. AsyncManager,
  383. ];
  384. })();