常用函数(用户脚本)

自用函数

目前为 2022-12-05 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/456034/1124967/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.1
  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, trace=false
  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, trace] = parseArgs([...arguments], [
  82. [2],
  83. [1,2],
  84. [1,2,3]
  85. ], [LogLevel.Info, 'DoLog initialized.', false]);
  86.  
  87. // Log when log level permits
  88. if (level <= DoLog.logLevel) {
  89. let msg = '%c' + LogLevelMap[level].prefix + (typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + (LogLevelMap[level].prefix ? ' ' : '');
  90. let subst = LogLevelMap[level].color;
  91.  
  92. switch (typeof(logContent)) {
  93. case 'string':
  94. msg += '%s';
  95. break;
  96. case 'number':
  97. msg += '%d';
  98. break;
  99. default:
  100. msg += '%o';
  101. break;
  102. }
  103.  
  104. if (++DoLog.logCount > 512) {
  105. console.clear();
  106. DoLog.logCount = 0;
  107. }
  108. console[trace ? 'trace' : 'log'](msg, subst, logContent);
  109. }
  110. }
  111. }) ();
  112.  
  113. // type: [Error, TypeError]
  114. function Err(msg, type=0) {
  115. throw new [Error, TypeError][type]((typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + msg);
  116. }
  117.  
  118. // Basic functions
  119. // querySelector
  120. function $() {
  121. switch(arguments.length) {
  122. case 2:
  123. return arguments[0].querySelector(arguments[1]);
  124. break;
  125. default:
  126. return document.querySelector(arguments[0]);
  127. }
  128. }
  129. // querySelectorAll
  130. function $All() {
  131. switch(arguments.length) {
  132. case 2:
  133. return arguments[0].querySelectorAll(arguments[1]);
  134. break;
  135. default:
  136. return document.querySelectorAll(arguments[0]);
  137. }
  138. }
  139. // createElement
  140. function $CrE() {
  141. switch(arguments.length) {
  142. case 2:
  143. return arguments[0].createElement(arguments[1]);
  144. break;
  145. default:
  146. return document.createElement(arguments[0]);
  147. }
  148. }
  149. // addEventListener
  150. function $AEL(...args) {
  151. const target = args.shift();
  152. return target.addEventListener.apply(target, args);
  153. }
  154.  
  155. // Append a style text to document(<head>) with a <style> element
  156. function addStyle(css, id) {
  157. const style = document.createElement("style");
  158. id && (style.id = id);
  159. style.textContent = css;
  160. for (const elm of document.querySelectorAll('#'+id)) {
  161. elm.parentElement && elm.parentElement.removeChild(elm);
  162. }
  163. document.head.appendChild(style);
  164. }
  165.  
  166. // Just stopPropagation and preventDefault
  167. function destroyEvent(e) {
  168. if (!e) {return false;};
  169. if (!e instanceof Event) {return false;};
  170. e.stopPropagation();
  171. e.preventDefault();
  172. }
  173.  
  174. // Object1[prop] ==> Object2[prop]
  175. function copyProp(obj1, obj2, prop) {obj1[prop] !== undefined && (obj2[prop] = obj1[prop]);}
  176. function copyProps(obj1, obj2, props) {(props || Object.keys(obj1)).forEach((prop) => (copyProp(obj1, obj2, prop)));}
  177.  
  178. function parseArgs(args, rules, defaultValues=[]) {
  179. // args and rules should be array, but not just iterable (string is also iterable)
  180. if (!Array.isArray(args) || !Array.isArray(rules)) {
  181. throw new TypeError('parseArgs: args and rules should be array')
  182. }
  183.  
  184. // fill rules[0]
  185. (!Array.isArray(rules[0]) || rules[0].length === 1) && rules.splice(0, 0, []);
  186.  
  187. // max arguments length
  188. const count = rules.length - 1;
  189.  
  190. // args.length must <= count
  191. if (args.length > count) {
  192. throw new TypeError(`parseArgs: args has more elements(${args.length}) longer than ruless'(${count})`);
  193. }
  194.  
  195. // rules[i].length should be === i if rules[i] is an array, otherwise it should be a function
  196. for (let i = 1; i <= count; i++) {
  197. const rule = rules[i];
  198. if (Array.isArray(rule)) {
  199. if (rule.length !== i) {
  200. throw new TypeError(`parseArgs: rules[${i}](${rule}) should have ${i} numbers, but given ${rules[i].length}`);
  201. }
  202. if (!rule.every((num) => (typeof num === 'number' && num <= count))) {
  203. throw new TypeError(`parseArgs: rules[${i}](${rule}) should contain numbers smaller than count(${count}) only`);
  204. }
  205. } else if (typeof rule !== 'function') {
  206. throw new TypeError(`parseArgs: rules[${i}](${rule}) should be an array or a function.`)
  207. }
  208. }
  209.  
  210. // Parse
  211. const rule = rules[args.length];
  212. let parsed;
  213. if (Array.isArray(rule)) {
  214. parsed = [...defaultValues];
  215. for (let i = 0; i < rule.length; i++) {
  216. parsed[rule[i]-1] = args[i];
  217. }
  218. } else {
  219. parsed = rule(args, defaultValues);
  220. }
  221. return parsed;
  222. }
  223.  
  224. // escape str into javascript written format
  225. function escJsStr(str, quote='"') {
  226. str = str.replaceAll('\\', '\\\\').replaceAll(quote, '\\' + quote);
  227. quote === '`' && (str = str.replaceAll(/(\$\{[^\}]*\})/g, '\\$1'));
  228. return quote + str + quote;
  229. }
  230.  
  231. // Replace model text with no mismatching of replacing replaced text
  232. // e.g. replaceText('aaaabbbbccccdddd', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'}) === 'bbbbccccddddeeee'
  233. // replaceText('abcdAABBAA', {'BB': 'AA', 'AAAAAA': 'This is a trap!'}) === 'abcdAAAAAA'
  234. // replaceText('abcd{AAAA}BB}', {'{AAAA}': '{BB', '{BBBB}': 'This is a trap!'}) === 'abcd{BBBB}'
  235. // replaceText('abcd', {}) === 'abcd'
  236. /* Note:
  237. replaceText will replace in sort of replacer's iterating sort
  238. e.g. currently replaceText('abcdAABBAA', {'BBAA': 'TEXT', 'AABB': 'TEXT'}) === 'abcdAATEXT'
  239. but remember: (As MDN Web Doc said,) Although the keys of an ordinary Object are ordered now, this was
  240. not always the case, and the order is complex. As a result, it's best not to rely on property order.
  241. So, don't expect replaceText will treat replacer key-values in any specific sort. Use replaceText to
  242. replace irrelevance replacer keys only.
  243. */
  244. function replaceText(text, replacer) {
  245. if (Object.entries(replacer).length === 0) {return text;}
  246. const [models, targets] = Object.entries(replacer);
  247. const len = models.length;
  248. let text_arr = [{text: text, replacable: true}];
  249. for (const [model, target] of Object.entries(replacer)) {
  250. text_arr = replace(text_arr, model, target);
  251. }
  252. return text_arr.map((text_obj) => (text_obj.text)).join('');
  253.  
  254. function replace(text_arr, model, target) {
  255. const result_arr = [];
  256. for (const text_obj of text_arr) {
  257. if (text_obj.replacable) {
  258. const splited = text_obj.text.split(model);
  259. for (const part of splited) {
  260. result_arr.push({text: part, replacable: true});
  261. result_arr.push({text: target, replacable: false});
  262. }
  263. result_arr.pop();
  264. } else {
  265. result_arr.push(text_obj);
  266. }
  267. }
  268. return result_arr;
  269. }
  270. }
  271.  
  272. // Get a url argument from lacation.href
  273. // also recieve a function to deal the matched string
  274. // returns defaultValue if name not found
  275. // Args: {url=location.href, name, dealFunc=((a)=>{return a;}), defaultValue=null} or 'name'
  276. function getUrlArgv(details) {
  277. typeof(details) === 'string' && (details = {name: details});
  278. typeof(details) === 'undefined' && (details = {});
  279. if (!details.name) {return null;};
  280.  
  281. const url = details.url ? details.url : location.href;
  282. const name = details.name ? details.name : '';
  283. const dealFunc = details.dealFunc ? details.dealFunc : ((a)=>{return a;});
  284. const defaultValue = details.defaultValue ? details.defaultValue : null;
  285. const matcher = new RegExp('[\\?&]' + name + '=([^&#]+)');
  286. const result = url.match(matcher);
  287. const argv = result ? dealFunc(result[1]) : defaultValue;
  288.  
  289. return argv;
  290. }
  291.  
  292. // Save dataURL to file
  293. function dl_browser(dataURL, filename) {
  294. const a = document.createElement('a');
  295. a.href = dataURL;
  296. a.download = filename;
  297. a.click();
  298. }
  299.  
  300. // File download function
  301. // details looks like the detail of GM_xmlhttpRequest
  302. // onload function will be called after file saved to disk
  303. function dl_GM(details) {
  304. if (!details.url || !details.name) {return false;};
  305.  
  306. // Configure request object
  307. const requestObj = {
  308. url: details.url,
  309. responseType: 'blob',
  310. onload: function(e) {
  311. // Save file
  312. dl_browser(URL.createObjectURL(e.response), details.name);
  313.  
  314. // onload callback
  315. details.onload ? details.onload(e) : function() {};
  316. }
  317. }
  318. if (details.onloadstart ) {requestObj.onloadstart = details.onloadstart;};
  319. if (details.onprogress ) {requestObj.onprogress = details.onprogress;};
  320. if (details.onerror ) {requestObj.onerror = details.onerror;};
  321. if (details.onabort ) {requestObj.onabort = details.onabort;};
  322. if (details.onreadystatechange) {requestObj.onreadystatechange = details.onreadystatechange;};
  323. if (details.ontimeout ) {requestObj.ontimeout = details.ontimeout;};
  324.  
  325. // Send request
  326. GM_xmlhttpRequest(requestObj);
  327. }
  328.  
  329. function AsyncManager() {
  330. const AM = this;
  331.  
  332. // Ongoing xhr count
  333. this.taskCount = 0;
  334.  
  335. // Whether generate finish events
  336. let finishEvent = false;
  337. Object.defineProperty(this, 'finishEvent', {
  338. configurable: true,
  339. enumerable: true,
  340. get: () => (finishEvent),
  341. set: (b) => {
  342. finishEvent = b;
  343. b && AM.taskCount === 0 && AM.onfinish && AM.onfinish();
  344. }
  345. });
  346.  
  347. // Add one task
  348. this.add = () => (++AM.taskCount);
  349.  
  350. // Finish one task
  351. this.finish = () => ((--AM.taskCount === 0 && AM.finishEvent && AM.onfinish && AM.onfinish(), AM.taskCount));
  352. }
  353.  
  354. return [
  355. // Console & Debug
  356. LogLevel, DoLog, Err,
  357.  
  358. // DOM
  359. $, $All, $CrE, $AEL, addStyle, destroyEvent,
  360.  
  361. // Data
  362. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  363.  
  364. // Environment & Browser
  365. getUrlArgv, dl_browser, dl_GM,
  366.  
  367. // Logic & Task
  368. AsyncManager,
  369. ];
  370. })();