UserscriptAPI

My API for userscripts.

Verze ze dne 13. 03. 2023. Zobrazit nejnovější verzi.

Tento skript by neměl být instalován přímo. Jedná se o knihovnu, kterou by měly jiné skripty využívat pomocí meta příkazu // @require https://update.greatest.deepsurf.us/scripts/409641/1161014/UserscriptAPI.js

  1. /* exported UserscriptAPI */
  2. /**
  3. * UserscriptAPI
  4. *
  5. * 需要引入模块方可工作,详见 `README.md`。
  6. * @version 2.2.1.20230314
  7. * @author Laster2800
  8. * @see {@link https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI UserscriptAPI}
  9. */
  10. class UserscriptAPI {
  11. /** @type {{[name: string]: Function}} 可访问模块 */
  12. static #modules = {}
  13. /** @type {string[]} 待添加模块样式队列 */
  14. #moduleCssQueue = []
  15.  
  16. /**
  17. * @param {Object} [options] 选项
  18. * @param {string} [options.id='default'] 标识符
  19. * @param {string} [options.label] 日志标签,为空时不设置标签
  20. * @param {Object} [options.wait] `wait` API 默认选项(默认值见构造器代码)
  21. * @param {Object} [options.wait.condition] `wait` 条件 API 默认选项
  22. * @param {Object} [options.wait.element] `wait` 元素 API 默认选项
  23. * @param {number} [options.fadeTime=400] UI 渐变时间
  24. */
  25. constructor(options) {
  26. this.options = {
  27. id: 'default',
  28. label: null,
  29. fadeTime: 400,
  30. ...options,
  31. wait: {
  32. condition: {
  33. callback: result => this.logger.info(result),
  34. interval: 100,
  35. timeout: 10000,
  36. onTimeout: options => this.logger[options.stopOnTimeout ? 'error' : 'warn']('executeAfterConditionPassed: TIMEOUT', options),
  37. stopOnTimeout: true,
  38. stopCondition: null,
  39. onStop: options => this.logger.error('executeAfterConditionPassed: STOP', options),
  40. stopInterval: 50,
  41. stopTimeout: 0,
  42. onError: (options, e) => this.logger.error('executeAfterConditionPassed: ERROR', options, e),
  43. stopOnError: true,
  44. timePadding: 0,
  45. ...options?.wait?.condition,
  46. },
  47. element: {
  48. base: document,
  49. exclude: null,
  50. callback: el => this.logger.info(el),
  51. subtree: true,
  52. multiple: false,
  53. repeat: false,
  54. throttleWait: 100,
  55. timeout: 10000,
  56. onTimeout: options => this.logger[options.stopOnTimeout ? 'error' : 'warn']('executeAfterElementLoaded: TIMEOUT', options),
  57. stopOnTimeout: false,
  58. stopCondition: null,
  59. onStop: options => this.logger.error('executeAfterElementLoaded: STOP', options),
  60. onError: (options, e) => this.logger.error('executeAfterElementLoaded: ERROR', options, e),
  61. stopOnError: true,
  62. timePadding: 0,
  63. ...options?.wait?.element,
  64. },
  65. },
  66. }
  67.  
  68. /** @type {UserscriptAPIDom} */
  69. this.dom = this.#getModuleInstance('dom')
  70. /** @type {UserscriptAPIMessage} */
  71. this.message = this.#getModuleInstance('message')
  72. /** @type {UserscriptAPIWait} */
  73. this.wait = this.#getModuleInstance('wait')
  74. /** @type {UserscriptAPIWeb} */
  75. this.web = this.#getModuleInstance('web')
  76.  
  77. if (!this.message) {
  78. this.message = {
  79. api: this,
  80. alert: this.base.alert,
  81. confirm: this.base.confirm,
  82. prompt: this.base.prompt,
  83. }
  84. }
  85.  
  86. for (const css of this.#moduleCssQueue) {
  87. this.base.addStyle(css)
  88. }
  89. }
  90.  
  91. /**
  92. * 注册模块
  93. * @param {string} name 模块名称
  94. * @param {Object} module 模块类
  95. */
  96. static registerModule(name, module) {
  97. this.#modules[name] = module
  98. }
  99.  
  100. /**
  101. * 获取模块实例
  102. * @param {string} name 模块名称
  103. * @returns {Object} 模块实例,无对应模块时返回 `null`
  104. */
  105. #getModuleInstance(name) {
  106. const module = UserscriptAPI.#modules[name]
  107. return module ? new module(this) : null
  108. }
  109.  
  110. /**
  111. * 初始化模块样式(仅应在模块构造器中使用)
  112. * @param {string} css 样式
  113. */
  114. initModuleStyle(css) {
  115. this.#moduleCssQueue.push(css)
  116. }
  117.  
  118. /**
  119. * UserscriptAPIBase
  120. * @version 1.2.1.20210813
  121. */
  122. base = new class UserscriptAPIBase {
  123. /**
  124. * @param {UserscriptAPI} api `UserscriptAPI`
  125. */
  126. constructor(api) {
  127. this.api = api
  128. }
  129.  
  130. /**
  131. * 添加样式
  132. * @param {string} css 样式
  133. * @param {Document} [doc=document] 文档
  134. * @returns {HTMLStyleElement} `<style>`
  135. */
  136. addStyle(css, doc = document) {
  137. const { api } = this
  138. const style = doc.createElement('style')
  139. style.className = `${api.options.id}-style`
  140. style.textContent = css
  141. const parent = doc.head || doc.documentElement
  142. if (parent) {
  143. parent.append(style)
  144. } else { // 极端情况下会出现,DevTools 网络+CPU 双限制可模拟
  145. api.wait?.waitForConditionPassed({
  146. condition: () => doc.head || doc.documentElement,
  147. timeout: 0,
  148. }).then(parent => parent.append(style))
  149. }
  150. return style
  151. }
  152.  
  153. /**
  154. * 判断给定 URL 是否匹配
  155. * @param {RegExp | RegExp[]} regex 用于判断是否匹配的正则表达式,或正则表达式数组
  156. * @param {'OR' | 'AND'} [mode='OR'] 匹配模式
  157. * @returns {boolean} 是否匹配
  158. */
  159. urlMatch(regex, mode = 'OR') {
  160. let result = false
  161. const { href } = location
  162. if (Array.isArray(regex)) {
  163. if (regex.length > 0) {
  164. if (mode === 'AND') {
  165. result = true
  166. for (const ex of regex) {
  167. if (!ex.test(href)) {
  168. result = false
  169. break
  170. }
  171. }
  172. } else if (mode === 'OR') {
  173. for (const ex of regex) {
  174. if (ex.test(href)) {
  175. result = true
  176. break
  177. }
  178. }
  179. }
  180. }
  181. } else {
  182. result = regex.test(href)
  183. }
  184. return result
  185. }
  186.  
  187. /**
  188. * 初始化 `urlchange` 事件
  189. * @example
  190. * window.addEventListener('urlchange', e => { ... })
  191. * window.addEventListener('urlchange', e => e.stopPropagation(), true)
  192. * window.onurlchange = function(e) { ... }
  193. * @see {@link https://stackoverflow.com/a/52809105 How to detect if URL has changed after hash in JavaScript}
  194. * @see {@link https://stackoverflow.com/a/69342637 Event bubbles before captured on `window`}
  195. */
  196. initUrlchangeEvent() {
  197. const win = typeof unsafeWindow === 'object' ? unsafeWindow : window
  198. if (win[Symbol.for('onurlchange')] === undefined) {
  199. let url = new URL(location.href)
  200. const dispatchEvent = () => {
  201. const event = new CustomEvent('urlchange', {
  202. detail: { prev: url, curr: new URL(location.href) },
  203. bubbles: true,
  204. })
  205. url = event.detail.curr
  206. if (typeof window.onurlchange === 'function') { // 若直接调用则 eventPhase 不对,且会有一些其他问题
  207. // 这一方案只能让事件处理器属性在最后被激活,但正确的顺序是:https://stackoverflow.com/a/49806959
  208. // 要实现正确的顺序,需用 defineProperty 定义 onurlchange,但 Tampermonkey 已经定义了该属性
  209. // 尽管目前 Tampermonkey 定义的属性是可写的,但为了向前兼容性及简化代码考虑,决定采用当前方案
  210. window.addEventListener('urlchange', window.onurlchange, { once: true })
  211. }
  212. document.dispatchEvent(event) // 在 window 上 dispatch 不能确保在冒泡前捕获,至少目前是这样
  213. }
  214.  
  215. history.pushState = (f => (...args) => {
  216. const ret = Reflect.apply(f, history, args)
  217. dispatchEvent()
  218. return ret
  219. })(history.pushState)
  220. history.replaceState = (f => (...args) => {
  221. const ret = Reflect.apply(f, history, args)
  222. dispatchEvent()
  223. return ret
  224. })(history.replaceState)
  225. window.addEventListener('popstate', () => {
  226. dispatchEvent()
  227. })
  228. win[Symbol.for('onurlchange')] = true
  229. }
  230. }
  231.  
  232. /**
  233. * 生成消抖函数
  234. * @param {Function} fn 目标函数
  235. * @param {number} [wait=0] 消抖延迟
  236. * @param {Object} [options] 选项
  237. * @param {boolean} [options.leading] 是否在延迟开始前调用目标函数
  238. * @param {boolean} [options.trailing=true] 是否在延迟结束后调用目标函数
  239. * @param {number} [options.maxWait=0] 最大延迟时间(非准确),`0` 表示禁用
  240. * @returns {Function} 消抖函数 `debounced`,可调用 `debounced.cancel()` 取消执行
  241. */
  242. debounce(fn, wait = 0, options = {}) {
  243. options = {
  244. leading: false,
  245. trailing: true,
  246. maxWait: 0,
  247. ...options,
  248. }
  249.  
  250. let tid = null
  251. let start = null
  252. let execute = null
  253. let callback = null
  254.  
  255. /** @this {*} thisArg */
  256. function debounced(...args) {
  257. execute = () => {
  258. Reflect.apply(fn, this, args)
  259. execute = null
  260. }
  261. callback = () => {
  262. if (options.trailing) {
  263. execute?.()
  264. }
  265. tid = null
  266. start = null
  267. }
  268.  
  269. if (tid) {
  270. clearTimeout(tid)
  271. if (options.maxWait > 0 && Date.now() - start > options.maxWait) {
  272. callback()
  273. }
  274. }
  275.  
  276. if (!tid && options.leading) {
  277. execute?.()
  278. }
  279.  
  280. if (!start) {
  281. start = Date.now()
  282. }
  283.  
  284. tid = setTimeout(callback, wait)
  285. }
  286.  
  287. debounced.cancel = function() {
  288. if (tid) {
  289. clearTimeout(tid)
  290. tid = null
  291. start = null
  292. }
  293. }
  294.  
  295. return debounced
  296. }
  297.  
  298. /**
  299. * 生成节流函数
  300. * @param {Function} fn 目标函数
  301. * @param {number} [wait=0] 节流延迟(非准确)
  302. * @returns {Function} 节流函数 `throttled`,可调用 `throttled.cancel()` 取消执行
  303. */
  304. throttle(fn, wait = 0) {
  305. return this.debounce(fn, wait, {
  306. leading: true,
  307. trailing: true,
  308. maxWait: wait,
  309. })
  310. }
  311.  
  312. /**
  313. * 创建基础提醒对话框(异步)
  314. *
  315. * 若没有引入 `message` 模块,可使用 `api.message.alert()` 引用该方法。
  316. * @param {string} msg 信息
  317. */
  318. alert(msg) {
  319. const { label } = this.api.options
  320. return new Promise(resolve => {
  321. resolve(alert(`${label ? `${label}\n\n` : ''}${msg}`))
  322. })
  323. }
  324.  
  325. /**
  326. * 创建基础确认对话框(异步)
  327. *
  328. * 若没有引入 `message` 模块,可使用 `api.message.confirm()` 引用该方法。
  329. * @param {string} msg 信息
  330. * @returns {Promise<boolean>} 用户输入
  331. */
  332. confirm(msg) {
  333. const { label } = this.api.options
  334. return new Promise(resolve => {
  335. resolve(confirm(`${label ? `${label}\n\n` : ''}${msg}`))
  336. })
  337. }
  338.  
  339. /**
  340. * 创建基础输入对话框(异步)
  341. *
  342. * 若没有引入 `message` 模块,可使用 `api.message.prompt()` 引用该方法。
  343. * @param {string} msg 信息
  344. * @param {string} [val] 默认值
  345. * @returns {Promise<string>} 用户输入
  346. */
  347. prompt(msg, val) {
  348. const { label } = this.api.options
  349. return new Promise(resolve => {
  350. resolve(prompt(`${label ? `${label}\n\n` : ''}${msg}`, val))
  351. })
  352. }
  353. }(this)
  354.  
  355. /**
  356. * UserscriptAPILogger
  357. * @version 1.2.0.20210925
  358. */
  359. logger = new class UserscriptAPILogger {
  360. #logCss = `
  361. background-color: black;
  362. color: white;
  363. border-radius: 2px;
  364. padding: 2px;
  365. margin-right: 4px;
  366. `
  367.  
  368. /**
  369. * @param {UserscriptAPI} api `UserscriptAPI`
  370. */
  371. constructor(api) {
  372. this.api = api
  373. }
  374.  
  375. /**
  376. * 打印格式化日志
  377. * @param {'info' | 'warn' | 'error'} fn 日志函数名
  378. * @param {*[]} message 日志信息
  379. */
  380. #log(fn, ...message) {
  381. const output = console[fn]
  382. const label = this.api.options.label ?? ''
  383. const causes = []
  384. let template = null
  385. if (message.length > 0) {
  386. const types = []
  387. for (const [idx, m] of message.entries()) {
  388. if (m) {
  389. types.push(typeof m === 'string' ? '%s' : '%o')
  390. if (m instanceof Error && m.cause !== undefined) {
  391. causes.push(m.cause)
  392. }
  393. } else {
  394. if (m === undefined) {
  395. message[idx] = '[undefined]'
  396. } else if (m === null) {
  397. message[idx] = '[null]'
  398. } else if (m === '') {
  399. message[idx] = '[empty string]'
  400. }
  401. types.push(typeof message[idx] === 'string' ? '%s' : '%o')
  402. }
  403. }
  404. template = types.join(', ')
  405. } else {
  406. template = '[undefined]'
  407. }
  408. output(`%c${label}%c${template}`, this.#logCss, null, ...message)
  409. for (const [idx, cause] of causes.entries()) {
  410. output(`%c${label}%c${idx + 1}-th error is caused by %o`, this.#logCss, null, cause)
  411. }
  412. }
  413.  
  414. /**
  415. * 打印日志
  416. * @param {*[]} message 日志信息
  417. */
  418. info(...message) {
  419. this.#log('info', ...message)
  420. }
  421.  
  422. /**
  423. * 打印警告日志
  424. * @param {*[]} message 警告日志信息
  425. */
  426. warn(...message) {
  427. this.#log('warn', ...message)
  428. }
  429.  
  430. /**
  431. * 打印错误日志
  432. * @param {*[]} message 错误日志信息
  433. */
  434. error(...message) {
  435. this.#log('error', ...message)
  436. }
  437. }(this)
  438. }