Config_Manager

设置获取配置的APIs

目前為 2023-10-12 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/476522/1263685/Config_Manager.js

  1. // ==UserScript==
  2. // @name Config_Manager
  3. // @namespace Violentmonkey Scripts
  4. // @grant GM_getValue
  5. // @grant GM_setValue
  6. // @grant GM_addValueChangeListener
  7. // @grant GM_registerMenuCommand
  8. // @grant GM_unregisterMenuCommand
  9. // @author axototl
  10. // @license AGPL-3.0-or-later
  11. // @description 设置获取配置的APIs
  12. // ==/UserScript==
  13. 'use strict';
  14.  
  15. const config = {};
  16. let register;
  17. const inplace = (() => {
  18. const id = "test";
  19. const cap = GM_registerMenuCommand("测试", Function.prototype, {id});
  20. GM_unregisterMenuCommand(cap);
  21. return (cap === id);
  22. })();
  23.  
  24. (() => {
  25. (() => {
  26. 'use strict';
  27. const _APIs = ["GM_getValue", "GM_setValue", "GM_addValueChangeListener", "GM_registerMenuCommand", "GM_unregisterMenuCommand"];
  28. for (const val in _APIs)
  29. if (eval("typeof " + val) === 'undefined') throw new Error("需要" + val + " API权限!!!");
  30. })();
  31.  
  32. const boolean_prefix = ["❌(已禁用) ", "✅(已启用) "];
  33. const int_family = ['uint', 'int'];
  34. register = ({name, default: def, type = "other", desc: prompts, tips: ipt, input: func = prompt, callback: listener = Function.prototype, init = false, autoClose = true}) => {
  35. let val = GM_getValue(name, def);
  36. config[name] = val;
  37. if (typeof init === 'function') init(name, val);
  38. if (int_family.includes(type)) {
  39. const judge = (type === 'uint') ? (s => (s|0) < 0) : (()=>false);
  40. if (func === prompt) {
  41. func = () => {
  42. let p;
  43. do {p = prompt(ipt);} while(isNaN(p) || judge(p));
  44. return p;
  45. };
  46. }
  47. type = 'other';
  48. }
  49. if (type === 'bool') {
  50. let cont;
  51. const reg = () => cont = GM_registerMenuCommand(boolean_prefix[val | 0] + prompts, () => GM_setValue(name, !val), {id: name, autoClose});
  52. if (true == init) listener(name, val, val, cont);
  53. GM_addValueChangeListener(name, !inplace ? (_1, ov, newval) => {
  54. config[name] = val = newval;
  55. GM_unregisterMenuCommand(cont);
  56. reg();
  57. listener(name, ov, newval, cont);
  58. } : (_1, ov, nv) => (config[name] = val = nv, reg(), listener(name, ov, nv, cont)));
  59. reg();
  60. } else if (type === "other") {
  61. const cont = GM_registerMenuCommand(prompts, () => GM_setValue(name, func()), {id: name, autoClose});
  62. if (true == init) listener(name, val, val, cont);
  63. GM_addValueChangeListener(name, (_1, ov, newval) => (config[name] = newval, listener(name, ov, newval, cont)));
  64. }
  65. console.debug(type, name, "\nRegistered!");
  66. };
  67. })();