Luogu 题目外显示颜色

· · 科技·工程

我们平时看题目难度都要点进去,这十分麻烦,所以我们需要一个在外面显示题目难度的东西。直接上代码

::::info[主题]

// ==UserScript==
// @name         Luogu 题目颜色
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @description  仅保留洛谷题目难度颜色显示
// @author       realskc(精简)
// @match        https://www.luogu.com.cn/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

'use strict';

(function () {
    const problemDifficultyToColor = [
        [191, 191, 191],
        [254, 76, 97],
        [243, 156, 17],
        [255, 193, 22],
        [82, 196, 26],
        [19, 194, 194],
        [52, 152, 219],
        [157, 61, 207],
        [14, 29, 105]
    ];

    const problemToColorMap = new Map();

    class FetchRateLimiter {
        constructor(limit) {
            this.limit = limit;
            this.queue = [];
            this.queuePrior = [];
            this.active = false;
            this.requestCache = new Map();
        }

        process() {
            this.active = true;

            let resolve, reject, url;

            if (this.queuePrior.length > 0) {
                ({ resolve, reject, url } = this.queuePrior.shift());
            } else if (this.queue.length > 0) {
                ({ resolve, reject, url } = this.queue.shift());
            } else {
                this.active = false;
                return;
            }

            fetch(url)
                .then(resolve)
                .catch(reject);

            setTimeout(this.process.bind(this), this.limit);
        }

        push(url, prior) {
            if (this.requestCache.has(url)) {
                return this.requestCache.get(url);
            }

            const request = new Promise((resolve, reject) => {
                if (prior) {
                    this.queuePrior.push({ url, resolve, reject });
                } else {
                    this.queue.push({ url, resolve, reject });
                }

                if (!this.active) {
                    this.process();
                }
            }).then(response => response.text());

            this.requestCache.set(url, request);
            return request;
        }
    }

    const limiter = new FetchRateLimiter(300);

    function fillPracticeProblems(problemList) {
        if (!Array.isArray(problemList) || problemList.lgbot1Visited) {
            return;
        }

        for (const item of problemList) {
            if (
                item &&
                item.pid &&
                Number.isInteger(item.difficulty) &&
                problemDifficultyToColor[item.difficulty]
            ) {
                problemToColorMap.set(
                    item.pid,
                    `rgb(${problemDifficultyToColor[item.difficulty].join(',')})`
                );
            }
        }

        problemList.lgbot1Visited = true;
    }

    async function getProblemColor(problemid, prior = false) {
        if (window.location.href.startsWith('https://www.luogu.com.cn/record/list')) {
            if (typeof _feInstance !== 'undefined') {
                const resultList = _feInstance.currentData?.records?.result;

                if (Array.isArray(resultList) && !resultList.lgbot1Visited) {
                    for (const item of resultList) {
                        const problem = item.problem;

                        if (
                            problem &&
                            problem.pid &&
                            Number.isInteger(problem.difficulty) &&
                            problemDifficultyToColor[problem.difficulty]
                        ) {
                            problemToColorMap.set(
                                problem.pid,
                                `rgb(${problemDifficultyToColor[problem.difficulty].join(',')})`
                            );
                        }
                    }

                    resultList.lgbot1Visited = true;
                }
            }
        }

        if (/^https:\/\/www\.luogu\.com\.cn\/user\/\d+#practice$/.test(window.location.href)) {
            if (typeof _feInstance !== 'undefined') {
                fillPracticeProblems(_feInstance.currentData?.submittedProblems);
                fillPracticeProblems(_feInstance.currentData?.passedProblems);
            }
        }

        if (problemToColorMap.has(problemid)) {
            return problemToColorMap.get(problemid);
        }

        const url = '/problem/' + problemid;
        let data;

        try {
            data = await limiter.push(url, prior);
        } catch (error) {
            console.error('Error fetching problem data:', error, problemid);
            return;
        }

        const parser = new DOMParser();
        const doc = parser.parseFromString(data, 'text/html');

        let scriptText = '';
        for (const script of doc.querySelectorAll('script')) {
            scriptText += script.textContent;
        }

        const match = scriptText.match(/"difficulty":(\d+)/);
        if (!match) {
            return;
        }

        const difficulty = Number(match[1]);
        const colorArray = problemDifficultyToColor[difficulty];

        if (!colorArray) {
            return;
        }

        const color = `rgb(${colorArray.join(',')})`;
        problemToColorMap.set(problemid, color);

        return color;
    }

    function isProblemId(problemid) {
        if (problemid.startsWith('AT_')) {
            return true;
        }

        if (!/[a-zA-Z]/.test(problemid)) {
            return false;
        }

        if (!/[0-9]/.test(problemid)) {
            return false;
        }

        return true;
    }

    async function addProblemColor(item) {
        let problemid = item.href.split('/').pop();
        let prior = false;

        if (problemid.includes('?forum=')) {
            problemid = problemid.split('=').pop();
            prior = true;
        }

        problemid = problemid.split('?')[0];
        problemid = problemid.split('=').pop();

        if (item.matches('a[data-v-bade3303][data-v-4842157a]')) {
            if (problemid === 'javascript:void 0') {
                problemid = item.innerText.split(' ')[0];
            }
        }

        if (!isProblemId(problemid)) {
            return;
        }

        if (item.innerText.startsWith(problemid)) {
            const spanItem = item.children[0];

            if (
                spanItem &&
                spanItem.matches('span.pid') &&
                spanItem.innerText === problemid
            ) {
                const color = await getProblemColor(problemid, prior);
                if (!color) {
                    return;
                }

                spanItem.style.color = color;
                spanItem.style.fontWeight = 'bold';
            } else {
                const color = await getProblemColor(problemid, prior);
                if (!color) {
                    return;
                }

                const content = item.innerHTML;
                item.innerHTML = content.replace(
                    problemid,
                    `<b style="color: ${color};">${problemid}</b>`
                );
            }
        }
    }

    function addProblemsColor() {
        const observer = new MutationObserver(async mutationsList => {
            for (const mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    for (const addedNode of mutation.addedNodes) {
                        if (addedNode.nodeType !== Node.ELEMENT_NODE) {
                            continue;
                        }

                        if (addedNode.matches('a[href]')) {
                            addProblemColor(addedNode);
                        }

                        const newItems = addedNode.querySelectorAll('a[href]');
                        for (const newItem of newItems) {
                            addProblemColor(newItem);
                        }
                    }
                } else if (mutation.type === 'characterData') {
                    const parent = mutation.target.parentElement;

                    if (parent && parent.matches('span.pid')) {
                        const color = await getProblemColor(mutation.target.textContent);

                        if (color) {
                            parent.style.color = color;
                            parent.style.fontWeight = 'bold';
                        }
                    }
                }
            }
        });

        observer.observe(document, {
            childList: true,
            subtree: true,
            characterData: true
        });

        const nodelist = document.querySelectorAll('a[href]');
        for (const item of nodelist) {
            addProblemColor(item);
        }
    }

    setTimeout(addProblemsColor, 500);
})();

::::

灵感源自之前一款已经停更但我还在用的插件 luogu_bot1,我就用 AI 只保留了其颜色显示功能,也就是这个东西。

值得一提的是,这个插件会优先从本地读取,且有读取限速,所以并不会导致频繁访问洛谷。但如果你改了限速或者是频繁刷新可能会有问题(?)。同时在类似于练习页面的地方加载的会比较慢,虽然这也不是主要应用场景就对了。效果示例图: