Greasy Fork is available in English.

UserscriptAPI

My API for userscripts.

Verze ze dne 13. 08. 2022. 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/1081030/UserscriptAPI.js

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