Yinr-libs

Useful functions for yinr

Från och med 2023-02-06. Se den senaste versionen.

Detta skript bör inte installeras direkt. Det är ett bibliotek för andra skript att inkludera med meta-direktivet // @require https://updategf.qytechs.cn/scripts/458769/1146261/Yinr-libs.js

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name               Yinr-libs
// @namespace          https://yinr.cc/
// @version            0.0.4
// @description        Useful functions for yinr
// @author             Yinr
// @license            GPL-v3
// ==/UserScript==

/**
 * Useful functions for yinr
 * ### 脚本常用功能库
 * 1. `YinrLibs.launchObserver`: 创建 DOM 监听
 * 2. `YinrLibs.sleep`: 等待延时
 * 3. `YinrLibs.generateTextFile`: 生成文本文件下载链接
 * ### 使用
 * ```
 * // @require https://greasyfork.org/scripts/458769-yinr-libs/code/Yinr-libs.js
 * ```
 * @module YinrLibs
 */
const YinrLibs = (function() {
    'use strict'

    return {
        /** 创建 DOM 监听
         * @param {Object} option
         * @param {(Element | string)} option.parentNode MutationObserver 绑定的 DOM 对象
         * @param {string} option.selector 需要监听变化的 selector
         * @param {voidCallback} [option.failCallback=callback] selector 不存在时执行的回调函数
         * @param {MutationCallback} [option.successCallback=null] selector 对象发生 Mutation 事件时执行的回调函数
         * @param {boolean} [option.stopWhenSuccess=true] 执行一次 `successCallback` 后立即解除监听
         * @param {MutationObserverInit} [option.config={childList: true, subtree: true}] MutationObserver 配置参数
         */
        launchObserver ({
            parentNode,
            selector,
            failCallback = null,
            successCallback = null,
            stopWhenSuccess = true,
            config = { childList: true, subtree: true }
        }) {
            if (!parentNode) return
            /** @type {MutationCallback} */
            const observeFunc = mutationList => {
                if (!document.querySelector(selector)) {
                    if (failCallback) failCallback()
                    return
                }
                if (stopWhenSuccess) observer.disconnect()

                mutationList.itemFilter = (fn, type = 'addedNodes') => mutationList.map(i => Array.from(i[type]).filter(fn)).reduce((arr, val) => arr.concat(val), [])

                if (successCallback) successCallback(mutationList)
            }
            const observer = new MutationObserver(observeFunc)
            observer.observe(parentNode, config)
        },

        /** 等待延时函数,默认固定延时 1s
         * @param {number} [timeoutMin=1000] 最少随机等待时间(ms)
         * @param {number} [timeoutMax=timeMin] 最多随机等待时间(ms)
         * @returns {Promise<true>}
         * @example
         * await sleep() // 默认等待 1s
         * await sleep(1000, 3000) // 随机等待 1-3s
         * sleep().then(() => { callbackFn() }) // 等待 1s 后执行 callbackFn()
         */
        sleep(timeoutMin = 1000, timeoutMax = timeoutMin) {
            return new Promise((resolve) => {
                const timeout = timeoutMin === timeoutMax ? timeoutMin : Math.floor(Math.random() * (timeoutMax - timeoutMin) + timeoutMin)
                setTimeout(() => { resolve(true) }, timeout);
            })
        },

        /** 创建文本文件,返回可下载文件链接
         * @param {string} text 文本文件内容文本
         * @param {string} [type='text/plain'] 文件 MIME 类型
         * @returns {string}
         * @example
         * // 生成 json 文件下载链接,并使用 GM_download 函数下载
         * let url = generateTextFile('{ "data": 1 }', 'application/json')
         * GM_download(url, 'data.json')
         */
        generateTextFile(text, type = 'text/plain') {
            const data = new Blob([text], { type })
            return URL.createObjectURL(data)
        }
    }
})();