UserscriptAPIWait

https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI

2022-12-10 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

بۇ قوليازمىنى بىۋاسىتە قاچىلاشقا بولمايدۇ. بۇ باشقا قوليازمىلارنىڭ ئىشلىتىشى ئۈچۈن تەمىنلەنگەن ئامبار بولۇپ، ئىشلىتىش ئۈچۈن مېتا كۆرسەتمىسىگە قىستۇرىدىغان كود: // @require https://update.greatest.deepsurf.us/scripts/432002/1126985/UserscriptAPIWait.js

  1. /**
  2. * UserscriptAPIWait
  3. *
  4. * 依赖于 `UserscriptAPI`。
  5. * @version 1.3.0.20221211
  6. * @author Laster2800
  7. * @see {@link https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI UserscriptAPI}
  8. */
  9. class UserscriptAPIWait {
  10. /**
  11. * @param {UserscriptAPI} api `UserscriptAPI`
  12. */
  13. constructor(api) {
  14. this.api = api
  15. }
  16.  
  17. /**
  18. * @typedef waitConditionOptions
  19. * @property {() => (* | Promise)} condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  20. * @property {(result: *) => void} [callback] 当达成条件时执行 `callback(result)`
  21. * @property {number} [interval] 检测时间间隔
  22. * @property {number} [timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  23. * @property {(options: waitConditionOptions) => void} [onTimeout] 检测超时时执行 `onTimeout()`
  24. * @property {boolean} [stopOnTimeout] 检测超时时是否终止检测
  25. * @property {() => (* | Promise)} [stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  26. * @property {(options: waitConditionOptions) => void} [onStop] 终止条件达成时执行 `onStop()`(包括终止条件的二次判断达成)
  27. * @property {number} [stopInterval] 终止条件二次判断期间的检测时间间隔
  28. * @property {number} [stopTimeout] 终止条件二次判断期间的检测超时时间,设置为 `0` 时禁用终止条件二次判断
  29. * @property {(options: waitConditionOptions, e: Error) => void} [onError] 条件检测过程中发生错误时执行 `onError(e)`
  30. * @property {boolean} [stopOnError] 条件检测过程中发生错误时,是否终止检测
  31. * @property {number} [timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  32. */
  33. /**
  34. * 在条件达成后执行操作
  35. *
  36. * 当条件达成后,如果不存在终止条件,那么直接执行 `callback(result)`。
  37. *
  38. * 当条件达成后,如果存在终止条件,且 `stopTimeout` 大于 0,则还会在接下来的 `stopTimeout` 时间内判断是否达成终止条件,称为终止条件的二次判断。如果在此期间,终止条件通过,则表示依然不达成条件,故执行 `onStop()` 而非 `callback(result)`。如果在此期间,终止条件一直失败,则顺利通过检测,执行 `callback(result)`。
  39. *
  40. * @param {waitConditionOptions} options 选项;缺失选项用 `api.options.wait.condition` 填充
  41. * @returns {() => boolean} 执行后终止检测的函数
  42. */
  43. executeAfterConditionPassed(options) {
  44. options = {
  45. ...this.api.options.wait.condition,
  46. ...options,
  47. }
  48. let stop = false
  49. let endTime = null
  50. if (options.timeout === 0) {
  51. endTime = 0
  52. } else {
  53. endTime = Math.max(Date.now() + options.timeout - options.timePadding, 1)
  54. }
  55. const task = async () => {
  56. if (stop) return
  57. let result = null
  58. try {
  59. result = await options.condition()
  60. } catch (e) {
  61. options.onError?.(options, e)
  62. if (options.stopOnError) {
  63. stop = true
  64. }
  65. }
  66. if (stop) return
  67. const stopResult = await options.stopCondition?.()
  68. if (stopResult) {
  69. stop = true
  70. options.onStop?.(options)
  71. } else if (endTime !== 0 && Date.now() > endTime) {
  72. if (options.stopOnTimeout) {
  73. stop = true
  74. } else {
  75. endTime = 0
  76. }
  77. options.onTimeout?.(options)
  78. } else if (result) {
  79. stop = true
  80. if (options.stopCondition && options.stopTimeout > 0) {
  81. this.executeAfterConditionPassed({
  82. condition: options.stopCondition,
  83. callback: () => options.onStop(options),
  84. interval: options.stopInterval,
  85. timeout: options.stopTimeout,
  86. onTimeout: () => options.callback(result),
  87. })
  88. } else {
  89. options.callback(result)
  90. }
  91. }
  92. if (!stop) {
  93. setTimeout(task, options.interval)
  94. }
  95. }
  96. setTimeout(async () => {
  97. if (stop) return
  98. await task()
  99. if (stop) return
  100. setTimeout(task, options.interval)
  101. }, options.timePadding)
  102. return () => { stop = true }
  103. }
  104.  
  105. /**
  106. * @typedef waitElementOptions
  107. * @property {string} selector 该选择器指定要等待加载的元素 `element`
  108. * @property {HTMLElement} [base] 基元素
  109. * @property {HTMLElement[]} [exclude] 若 `element` 在其中则跳过,并继续检测
  110. * @property {(element: HTMLElement) => void} [callback] 当 `element` 加载成功时执行 `callback(element)`
  111. * @property {boolean} [subtree] 是否将检测范围扩展为基元素的整棵子树
  112. * @property {boolean} [multiple] 若一次检测到多个目标元素,是否在所有元素上执行回调函数(否则只处理第一个结果)
  113. * @property {boolean} [repeat] `element` 加载成功后是否继续检测
  114. * @property {number} [throttleWait] 检测节流时间(非准确)
  115. * @property {number} [timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  116. * @property {(options: waitElementOptions) => void} [onTimeout] 检测超时时执行 `onTimeout()`
  117. * @property {boolean} [stopOnTimeout] 检测超时时是否终止检测
  118. * @property {() => (* | Promise)} [stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  119. * @property {(options: waitElementOptions) => void} [onStop] 终止条件达成时执行 `onStop()`
  120. * @property {(options: waitElementOptions, e: Error) => void} [onError] 检测过程中发生错误时执行 `onError(e)`
  121. * @property {boolean} [stopOnError] 检测过程中发生错误时,是否终止检测
  122. * @property {number} [timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  123. */
  124. /**
  125. * 在元素加载完成后执行操作
  126. *
  127. * 若执行时已存在对应元素,则针对已存在的对应元素同步执行 `callback(element)`。
  128. *
  129. * ```text
  130. * +──────────+────────+───────────────────────────────────+
  131. * multiple | repeat | 说明
  132. * +──────────+────────+───────────────────────────────────+
  133. * false | false | 查找第一个匹配元素,然后终止查找
  134. * true | false | 查找所有匹配元素,然后终止查找
  135. * false | true | 查找最后一个非标记匹配元素,并标记所有
  136. * | | 匹配元素,然后继续监听元素插入
  137. * true | true | 查找所有非标记匹配元素,并标记所有匹配
  138. * | | 元素,然后继续监听元素插入
  139. * +──────────+────────+───────────────────────────────────+
  140. * ```
  141. *
  142. * @param {waitElementOptions} options 选项;缺失选项用 `api.options.wait.element` 填充
  143. * @returns {() => boolean} 执行后终止检测的函数
  144. */
  145. executeAfterElementLoaded(options) {
  146. const { api } = this
  147. options = {
  148. ...api.options.wait.element,
  149. ...options,
  150. }
  151.  
  152. let loaded = false
  153. let stopped = false
  154. let tid = null // background timer id
  155. let insertUnrealElementListener = false
  156.  
  157. let excluded = null
  158. if (options.exclude) {
  159. excluded = new WeakSet(options.exclude)
  160. } else if (options.repeat) {
  161. excluded = new WeakSet()
  162. }
  163. const valid = el => !(excluded?.has(el))
  164.  
  165. const stop = () => {
  166. if (!stopped) {
  167. stopped = true
  168. ob.disconnect()
  169. if (insertUnrealElementListener) {
  170. document.removeEventListener('insert-unreal-element', core)
  171. insertUnrealElementListener = false
  172. }
  173. if (tid) {
  174. clearTimeout(tid)
  175. tid = null
  176. }
  177. }
  178. }
  179.  
  180. const singleTask = el => {
  181. let success = false
  182. try {
  183. if (valid(el)) {
  184. success = true // success 指查找成功,回调出错不影响
  185. options.repeat && excluded.add(el)
  186. options.callback(el)
  187. }
  188. } catch (e) {
  189. if (options.stopOnError) {
  190. throw e
  191. } else {
  192. options.onError?.(options, e)
  193. }
  194. }
  195. return success
  196. }
  197. const task = root => {
  198. let success = false
  199. if (options.multiple) {
  200. for (const el of root.querySelectorAll(options.selector)) {
  201. success = singleTask(el) || success
  202. }
  203. } else if (options.repeat) {
  204. const elements = root.querySelectorAll(options.selector)
  205. for (let i = elements.length - 1; i >= 0; i--) {
  206. const el = elements[i]
  207. if (success) {
  208. if (valid(el)) {
  209. excluded.add(el)
  210. }
  211. } else {
  212. success = singleTask(el)
  213. }
  214. }
  215. } else {
  216. const el = root.querySelector(options.selector)
  217. success = el && singleTask(el)
  218. }
  219. loaded ||= success
  220. if (loaded && !options.repeat) {
  221. stop()
  222. }
  223. return success
  224. }
  225. const throttledTask = options.throttleWait > 0 ? api.base.throttle(task, options.throttleWait) : task
  226.  
  227. const core = () => {
  228. if (stopped) return
  229. try {
  230. if (options.stopCondition?.()) {
  231. stop()
  232. options.onStop?.(options)
  233. return
  234. }
  235. throttledTask(options.base)
  236. } catch (e) {
  237. options.onError?.(options, e)
  238. if (options.stopOnError) {
  239. stop()
  240. }
  241. }
  242. }
  243. const ob = new MutationObserver(core)
  244.  
  245. const main = () => {
  246. if (stopped) return
  247. try {
  248. if (options.stopCondition?.()) {
  249. stop()
  250. options.onStop?.(options)
  251. return
  252. }
  253. task(options.base)
  254. } catch (e) {
  255. options.onError?.(options, e)
  256. if (options.stopOnError) {
  257. stop()
  258. }
  259. }
  260. if (stopped) return
  261. ob.observe(options.base, {
  262. childList: true,
  263. subtree: options.subtree,
  264. })
  265. // 重复加入的元素可能存在于 DocumentFragment 中,需要特殊的检测手段
  266. if (options.repeat) {
  267. initInsertUnrealElementEventDispatcher()
  268. document.addEventListener('insert-unreal-element', core)
  269. insertUnrealElementListener = true
  270. }
  271. if (options.timeout > 0) {
  272. tid = setTimeout(() => {
  273. if (stopped) return
  274. tid = null
  275. if (!loaded) {
  276. if (options.stopOnTimeout) {
  277. stop()
  278. }
  279. options.onTimeout?.(options)
  280. } else { // 只要检测到,无论重复与否,都不算超时;需永久检测必须设 timeout 为 0
  281. stop()
  282. }
  283. }, Math.max(options.timeout - options.timePadding, 0))
  284. }
  285. }
  286. options.timePadding > 0 ? setTimeout(main, options.timePadding) : main()
  287. return stop
  288.  
  289. /**
  290. * 初始化 insert-unreal-element 事件分发器
  291. *
  292. * 覆盖一系列插入节点的方法,以便在插入 DocumentFragment 向 doucment 分发 insert-unreal-element 事件。
  293. */
  294. function initInsertUnrealElementEventDispatcher() {
  295. if (unsafeWindow[Symbol.for('insert-unreal-element-event-dispatcher')] === undefined) {
  296. const dispatch = (target, fns) => {
  297. for (const fn of fns) {
  298. const orig = target.prototype[fn]
  299. target.prototype[fn] = function(...args) {
  300. const result = Reflect.apply(orig, this, args)
  301. for (const arg of args) {
  302. if (arg instanceof DocumentFragment) {
  303. document.dispatchEvent(new CustomEvent('insert-unreal-element'))
  304. break
  305. }
  306. }
  307. return result
  308. }
  309. }
  310. }
  311. dispatch(Node, ['appendChild', 'insertBefore', 'replaceChild'])
  312. dispatch(Element, ['after', 'append', 'before', 'insertAdjacentElement', 'prepend', 'replaceWith'])
  313. unsafeWindow[Symbol.for('insert-unreal-element-event-dispatcher')] = true
  314. }
  315. }
  316. }
  317.  
  318. /**
  319. * 等待条件达成
  320. *
  321. * 执行细节类似于 {@link executeAfterConditionPassed}。在原来执行 `callback(result)` 的地方执行 `resolve(result)`,被终止或超时执行 `reject()`。
  322. * @param {Object} options 选项;缺失选项用 `api.options.wait.condition` 填充
  323. * @param {() => (* | Promise)} options.condition 条件,当 `condition()` 返回的 `result` 为真值时达成条件
  324. * @param {number} [options.interval] 检测时间间隔
  325. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  326. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  327. * @param {() => (* | Promise)} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  328. * @param {number} [options.stopInterval] 终止条件二次判断期间的检测时间间隔
  329. * @param {number} [options.stopTimeout] 终止条件二次判断期间的检测超时时间,设置为 `0` 时禁用终止条件二次判断
  330. * @param {boolean} [options.stopOnError] 条件检测过程中发生错误时,是否终止检测
  331. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  332. * @returns {Promise} `result`
  333. * @throws 等待超时、达成终止条件、等待错误时抛出
  334. * @see executeAfterConditionPassed
  335. */
  336. waitForConditionPassed(options) {
  337. const { api } = this
  338. return new Promise((resolve, reject) => {
  339. this.executeAfterConditionPassed({
  340. ...options,
  341. callback: result => resolve(result),
  342. onTimeout: options => {
  343. if (options.stopOnTimeout) {
  344. reject(new Error('waitForConditionPassed: TIMEOUT', { cause: options }))
  345. } else {
  346. api.logger.warn('waitForConditionPassed: TIMEOUT', options)
  347. }
  348. },
  349. onStop: options => {
  350. reject(new Error('waitForConditionPassed: STOP', { cause: options }))
  351. },
  352. onError: (options, e) => {
  353. reject(new Error('waitForConditionPassed: ERROR', { cause: [options, e] }))
  354. },
  355. })
  356. })
  357. }
  358.  
  359. /**
  360. * 等待元素加载完成
  361. *
  362. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  363. * @param {Object} options 选项;缺失选项用 `api.options.wait.element` 填充
  364. * @param {string} options.selector 该选择器指定要等待加载的元素 `element`
  365. * @param {HTMLElement} [options.base] 基元素
  366. * @param {HTMLElement[]} [options.exclude] 若 `element` 在其中则跳过,并继续检测
  367. * @param {boolean} [options.subtree] 是否将检测范围扩展为基元素的整棵子树
  368. * @param {number} [options.throttleWait] 检测节流时间(非准确)
  369. * @param {number} [options.timeout] 检测超时时间,检测时间超过该值时终止检测;设置为 `0` 时永远不会超时
  370. * @param {() => (* | Promise)} [options.stopCondition] 终止条件,当 `stopCondition()` 返回的 `stopResult` 为真值时终止检测
  371. * @param {() => void} [options.onStop] 终止条件达成时执行 `onStop()`
  372. * @param {boolean} [options.stopOnTimeout] 检测超时时是否终止检测
  373. * @param {boolean} [options.stopOnError] 检测过程中发生错误时,是否终止检测
  374. * @param {number} [options.timePadding] 等待 `timePadding`ms 后才开始执行;包含在 `timeout` 中,因此不能大于 `timeout`
  375. * @returns {Promise<HTMLElement>} `element`
  376. * @throws 等待超时、达成终止条件、等待错误时抛出
  377. * @see executeAfterElementLoaded
  378. */
  379. waitForElementLoaded(options) {
  380. const { api } = this
  381. return new Promise((resolve, reject) => {
  382. this.executeAfterElementLoaded({
  383. ...options,
  384. callback: element => resolve(element),
  385. onTimeout: options => {
  386. if (options.stopOnTimeout) {
  387. reject(new Error('waitForElementLoaded: TIMEOUT', { cause: options }))
  388. } else {
  389. api.logger.warn('waitForElementLoaded: TIMEOUT', options)
  390. }
  391. },
  392. onStop: options => {
  393. reject(new Error('waitForElementLoaded: STOP', { cause: options }))
  394. },
  395. onError: (options, e) => {
  396. reject(new Error('waitForElementLoaded: ERROR', { cause: [options, e] }))
  397. },
  398. })
  399. })
  400. }
  401.  
  402. /**
  403. * 元素加载选择器
  404. *
  405. * 执行细节类似于 {@link executeAfterElementLoaded}。在原来执行 `callback(element)` 的地方执行 `resolve(element)`,被终止或超时执行 `reject()`。
  406. * @param {string} selector 该选择器指定要等待加载的元素 `element`
  407. * @param {HTMLElement} [base=api.options.wait.element.base] 基元素
  408. * @param {boolean} [stopOnTimeout=api.options.wait.element.stopOnTimeout] 检测超时时是否终止检测
  409. * @returns {Promise<HTMLElement>} `element`
  410. * @throws 等待超时、达成终止条件、等待错误时抛出
  411. * @see executeAfterElementLoaded
  412. */
  413. $(selector, base = this.api.options.wait.element.base, stopOnTimeout = this.api.options.wait.element.stopOnTimeout) {
  414. const { api } = this
  415. return new Promise((resolve, reject) => {
  416. this.executeAfterElementLoaded({
  417. selector, base, stopOnTimeout,
  418. callback: element => resolve(element),
  419. onTimeout: options => {
  420. if (options.stopOnTimeout) {
  421. reject(new Error('waitQuerySelector: TIMEOUT', { cause: options }))
  422. } else {
  423. api.logger.warn('waitQuerySelector: TIMEOUT', options)
  424. }
  425. },
  426. onStop: options => {
  427. reject(new Error('waitQuerySelector: STOP', { cause: options }))
  428. },
  429. onError: (options, e) => {
  430. reject(new Error('waitQuerySelector: ERROR', { cause: [options, e] }))
  431. },
  432. })
  433. })
  434. }
  435. }
  436.  
  437. /* global UserscriptAPI */
  438. // eslint-disable-next-line no-lone-blocks
  439. { UserscriptAPI.registerModule('wait', UserscriptAPIWait) }